~ajk/bsr

2765a1bb20c5e679bf4b18ca785840b610138352 — Andrew Kay 3 years ago 65f77ec
Refactor Bitstream iterator and implement ExactSizeIterator
1 files changed, 46 insertions(+), 9 deletions(-)

M src/bitstream.rs
M src/bitstream.rs => src/bitstream.rs +46 -9
@@ 131,36 131,48 @@ mod read_header_tests {
    }
}

pub struct Bitstream<'a, R> {
pub struct Bitstream<R> {
    reader: R,
    header: &'a Header,
    counter: u32
    length: usize,
    counter: usize
}

impl<'a, R> Bitstream<'a, R> {
    pub fn new(reader: R, header: &'a Header) -> Bitstream<'a, R> {
        Bitstream { reader, header, counter: 0 }
impl<R> Bitstream<R> {
    pub fn new(reader: R, header: &Header) -> Bitstream<R> {
        let length = (header.bitstream_length / 4) as usize;

        Bitstream { reader, length, counter: 0 }
    }
}

impl<'a, R: Read> Iterator for Bitstream<'a, R> {
impl<R: Read> Iterator for Bitstream<R> {
    type Item = io::Result<u32>;

    fn next(&mut self) -> Option<io::Result<u32>> {
        if self.counter < self.header.bitstream_length {
        if self.counter < self.length {
            let word = read_u32(&mut self.reader);

            if let Err(e) = word {
                return Some(Err(e));
            }

            self.counter += 4;
            self.counter += 1;

            Some(word)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = self.length - self.counter;

        (size, Some(size))
    }
}

impl<R: Read> ExactSizeIterator for Bitstream<R> {
    // Uses default len() implementation.
}

#[cfg(test)]


@@ 204,6 216,31 @@ mod bitstream_tests {

        assert!(bitstream.collect::<Result<Vec<_>, _>>().is_err());
    }

    #[test]
    fn test_len() {
        let buffer: [u8; 16] = [
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04
        ];

        let header = Header {
            design_name: "design".to_string(),
            part_name: "part".to_string(),
            design_date: "date".to_string(),
            design_time: "time".to_string(),
            bitstream_length: 16
        };

        let mut bitstream = Bitstream::new(buffer.as_ref(), &header);

        assert_eq!(bitstream.len(), 4);

        for _ in 0..4 {
            bitstream.next();
        }

        assert_eq!(bitstream.len(), 0);
    }
}

fn read_u8<R: Read>(reader: &mut R) -> io::Result<u8> {