I have some code which parses files, very similar to the following:
use std::io::Cursor;
use std::io::Result;
use std::io::Read;
fn main() {
let v1 = [1, 2, 3, 4, 5];
let mut c1 = Cursor::new(v1); // *
println!("{:?}", read_one(&mut c1)); // 1
println!("{:?}", read_three(&mut c1)); // 2, 3, 4
println!("{:?}", read_one(&mut c1)); // 5
println!("{:?}", read_one(&mut c1)); // eof
}
fn read_one<R: Read>(r: &mut R) -> Result<u8> {
let mut buf = [0; 1];
r.read_exact(&mut buf)?;
Ok(buf[0])
}
fn read_three<R: Read>(r: &mut R) -> Result<[u8; 3]> {
let mut buf = [0; 3];
r.read_exact(&mut buf)?;
Ok(buf)
}
Here, read_one
and read_three
take a Read
trait, get some bytes off of it, and return the result. I can then read the bytes piece by piece.
I'd like to convert this code to using an iterator instead. That is, have the *
line be
let mut i1 = v1.iter();
Trying this, I ran into problems where I couldn't find functions to easily extract a number of items (analogous to read_exact
) or otherwise partially process an iterator. It seems most of the iterator functions are designed to consume the content entirely.
Is the iterator just a bad tool for this or am I using it wrong? If the latter, how do I convert this code to use iterators instead?