File tree Expand file tree Collapse file tree 2 files changed +14
-10
lines changed Expand file tree Collapse file tree 2 files changed +14
-10
lines changed Original file line number Diff line number Diff line change 1- use std:: io:: { copy, stdout} ;
1+ use std:: {
2+ collections:: VecDeque ,
3+ io:: { copy, stdout} ,
4+ } ;
25
36use lib:: io:: MultiReader ;
47
58fn main ( ) -> std:: io:: Result < ( ) > {
69 let header = "---- HEADER ----\n " . as_bytes ( ) ;
710 let content = "Example of MultiReader\n " . as_bytes ( ) ;
811 let footer = "---- FOOTER ----\n " . as_bytes ( ) ;
9- let mut multi_reader = MultiReader :: new ( vec ! [ header, content, footer] ) ;
12+ let mut multi_reader = MultiReader :: new ( VecDeque :: from ( vec ! [ header, content, footer] ) ) ;
1013 copy ( & mut multi_reader, & mut stdout ( ) ) ?;
1114
1215 Ok ( ( ) )
Original file line number Diff line number Diff line change 1- use std:: io:: Read ;
1+ use std:: { collections :: VecDeque , io:: Read } ;
22
33/// Takes multiple `std::io::Read` at once.
44/// This is inspired by `io.MultiReader` in Go.
@@ -22,31 +22,32 @@ use std::io::Read;
2222/// }
2323/// ```
2424pub struct MultiReader < R : Read > {
25- readers : Vec < R > ,
25+ readers : VecDeque < R > ,
2626 /// Points to where we read right now.
27- pos : usize ,
27+ current : Option < R > ,
2828}
2929
3030impl < R : Read > MultiReader < R > {
3131 /// Creates `MultiReader`. `pos` is set to 0 by default.
32- pub fn new ( readers : Vec < R > ) -> Self {
33- Self { readers, pos : 0 }
32+ pub fn new ( mut readers : VecDeque < R > ) -> Self {
33+ let current = readers. pop_front ( ) ;
34+ Self { readers, current }
3435 }
3536}
3637
3738impl < R : Read > Read for MultiReader < R > {
3839 fn read ( & mut self , buf : & mut [ u8 ] ) -> std:: io:: Result < usize > {
3940 loop {
40- match self . readers . get_mut ( self . pos ) {
41- Some ( r) => {
41+ match self . current . take ( ) {
42+ Some ( ref mut r) => {
4243 let n = r. read ( buf) ?;
4344 if n > 0 {
4445 return Ok ( n) ;
4546 }
4647 }
4748 None => return Ok ( 0 ) ,
4849 }
49- self . pos += 1 ;
50+ self . current = self . readers . pop_front ( ) ;
5051 }
5152 }
5253}
You can’t perform that action at this time.
0 commit comments