From b2fdbd6c5fdb6eb3830912e08fcc95fd85d12e78 Mon Sep 17 00:00:00 2001 From: Nadir Ali <36660597+Xnadir@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:49:21 +0500 Subject: [PATCH 1/2] expand: count a multi-byte char split across reads as one column When a read ends inside a UTF-8 character, hold its first bytes back and join them to the next read, so the character is measured once instead of as two invalid bytes of one column each. The check lives in uucore::char_width::incomplete_utf8_suffix so unexpand can share it. Un-ignore test_multibyte_char_split_across_reads and add a portable case where the character straddles the read buffer of a file. Fixes #16503 Co-Authored-By: Claude Opus 5.5 --- src/uu/expand/src/expand.rs | 29 ++++++++++++++-- src/uucore/src/lib/features/char_width.rs | 37 ++++++++++++++++++++- tests/by-util/test_expand.rs | 40 ++++++++++++++++++----- 3 files changed, 94 insertions(+), 12 deletions(-) diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 94a58687c95..0ae1f5993c1 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -12,7 +12,7 @@ use std::io::{BufRead, BufReader, BufWriter, Write, stdin, stdout}; use std::num::IntErrorKind; use std::path::Path; use std::str::from_utf8; -use uucore::char_width::char_width_at; +use uucore::char_width::{char_width_at, incomplete_utf8_suffix}; use uucore::display::Quotable; use uucore::error::{FromIo, UError, UResult, set_exit_code}; use uucore::io::InputReader; @@ -528,18 +528,41 @@ fn expand_file( ) -> UResult<()> { let mut input = open(file)?; let ts = options.tabstops.as_ref(); + // The start of a multi-byte character that the previous read cut short. + // It is joined to the next read, so the character counts as one column. + let mut carry: Vec = Vec::new(); loop { match input.fill_buf() { Ok([]) => break, Ok(buf) => { - expand_buf(buf, output, ts, options, line) - .map_err_context(|| translate!("expand-error-failed-to-write-output"))?; let len = buf.len(); + let joined; + let data: &[u8] = if carry.is_empty() { + buf + } else { + carry.extend_from_slice(buf); + joined = std::mem::take(&mut carry); + &joined + }; + let keep = if options.utf8 { + incomplete_utf8_suffix(data) + } else { + 0 + }; + let (complete, rest) = data.split_at(data.len() - keep); + expand_buf(complete, output, ts, options, line) + .map_err_context(|| translate!("expand-error-failed-to-write-output"))?; + carry = rest.to_vec(); input.consume(len); } Err(e) => return Err(e.map_err_context(|| file.maybe_quote().to_string())), } } + // The file ended inside a character: write the bytes as they are. + if !carry.is_empty() { + expand_buf(&carry, output, ts, options, line) + .map_err_context(|| translate!("expand-error-failed-to-write-output"))?; + } Ok(()) } diff --git a/src/uucore/src/lib/features/char_width.rs b/src/uucore/src/lib/features/char_width.rs index 5e4c813d66f..ebbb7e0f907 100644 --- a/src/uucore/src/lib/features/char_width.rs +++ b/src/uucore/src/lib/features/char_width.rs @@ -51,9 +51,32 @@ pub fn char_width_at(buf: &[u8], pos: usize) -> (usize, usize) { (width, nbytes) } +/// Return the number of bytes at the end of `buf` that begin a UTF-8 sequence +/// the buffer cuts short, i.e. a character whose remaining bytes come with the +/// next read. Callers that read in chunks hold these bytes back and join them +/// to the next chunk, so the character is measured once. +#[must_use] +pub fn incomplete_utf8_suffix(buf: &[u8]) -> usize { + // A sequence is at most 4 bytes, so a cut one starts in the last 3. + for back in 1..=buf.len().min(3) { + let b = buf[buf.len() - back]; + if b & 0xC0 == 0x80 { + continue; // continuation byte + } + let needed = match b { + 0xC2..=0xDF => 2, + 0xE0..=0xEF => 3, + 0xF0..=0xF4 => 4, + _ => return 0, + }; + return if needed > back { back } else { 0 }; + } + 0 +} + #[cfg(test)] mod tests { - use super::{char_info_at, char_width_at}; + use super::{char_info_at, char_width_at, incomplete_utf8_suffix}; #[test] fn width_and_length() { @@ -75,4 +98,16 @@ mod tests { assert_eq!(char_info_at(b"a", 0), (Some('a'), 1, 1)); assert_eq!(char_info_at(&[0xFF], 0), (None, 1, 1)); // invalid resyncs } + + #[test] + fn incomplete_suffix() { + assert_eq!(incomplete_utf8_suffix(b""), 0); + assert_eq!(incomplete_utf8_suffix(b"abc"), 0); + assert_eq!(incomplete_utf8_suffix("a\u{e9}".as_bytes()), 0); // complete + assert_eq!(incomplete_utf8_suffix(b"a\xC3"), 1); // 2-byte cut after 1 + assert_eq!(incomplete_utf8_suffix(b"a\xE3\x80"), 2); // 3-byte cut after 2 + assert_eq!(incomplete_utf8_suffix(b"\xF0\x9F\x98"), 3); // 4-byte cut after 3 + assert_eq!(incomplete_utf8_suffix(b"a\x80"), 0); // stray continuation byte + assert_eq!(incomplete_utf8_suffix(b"a\xFF"), 0); // never a lead byte + } } diff --git a/tests/by-util/test_expand.rs b/tests/by-util/test_expand.rs index ba864890e27..e11386cbe92 100644 --- a/tests/by-util/test_expand.rs +++ b/tests/by-util/test_expand.rs @@ -556,17 +556,41 @@ fn test_specifier_in_two_tabs_values() { .stderr_is("expand: '/' specifier only allowed with the last value\n"); } -#[cfg(unix)] #[test] -#[ignore = "a multi-byte char split across reads must count as one column"] fn test_multibyte_char_split_across_reads() { - let scene = TestScenario::new(util_name!()); - scene - .cmd_shell("(printf '\\303'; sleep 0.3; printf '\\251\\tz\\n') | \"$BIN\" expand") - .env("BIN", &scene.bin_path) - .env("LC_ALL", "C.UTF-8") + // A slow pipe delivers the two bytes of `é` in two reads. + #[cfg(unix)] + { + let scene = TestScenario::new(util_name!()); + scene + .cmd_shell("(printf '\\303'; sleep 0.3; printf '\\251\\tz\\n') | \"$BIN\" expand") + .env("BIN", &scene.bin_path) + .env("LC_ALL", "C.UTF-8") + .succeeds() + .stdout_only("\u{e9} z\n"); + } + + // In a file, 8191 ASCII bytes put the two bytes of `é` on both sides of + // the 8 KiB read buffer. + let ts = TestScenario::new(util_name!()); + let at = &ts.fixtures; + let prefix = "a".repeat(8191); + at.write("split", &format!("{prefix}\u{e9}\tz\n")); + ts.ucmd() + .arg("split") + .succeeds() + .stdout_only(format!("{prefix}\u{e9}{}z\n", " ".repeat(8))); +} + +#[test] +fn test_file_ending_inside_a_multibyte_char() { + let ts = TestScenario::new(util_name!()); + let at = &ts.fixtures; + at.write_bytes("cut", b"a\tb\xC3"); + ts.ucmd() + .arg("cut") .succeeds() - .stdout_only("\u{e9} z\n"); + .stdout_only_bytes(b"a b\xC3"); } #[test] From 7c4c5593f5df858b3bf59208921fbff3ea012bc0 Mon Sep 17 00:00:00 2001 From: Nadir Ali <36660597+Xnadir@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:01:06 +0500 Subject: [PATCH 2/2] Keep the slow-pipe regression on native Unix --- tests/by-util/test_expand.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/by-util/test_expand.rs b/tests/by-util/test_expand.rs index e11386cbe92..16941b1e7a0 100644 --- a/tests/by-util/test_expand.rs +++ b/tests/by-util/test_expand.rs @@ -559,7 +559,7 @@ fn test_specifier_in_two_tabs_values() { #[test] fn test_multibyte_char_split_across_reads() { // A slow pipe delivers the two bytes of `é` in two reads. - #[cfg(unix)] + #[cfg(all(unix, not(wasi_runner)))] { let scene = TestScenario::new(util_name!()); scene