reaves/
lib.rs

1use std::io::{Read, Result, Write, BufRead, Seek, SeekFrom};
2
3/// Delegates reads from the wrapped `Read` and writes a copy to the wrapped `Write`
4#[derive(Debug, Clone)]
5pub struct Reaves<R: Read, W: Write> {
6    r: R,
7    w: W,
8}
9
10impl<R: Read, W: Write> Reaves<R, W> {
11    pub fn new(r: R, w: W) -> Self {
12        Self { r, w }
13    }
14
15    pub fn into_inner(self) -> (R, W) {
16        (self.r, self.w)
17    }
18}
19
20impl<R: Read, W: Write> Read for Reaves<R, W> {
21    #[inline]
22    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
23        let ret = self.r.read(buf)?;
24        if ret > 0 {
25            self.w.write_all(&buf[..ret])?;
26        }
27        Ok(ret)
28    }
29}
30
31impl<R: BufRead, W: Write> BufRead for Reaves<R, W> {
32    fn fill_buf(&mut self) -> Result<&[u8]> {
33        self.r.fill_buf()
34    }
35
36    fn consume(&mut self, amt: usize) {
37        self.r.consume(amt)
38    }
39}
40
41impl<R: Read + Seek, W: Write> Seek for Reaves<R, W> {
42    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
43        self.r.seek(pos)
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use std::io::{Cursor, Read};
50
51    use super::Reaves;
52
53    #[test]
54    fn test() {
55        let input = b"Hello world";
56        let mut output = Vec::<u8>::new();
57
58        let r = Cursor::new(input);
59        let w = &mut output;
60
61        let mut reaves = Reaves::new(r, w);
62
63        let mut verify = vec![];
64        assert_eq!(
65            reaves
66                .read_to_end(&mut verify)
67                .expect("Cannot fail reading a Vec"),
68            input.len()
69        );
70        assert_eq!(&verify, input);
71        assert_eq!(&output, input);
72    }
73}