use { crate::{listing::Kind, Error, Listing, MAGIC}, std::{ io::{ErrorKind, Read, Seek}, iter::Iterator, }, }; #[derive(Debug)] pub struct ListingStream { pub length: u32, reader: R, } impl Iterator for ListingStream { type Item = Result; fn next(&mut self) -> Option { match Listing::read(&mut self.reader) { Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => None, Ok(f) => match f.kind { Kind::Eof => None, _ => Some(Ok(f)), }, x => Some(x), } } } impl ListingStream { pub fn new(mut reader: R) -> Result { let mut buf = [0; 11]; reader.read_exact(&mut buf)?; let length = u32::from_le_bytes(buf[7..].try_into()?); if buf[0..7] == MAGIC { Ok(Self { length, reader }) } else { Err(Error::InvalidMagic) } } pub fn list(&mut self) -> Result, Error> { let mut list = vec![]; for listing in self { let listing = listing?; list.push(listing); } list.sort_unstable(); Ok(list) } }