From 2372871575717d3598d1a01954bbb5a5d283a063 Mon Sep 17 00:00:00 2001 From: Kento Ikeda <974175+ikenyal@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:27:18 +0900 Subject: [PATCH] fix(tail): avoid preallocating from the requested line count --- src/commands/tail.rs | 2 +- tests/shell_integration.rs | 40 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/commands/tail.rs b/src/commands/tail.rs index d0d82ba..0d549aa 100644 --- a/src/commands/tail.rs +++ b/src/commands/tail.rs @@ -61,7 +61,7 @@ async fn cmd_tail(os: &dyn Kernel, args: &[String]) -> CommandResult { } } else { // Keep last N lines in a ring buffer - let mut ring: VecDeque = VecDeque::with_capacity(count + 1); + let mut ring: VecDeque = VecDeque::new(); let mut line = String::new(); loop { line.clear(); diff --git a/tests/shell_integration.rs b/tests/shell_integration.rs index b4ef615..42bf53d 100644 --- a/tests/shell_integration.rs +++ b/tests/shell_integration.rs @@ -4481,6 +4481,46 @@ expect!( // ── tail coverage ─────────────────────────────────────────────────── +#[test] +fn tail_large_line_counts_preserve_small_input() { + let (rt, local) = rt(); + rt.block_on(local.run_until(async { + let mut shell = Shell::builder().build().unwrap(); + for count in [usize::MAX, usize::MAX / 2] { + for (cmd, expected) in [ + (format!("printf 'a\\nb\\nc' | tail -n {count}"), "a\nb\nc"), + ( + format!( + "printf 'a\\nb\\nc' > /tmp/tail-large; tail -n {count} /tmp/tail-large" + ), + "a\nb\nc", + ), + (format!("printf '' | tail -n {count}"), ""), + ] { + let out = shell.run(&cmd).await; + assert_eq!(out.status, 0, "{cmd}: {}", out.stderr); + assert_eq!(out.stdout, expected, "{cmd}"); + assert!(out.stderr.is_empty(), "{cmd}: {}", out.stderr); + } + } + })); +} + +#[test] +fn tail_line_count_boundaries() { + let (rt, local) = rt(); + rt.block_on(local.run_until(async { + let mut shell = Shell::builder().build().unwrap(); + for (count, expected) in [(0, ""), (1, "c"), (3, "a\nb\nc"), (4, "a\nb\nc")] { + let cmd = format!("printf 'a\\nb\\nc' | tail -n {count}"); + let out = shell.run(&cmd).await; + assert_eq!(out.status, 0, "{cmd}: {}", out.stderr); + assert_eq!(out.stdout, expected, "{cmd}"); + assert!(out.stderr.is_empty(), "{cmd}: {}", out.stderr); + } + })); +} + expect!( tail_from_file, "printf 'a\\nb\\nc\\nd\\ne\\n' > /tmp/tf; tail -n 2 /tmp/tf",