How to re-use a `BufReader`

I am doing AOC day1, and I my code looks like this:

let parse_float = |line| line.unwrap().parse::<f32>().unwrap();

let f = File::open("day1/src/input.txt")?;
let simple_sonar = BufReader::new(f)
    .lines()
    .map(parse_float)
    // do stuff with the data

let simple_sonar_2 = BufReader::new(f)
    .lines()
    .map(parse_float)
    // do other stuff with the data

I would like to not have to re-create the buf reader between both computation, is it possible?

BufRead is implemented for all &mut T where T: BufRead so you should be able to do

let mut buf_reader = BufReader::new(f);
let simple_sonar = (&mut buf_reader).lines()....
buf_reader.seek(...)
let simple_sonar_2 = buf_reader.lines()....

Indeed, this compiles, but it seems that the bufreader it not reset between calls (ie the pointer is at the end of the file). The second sonar doesn’t output any lines.

I've edited my post to add the seek in the meantime. But that a seek is required was not part of your post, I had to look up the AoC problem.

Thanks, I didn’t realized that you could call seek directly.

Normally if you need to do multiple passes over some data you'll read it entirely into memory and work with it there. In general, file IO is a lot slower than writing to a big buffer, and this way you only need to handle errors once.

let parse_float = |line| line.unwrap().parse::<f32>().unwrap();

let input = std::fs::read_to_string("day1/src/input.txt")?;
let simple_sonar = input
    .lines()
    .map(parse_float)
    // do stuff with the data

let simple_sonar_2 = input
    .lines()
    .map(parse_float)
    // do other stuff with the data

As a bonus, it means we can avoid doing the string parsing twice (a slow operation) by collecting the result of parse_float() into a Vec.

let input = std::fs::read_to_string("day1/src/input.txt")?;
let floats: Vec<f32> = input.lines()
  .map(|line| line.parse().unwrap())
  .collect();

let simple_sonar = floats.iter()...;
let simple_sonar_2 = floats.iter()...;

The only time this strategy might not be appropriate is when your input.txt is so large it won't easily fit into memory.

1 Like

Of course, such small files will likely be entirely cached by the OS after the first read.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.