bread_cli/
raw.rs

1use crate::byte_writer::ByteWriter;
2use crate::error::{InError, OutError};
3use crate::util;
4use std::io::{Bytes, Read, Write};
5
6/// An iterator over Result<u8,[InError]>
7///
8/// Reads raw bytes from the input stream
9///
10/// [InError]: crate::error::InError
11pub struct Reader<R: Read> {
12    in_bytes: Bytes<R>,
13}
14
15impl<R: Read> Reader<R> {
16    pub fn new(read: R) -> Self {
17        Reader {
18            in_bytes: read.bytes(),
19        }
20    }
21}
22
23impl<R: Read> Iterator for Reader<R> {
24    type Item = Result<u8, InError>;
25    fn next(&mut self) -> Option<Self::Item> {
26        match self.in_bytes.next()? {
27            Ok(b) => Some(Ok(b)),
28            Err(e) => Some(Err(InError::StdIO(e))),
29        }
30    }
31}
32
33/// Writes raw bytes to the output stream
34pub struct Writer<W: Write> {
35    out_bytes: W,
36}
37
38impl<W: Write> Writer<W> {
39    pub fn new(out_bytes: W) -> Self {
40        Writer { out_bytes }
41    }
42}
43
44impl<W: Write> ByteWriter for Writer<W> {
45    fn write(&mut self, byte: u8) -> Result<(), OutError> {
46        util::write(&mut self.out_bytes, &[byte], 1)
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn read() {
56        let input = [10u8, 128u8, 255u8, 4u8];
57        let mut reader = Reader::new(input.as_slice());
58        for b in input {
59            assert_eq!(b, reader.next().unwrap().unwrap());
60        }
61        assert!(reader.next().is_none());
62    }
63
64    #[test]
65    fn write() {
66        let input = 127u8;
67        let mut output = [0u8; 1];
68        let mut writer = Writer::new(output.as_mut_slice());
69        writer.write(input).unwrap();
70        assert_eq!(input, output[0]);
71    }
72}