From 412ce2b142ad4a6e9ff96f9146f4d2ed7a3ed2fc Mon Sep 17 00:00:00 2001 From: Lucy Date: Sat, 5 Oct 2024 22:54:26 -0400 Subject: [PATCH] Optimize `aneri_file::file_get_line_count` --- crates/file/src/lib.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/crates/file/src/lib.rs b/crates/file/src/lib.rs index f887c16..08c22ad 100644 --- a/crates/file/src/lib.rs +++ b/crates/file/src/lib.rs @@ -68,15 +68,12 @@ pub fn file_append(path: PathBuf, data: String) -> bool { pub fn file_get_line_count(path: PathBuf) -> Option { let mut file = File::open(path).ok().map(BufReader::new)?; let mut lines = 0_usize; - let mut temp_string = String::new(); - loop { - match file.read_line(&mut temp_string) { - Ok(0) => break, - Ok(_) => (), - Err(_) => return None, + let mut buffer = [0; 8192]; // Use an 8KB buffer for efficiency + while let Ok(bytes_read) = file.read(&mut buffer) { + if bytes_read == 0 { + break; } - lines += 1; - temp_string.clear(); + lines += buffer[..bytes_read].iter().filter(|&&b| b == b'\n').count(); } Some(lines) }