Created
December 7, 2022 21:38
-
-
Save brsc2909/88ee072d99ad7707fc5c72c1bf621ffa to your computer and use it in GitHub Desktop.
Rust File reader that can iterate over lines of file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() -> std::io::Result<()>{ | |
for item in file_reader::BufReader::open("file.txt")? { | |
println!("{}", item?); | |
} | |
Ok(()) | |
} | |
mod file_reader { | |
use std::{ | |
fs::File, | |
io::{self, prelude::*}, | |
rc::Rc, | |
}; | |
pub struct BufReader { | |
reader: io::BufReader<File>, | |
buf: Rc<String>, | |
} | |
fn new_buf() -> Rc<String> { | |
Rc::new(String::with_capacity(1024)) | |
} | |
impl BufReader { | |
pub fn open(path: impl AsRef<std::path::Path>) -> io::Result<Self>{ | |
let file = File::open(path)?; | |
let reader = io::BufReader::new(file); | |
let buf = new_buf(); | |
Ok (Self {reader, buf}) | |
} | |
} | |
impl Iterator for BufReader { | |
type Item = io::Result<Rc<String>>; | |
fn next(&mut self) -> Option<Self::Item>{ | |
let buf = match Rc::get_mut(&mut self.buf) { | |
Some(buf) => { | |
buf.clear(); | |
buf | |
} | |
None => { | |
self.buf = new_buf(); | |
Rc::make_mut(&mut self.buf) | |
} | |
}; | |
self.reader | |
.read_line(buf) | |
.map(|u| if u == 0 {None} else {Some(Rc::clone(&self.buf))}) | |
.transpose() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment