Trait claudiofsr_lib::IteratorExtension
source · pub trait IteratorExtension<E> {
// Required method
fn try_count(&mut self) -> Result<u64, E>;
}Expand description
Count function consumes the Lines:
let number_of_lines = BufReader::new(file).lines().count();
count() essentially loops over all the elements of the iterator, incrementing a counter until the iterator returns None.
In this case, once the file can no longer be read, the iterator never returns None, and the function runs forever.
You can make the iterator return None when the inner value is an error by using functions such as try_fold().
use claudiofsr_lib::IteratorExtension;
use std::io::{BufRead, BufReader};
let text: &str = "this\nis\na\ntest\n";
let counter: Result<u64, _> = BufReader::new(text.as_bytes())
//.lines() // Return an error if the read bytes are not valid UTF-8
.split(b'\n') // Ignores invalid UTF-8 but
.try_count(); // Catches other errors
//assert!(result.is_ok_and(|c| c == 4));
assert!(matches!(counter, Ok(4)));https://www.reddit.com/r/rust/comments/wyk1l0/can_you_compose_stdiolines_with_stditercount/