From a4b621ad8ae93eab45815da7cced476599e312da Mon Sep 17 00:00:00 2001 From: Karl McDowall Date: Wed, 2 Apr 2025 16:56:38 -0600 Subject: [PATCH] cat: bugfix when running with -T option Fixes an crash seen when running with -T option if no newline is found in a buffer. Added unit test to validate. --- src/uu/cat/src/cat.rs | 16 +++++++++++++++- tests/by-util/test_cat.rs | 9 +++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index d4013e0c8..63f1f8bb5 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -644,7 +644,7 @@ fn write_tab_to_end(mut in_buf: &[u8], writer: &mut W) -> usize { } None => { writer.write_all(in_buf).unwrap(); - return in_buf.len(); + return in_buf.len() + count; } }; } @@ -688,6 +688,20 @@ fn write_end_of_line( mod tests { use std::io::{BufWriter, stdout}; + #[test] + fn test_write_tab_to_end_with_newline() { + let mut writer = BufWriter::with_capacity(1024 * 64, stdout()); + let in_buf = b"a\tb\tc\n"; + assert_eq!(super::write_tab_to_end(in_buf, &mut writer), 5); + } + + #[test] + fn test_write_tab_to_end_no_newline() { + let mut writer = BufWriter::with_capacity(1024 * 64, stdout()); + let in_buf = b"a\tb\tc"; + assert_eq!(super::write_tab_to_end(in_buf, &mut writer), 5); + } + #[test] fn test_write_nonprint_to_end_new_line() { let mut writer = BufWriter::with_capacity(1024 * 64, stdout()); diff --git a/tests/by-util/test_cat.rs b/tests/by-util/test_cat.rs index be405dfc6..926befe72 100644 --- a/tests/by-util/test_cat.rs +++ b/tests/by-util/test_cat.rs @@ -414,6 +414,15 @@ fn test_stdin_nonprinting_and_tabs_repeated() { .stdout_only("^I^@\n"); } +#[test] +fn test_stdin_tabs_no_newline() { + new_ucmd!() + .args(&["-T"]) + .pipe_in("\ta") + .succeeds() + .stdout_only("^Ia"); +} + #[test] fn test_stdin_squeeze_blank() { for same_param in ["-s", "--squeeze-blank", "--squeeze"] {