I tried to read a file in a way that is performant enough for my purpose. I have a list of file ids, names and line indexes (ordered) and for each pair (file_id, file_name, line_index) I need to open the file, find the line by index and print.
To be more performant (I know the input is ordered) I'd like to cache the BufReader that reads by line and let the file stay open if possible.
fn main() {
// positions in file
// structure: (file_id, file_name, line_index_in_file)
let positions = &vec![
(1, String::from("file1"), 1),
(1, String::from("file1"), 2),
(1, String::from("file1"), 20),
(2, String::from("file2"), 15)];
print_lines_from_file(&positions);
}
fn print_lines_from_file(found: &Vec<(i32, String, i32)>) {
let mut last_file_id = -1;
//let mut last_file_name = None;
let mut open_file = None;
let mut open_reader = None;
for &(file_id, ref file_name, pos_in_file) in found {
println!("{} {}", file_id, pos_in_file);
if last_file_id < file_id {
last_file_id = file_id;
//last_file_name = file_ids.get(&file_id);
if let Some(to_close) = open_file {
drop(open_reader.unwrap());
drop(to_close);
}
//let file = File::open(last_file_name.unwrap()).unwrap();
let file = File::open(file_name).unwrap();
open_file = Some(file);
open_reader = Some(BufReader::new(&file));
}
// use reader to find the line in file and process
}
}
I'm facing this problem:
main.rs:40:48: 40:52 error: `file` does not live long enough
main.rs:40 open_reader = Some(BufReader::new(&file));
main.rs:40:48: 40:52 error: use of moved value: `file` [E0382]
main.rs:40 open_reader = Some(BufReader::new(&file));
It's obvious (file's lifetime is really short), but I don't know how to workaround it.
The BufReader depends on File, but I need to close the File later in loop when file_id changes.
Also I don't feel very comfortable calling drop this way in loop as it looks to me like I try to fool the compiler. Is that approach ok?
Please even if you know better solution (e.g. how to close the file through BufReader, I would appreciate the general insight how to solve it).