Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions src/uu/expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<u8> = 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(())
}

Expand Down
37 changes: 36 additions & 1 deletion src/uucore/src/lib/features/char_width.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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
}
}
40 changes: 32 additions & 8 deletions tests/by-util/test_expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading