In order to test my parser, I would like to have an abstraction which either read a file line by line or a String line by line (split at \n).
I currently can do the file with the example shown here, but I'm wondering if there a way to make the read_lines more generic.
This is what I have for now:
use std::ops::Generator;
use std::fs::File;
use std::io::{self, BufRead, Read};
use std::path::Path;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
pub fn reader(path: &str) -> impl Generator<Yield=String, Return=()> + '_ {
move || {
if let Ok(lines) = read_lines(path) {
for line in lines {
if let Ok(l) = line {
yield l
}
}
}
}
}
Read is implemented for both File and &[u8], so if you have a function with a signature like this, you can call it as both parse(file) and parse(string.as_bytes()):