I’d like to implement an Iterator that does read a text-file line-wise, examine the read lines, modify them as needed and return some slices that are not owned. Though I read the advise that all data must be owned by someone in the end I thought such an implementation should be possible if one knows how to handle lifetimes and annotations.
If I’m wrong please tell me because: I’m totally lost with my first attempt that does no IO at all but won’t even compile:
Is it worth amending this?
// rustc 1.88.0 (6b00bc388 2025-06-23)
use std::fs::File;
use std::io::{BufReader, Error};
use std::path::Path;
fn main() {
let tfuf = TextfileUnfolder::new(Path::new("../iCalendaR/radicale/calendar_many.ics"), 1024).unwrap();
assert_eq!(&tfuf.next().unwrap(), "Hello");
}
struct TextfileUnfolder<'a> {
file_name: &'a str,
reader: BufReader<File>,
buffer: String,
lines_read: usize,
}
impl TextfileUnfolder<'_> {
pub fn new<'a>(p: &'a Path, init_buffer_size: usize) -> Result<TextfileUnfolder<'a>, Error> {
Ok(TextfileUnfolder {
file_name: p.file_name().unwrap().to_str().unwrap(),
reader: BufReader::new(File::open(p)?),
buffer: String::with_capacity(init_buffer_size),
lines_read: 0,
})
}
}
impl<'a> Iterator for &'a TextfileUnfolder<'_> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.lines_read += 1;
Some("Hello")
}
}