File tree 2 files changed +14
-10
lines changed
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
+ } ;
2
5
3
6
use lib:: io:: MultiReader ;
4
7
5
8
fn main ( ) -> std:: io:: Result < ( ) > {
6
9
let header = "---- HEADER ----\n " . as_bytes ( ) ;
7
10
let content = "Example of MultiReader\n " . as_bytes ( ) ;
8
11
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] ) ) ;
10
13
copy ( & mut multi_reader, & mut stdout ( ) ) ?;
11
14
12
15
Ok ( ( ) )
Original file line number Diff line number Diff line change 1
- use std:: io:: Read ;
1
+ use std:: { collections :: VecDeque , io:: Read } ;
2
2
3
3
/// Takes multiple `std::io::Read` at once.
4
4
/// This is inspired by `io.MultiReader` in Go.
@@ -22,31 +22,32 @@ use std::io::Read;
22
22
/// }
23
23
/// ```
24
24
pub struct MultiReader < R : Read > {
25
- readers : Vec < R > ,
25
+ readers : VecDeque < R > ,
26
26
/// Points to where we read right now.
27
- pos : usize ,
27
+ current : Option < R > ,
28
28
}
29
29
30
30
impl < R : Read > MultiReader < R > {
31
31
/// 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 }
34
35
}
35
36
}
36
37
37
38
impl < R : Read > Read for MultiReader < R > {
38
39
fn read ( & mut self , buf : & mut [ u8 ] ) -> std:: io:: Result < usize > {
39
40
loop {
40
- match self . readers . get_mut ( self . pos ) {
41
- Some ( r) => {
41
+ match self . current . take ( ) {
42
+ Some ( ref mut r) => {
42
43
let n = r. read ( buf) ?;
43
44
if n > 0 {
44
45
return Ok ( n) ;
45
46
}
46
47
}
47
48
None => return Ok ( 0 ) ,
48
49
}
49
- self . pos += 1 ;
50
+ self . current = self . readers . pop_front ( ) ;
50
51
}
51
52
}
52
53
}
You can’t perform that action at this time.
0 commit comments