aboutsummaryrefslogtreecommitdiff
path: root/src/chain.rs
blob: a8014b80b6ff5e1a9ae8f24e65fd6c4baae942a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use std::io::{Read, Result, Write};

pub struct Chain<T> {
    elem: Vec<T>,
    index: usize,
}

impl<T: Read> Read for Chain<T> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        loop {
            match self.elem.get_mut(self.index) {
                Some(ref mut r) => {
                    match try!(r.read(buf)) {
                        0 => self.index += 1,
                        n => return Ok(n),
                    }
                }
                None => return Ok(0),
            }
        }
    }
}

impl<T: Write> Write for Chain<T> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        loop {
            match self.elem.get_mut(self.index) {
                Some(ref mut r) => {
                    match try!(r.write(buf)) {
                        0 => self.index += 1,
                        n => return Ok(n),
                    }
                }
                None => return Ok(0),
            }
        }
    }

    fn flush(&mut self) -> Result<()> {
        match self.elem.get_mut(self.index) {
            Some(ref mut r) => r.flush(),
            None => Ok(()),
        }
    }
}

impl<T> Chain<T> {
    pub fn new(elem: Vec<T>) -> Chain<T> {
        Chain {
            index: 0,
            elem: elem,
        }
    }
}