From d64e8a21565c333a2a35ca06984ad460dd2381d5 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:25:33 +0100 Subject: 0.2.0: streaming line-range reads read seeks to offset with a buffered reader and consumes over-long lines without keeping them: 16 MB RSS on a 200 MB file, 0.8s to line 999000. Adds CHANGELOG and the versioning policy. --- src/tools/fs.rs | 156 +++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 125 insertions(+), 31 deletions(-) (limited to 'src/tools/fs.rs') diff --git a/src/tools/fs.rs b/src/tools/fs.rs index 6addf8d..e543cb6 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -1,9 +1,11 @@ use std::fs; +use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use serde_json::Value; const MAX_LINE_CHARS: usize = 400; +const MAX_LINE_BYTES: usize = 4096; const MAX_READ_LINES: usize = 2000; const MAX_MATCHES: usize = 200; const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; @@ -138,42 +140,134 @@ pub fn read(args: &Value) -> Result { .unwrap_or(MAX_READ_LINES as u64) .clamp(1, MAX_READ_LINES as u64) as usize; - let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; - if bytes.iter().take(8192).any(|&b| b == 0) { - return Err(format!( - "{path}: looks like a binary file and will not be shown" - )); + let meta = fs::metadata(&path).map_err(|e| format!("{path}: {e}"))?; + if meta.is_dir() { + return Err(format!("{path} is a directory; use glob or grep")); } - let text = String::from_utf8_lossy(&bytes); - let lines: Vec<&str> = text.lines().collect(); - if lines.is_empty() { - return Ok(format!("{path}: empty file")); - } - if offset > lines.len() { - return Ok(format!( - "{path} has {} lines; offset {offset} is past the end", - lines.len() - )); - } - - let end = (offset + limit - 1).min(lines.len()); - let mut out = String::with_capacity((end - offset + 2) * 40); - for number in offset..=end { - out.push_str(&format!( - "{number:>6}\t{}\n", - clip(lines[number - 1], MAX_LINE_CHARS) - )); - } - if end < lines.len() { - out.push_str(&format!( - "… {} more line(s); continue with offset={}\n", - lines.len() - end, - end + 1 - )); + + let file = fs::File::open(&path).map_err(|e| format!("{path}: {e}"))?; + let mut reader = BufReader::with_capacity(64 * 1024, file); + + if let Ok(head) = reader.fill_buf() { + if head.iter().take(8192).any(|&b| b == 0) { + return Err(format!( + "{path}: looks like a binary file and will not be shown" + )); + } + } + + // Skip to the first requested line without buffering what is skipped, so a + // 500 MB log with offset near the end costs a scan, not a 500 MB allocation. + for _ in 1..offset { + match skip_line(&mut reader).map_err(|e| format!("{path}: {e}"))? { + true => {} + false => return Ok(format!("{path} has fewer than {offset} lines")), + } + } + + let mut out = String::new(); + let mut produced = 0usize; + let mut number = offset; + + while produced < limit { + let (bytes, truncated) = match read_line_limited(&mut reader, MAX_LINE_BYTES) + .map_err(|e| format!("{path}: {e}"))? + { + Some(line) => line, + None => break, + }; + let text = String::from_utf8_lossy(&bytes); + let text = text.trim_end_matches('\n'); + let mut rendered = clip(text, MAX_LINE_CHARS); + if truncated { + rendered.push_str(" …(line truncated)"); + } + out.push_str(&format!("{number:>6}\t{rendered}\n")); + produced += 1; + number += 1; + } + + if produced == 0 { + return Ok(if offset == 1 { + format!("{path}: empty file") + } else { + format!("{path} has fewer than {offset} lines") + }); + } + + if let Ok(head) = reader.fill_buf() { + if !head.is_empty() { + out.push_str(&format!("… more lines; continue with offset={number}\n")); + } } + Ok(out) } +/// Consumes one line without keeping it. False at end of file. +fn skip_line(reader: &mut R) -> std::io::Result { + let mut any = false; + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(any); + } + any = true; + match buf.iter().position(|&b| b == b'\n') { + Some(index) => { + reader.consume(index + 1); + return Ok(true); + } + None => { + let len = buf.len(); + reader.consume(len); + } + } + } +} + +/// Reads one line, keeping at most `max` bytes but consuming the whole line. +/// Returns `(bytes, truncated)`; `None` at end of file. +fn read_line_limited( + reader: &mut R, + max: usize, +) -> std::io::Result, bool)>> { + let mut kept: Vec = Vec::new(); + let mut any = false; + let mut truncated = false; + + loop { + let buf = reader.fill_buf()?; + if buf.is_empty() { + return Ok(if any { Some((kept, truncated)) } else { None }); + } + any = true; + + let newline = buf.iter().position(|&b| b == b'\n'); + let take = match newline { + Some(index) => index + 1, + None => buf.len(), + }; + + if kept.len() < max { + let room = max - kept.len(); + let slice = &buf[..take.min(room)]; + kept.extend_from_slice(slice); + if take > slice.len() { + truncated = true; + } + } else { + truncated = true; + } + + reader.consume(take); + + if newline.is_some() { + return Ok(Some((kept, truncated))); + } + } +} + pub fn grep(args: &Value) -> Result { let pattern = req(args, "pattern")?; if pattern.is_empty() { -- cgit v1.2.3