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/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 6bd8d9aefd9..ac5ea2b5690 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -10,7 +10,7 @@ use std::ffi::OsString; use std::fs::File; use std::io::{BufRead, BufReader, BufWriter, Stdin, Stdout, Write, stdin, stdout}; use std::num::IntErrorKind; -use uucore::char_width::char_info_at; +use uucore::char_width::{char_info_at, incomplete_utf8_suffix}; use uucore::display::Quotable; use uucore::error::{FromIo, UError, UResult, set_exit_code}; use uucore::io::InputReader; @@ -710,6 +710,24 @@ fn unexpand_file( result } +/// Unexpands the lines of one chunk of input, carrying the line state in `print_state`. +fn unexpand_lines( + buf: &[u8], + output: &mut BufWriter, + options: &Options, + lastcol: usize, + tab_config: &TabConfig, + print_state: &mut PrintState, +) -> UResult<()> { + for line in buf.split_inclusive(|b| *b == b'\n') { + unexpand_buf(line, output, options, lastcol, tab_config, print_state)?; + if let Some(b'\n') = line.last() { + print_state.new_line(); + } + } + Ok(()) +} + /// Unexpands everything `input` yields, carrying the line state in `print_state`. fn unexpand_input( input: &mut impl BufRead, @@ -720,20 +738,34 @@ fn unexpand_input( tab_config: &TabConfig, print_state: &mut PrintState, ) -> UResult<()> { + // 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(); while let buf @ [_, ..] = input .fill_buf() .map_err(|e| e.map_err_context(|| file.maybe_quote().to_string()) as Box)? { - for line in buf.split_inclusive(|b| *b == b'\n') { - unexpand_buf(line, output, options, lastcol, tab_config, print_state)?; - if let Some(b'\n') = line.last() { - print_state.new_line(); - } - } 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); + unexpand_lines(complete, output, options, lastcol, tab_config, print_state)?; + carry = rest.to_vec(); input.consume(len); } - Ok(()) + // The input ended inside a character: write the bytes as they are. + unexpand_lines(&carry, output, options, lastcol, tab_config, print_state) } fn unexpand(options: &Options) -> UResult<()> { 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..16941b1e7a0 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(all(unix, not(wasi_runner)))] + { + 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] diff --git a/tests/by-util/test_unexpand.rs b/tests/by-util/test_unexpand.rs index 1ab6bacd415..ba1993f82c4 100644 --- a/tests/by-util/test_unexpand.rs +++ b/tests/by-util/test_unexpand.rs @@ -624,15 +624,37 @@ fn test_line_continues_past_unreadable_file() { .stderr_contains("unexpand: dir: Is a directory"); } -#[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 = uutests::util::TestScenario::new(uutests::util_name!()); - scene - .cmd_shell("(printf '\\303'; sleep 0.3; printf '\\251 z\\n') | \"$BIN\" unexpand -a") - .env("BIN", &scene.bin_path) - .env("LC_ALL", "C.UTF-8") + // A slow pipe delivers the two bytes of `é` in two reads. + #[cfg(all(unix, not(wasi_runner)))] + { + let scene = uutests::util::TestScenario::new(uutests::util_name!()); + scene + .cmd_shell( + "(printf '\\303'; sleep 0.3; printf '\\251 z\\n') | \"$BIN\" unexpand -a", + ) + .env("BIN", &scene.bin_path) + .env("LC_ALL", "C.UTF-8") + .succeeds() + .stdout_only("\u{e9}\tz\n"); + } + + // In a file, 8191 ASCII bytes put the two bytes of `é` on both sides of + // the 8 KiB read buffer. + let (at, mut ucmd) = at_and_ucmd!(); + let prefix = "a".repeat(8191); + at.write("split", &format!("{prefix}\u{e9} z\n")); + ucmd.args(&["-a", "split"]) + .succeeds() + .stdout_only(format!("{prefix}\u{e9}\tz\n")); +} + +#[test] +fn test_file_ending_inside_a_multibyte_char() { + let (at, mut ucmd) = at_and_ucmd!(); + at.write_bytes("cut", b"a b\xC3"); + ucmd.args(&["-a", "cut"]) .succeeds() - .stdout_only("\u{e9}\tz\n"); + .stdout_only_bytes(b"a\tb\xC3"); }