diff --git a/src/uu/rev/rev.md b/src/uu/rev/rev.md index 01bf0a74..719c537b 100644 --- a/src/uu/rev/rev.md +++ b/src/uu/rev/rev.md @@ -4,4 +4,6 @@ rev [options] [file ...] ``` -Reverse lines characterwise. \ No newline at end of file +Reverse lines characterwise. + +A record reverses by code point when it is valid UTF-8 and the first nonempty locale setting in LC_ALL, LC_CTYPE, LANG order specifies UTF-8; otherwise the whole record reverses bytewise. diff --git a/src/uu/rev/src/rev.rs b/src/uu/rev/src/rev.rs index b980d168..4b9a14dd 100644 --- a/src/uu/rev/src/rev.rs +++ b/src/uu/rev/src/rev.rs @@ -17,6 +17,98 @@ mod options { pub const ZERO: &str = "zero"; } +// uucore's get_locale_encoding uses LC_COLLATE and accepts empty values. +fn is_utf8_locale() -> bool { + let locale = ["LC_ALL", "LC_CTYPE", "LANG"] + .into_iter() + .filter_map(env::var_os) + .find(|value| !value.is_empty()); + locale + .as_deref() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + let codeset = match name.split_once('.') { + Some((_, codeset)) => codeset, + None if cfg!(target_vendor = "apple") => name, + None => return false, + }; + let codeset = codeset.split_once('@').map_or(codeset, |(code, _)| code); + codeset.eq_ignore_ascii_case("UTF-8") || codeset.eq_ignore_ascii_case("UTF8") + }) +} + +// Checking while swapping avoids a separate scan in ASCII-only mode. +// The caller handles the middle so the loop can use complete words. +#[clippy::msrv = "1.70.0"] +fn reverse_blocks(buf: &mut [u8], ascii_only: bool) -> &mut [u8] { + let len = buf.len(); + let (front, back) = buf.split_at_mut(len / 2); + let mut done = 0; + for (a, b) in front.chunks_exact_mut(8).zip(back.rchunks_exact_mut(8)) { + let x = u64::from_ne_bytes(a.try_into().unwrap()); + let y = u64::from_ne_bytes(b.try_into().unwrap()); + if ascii_only && (x | y) & 0x8080_8080_8080_8080 != 0 { + break; + } + a.copy_from_slice(&y.swap_bytes().to_ne_bytes()); + b.copy_from_slice(&x.swap_bytes().to_ne_bytes()); + done += 8; + } + &mut buf[done..len - done] +} + +#[clippy::msrv = "1.70.0"] +fn utf8_ascii_prefix(buf: &[u8]) -> Option { + // Reject invalid trailing sequences before scanning a long ASCII prefix. + if buf.len() >= 128 { + let tail = buf.len() - 8; + if let Some(i) = buf[tail..].iter().rposition(|b| !b.is_ascii()) { + // A valid UTF-8 character ending here occupies at most four bytes. + let end = tail + i + 1; + let lead = buf[end - 4..end].iter().rposition(|&b| b & 0xc0 != 0x80); + if std::str::from_utf8(&buf[end - 4 + lead.unwrap_or(0)..end]).is_err() { + return None; + } + } + } + // Skip validated ASCII blocks in the remaining ASCII and UTF-8 checks. + let ascii_prefix = buf + .chunks_exact(64) + .take_while(|block| block.is_ascii()) + .count() + * 64; + let buf = &buf[ascii_prefix..]; + let remaining_prefix = buf.iter().position(|b| !b.is_ascii())?; + std::str::from_utf8(&buf[remaining_prefix..]) + .is_ok() + .then_some(ascii_prefix + remaining_prefix) +} + +fn reverse_record(buf: &mut [u8], utf8: bool) { + // A non-ASCII byte at either end would stop the block path immediately. + let buf = if utf8 && buf.len() >= 128 && buf[0].is_ascii() && buf[buf.len() - 1].is_ascii() { + reverse_blocks(buf, true) + } else { + buf + }; + if utf8 { + if let Some(ascii_prefix) = utf8_ascii_prefix(buf) { + reverse_blocks(buf, false).reverse(); + // The ASCII prefix needs no character repair after byte reversal. + let repair_end = buf.len() - ascii_prefix; + let mut start = 0; + for end in 0..repair_end { + if buf[end] & 0xc0 != 0x80 { + buf[start..=end].reverse(); + start = end + 1; + } + } + return; + } + } + buf.reverse(); +} + #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches: clap::ArgMatches = uu_app().try_get_matches_from(args)?; @@ -24,6 +116,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let zero = matches.get_flag(options::ZERO); let sep = if zero { b'\0' } else { b'\n' }; + let utf8 = is_utf8_locale(); if let Some(files) = files { for path in files { @@ -32,20 +125,20 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { uucore::show_error!("cannot open {path}: No such file or directory"); continue; }; - if let Err(err) = rev_stream(file, sep) { + if let Err(err) = rev_stream(file, sep, utf8) { uucore::error::set_exit_code(1); uucore::show_error!("cannot read {path}: {err}"); } } } else { let stdin = std::io::stdin().lock(); - let _ = rev_stream(stdin, sep); + let _ = rev_stream(stdin, sep, utf8); } Ok(()) } -fn rev_stream(stream: impl Read, sep: u8) -> std::io::Result<()> { +fn rev_stream(stream: impl Read, sep: u8, utf8: bool) -> std::io::Result<()> { let mut stdout = std::io::stdout().lock(); let mut stream = BufReader::new(stream); let mut buf = Vec::with_capacity(4096); @@ -54,11 +147,11 @@ fn rev_stream(stream: impl Read, sep: u8) -> std::io::Result<()> { stream.read_until(sep, &mut buf)?; if buf.last().copied() == Some(sep) { buf.pop(); - buf.reverse(); + reverse_record(&mut buf, utf8); buf.push(sep); stdout.write_all(&buf)?; } else { - buf.reverse(); + reverse_record(&mut buf, utf8); stdout.write_all(&buf)?; break; } diff --git a/tests/by-util/test_rev.rs b/tests/by-util/test_rev.rs index f322a3fd..cb91fdbe 100644 --- a/tests/by-util/test_rev.rs +++ b/tests/by-util/test_rev.rs @@ -15,6 +15,250 @@ fn test_piped_in_data() { new_ucmd!().pipe_in("a test").succeeds().stdout_is("tset a"); } +#[test] +fn test_utf8_characters() { + // Combining marks reverse separately because reversal is by code point. + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in("aé中🙂b\ne\u{301}x") + .succeeds() + .stdout_is_bytes("b🙂中éa\nx\u{301}e".as_bytes()); +} + +#[test] +fn test_utf8_zero_records() { + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .arg("-0") + .pipe_in("é中\0a🙂") + .succeeds() + .stdout_is_bytes("中é\0🙂a".as_bytes()); +} + +#[test] +fn test_utf8_files() { + let (at, mut ucmd) = at_and_ucmd!(); + + at.write("a.txt", "aé中\n"); + at.write("b.txt", "x🙂"); + + ucmd.env("LC_ALL", "C.UTF-8") + .args(&["a.txt", "b.txt"]) + .succeeds() + .stdout_is_bytes("中éa\n🙂x".as_bytes()); +} + +#[test] +fn test_c_locale_keeps_byte_reversal() { + // util-linux exits 1 here; rev keeps reversing the bytes. + new_ucmd!() + .env("LC_ALL", "C") + .pipe_in("é\n") + .succeeds() + .stdout_is_bytes([0xa9, 0xc3, b'\n']); +} + +#[test] +fn test_invalid_utf8_keeps_byte_reversal() { + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in([0xc3, b'A', b'\n']) + .succeeds() + .stdout_is_bytes([b'A', 0xc3, b'\n']); +} + +#[test] +fn test_locale_precedence() { + let cases: &[(&str, &str, &str, &[u8])] = &[ + ("", "C.UTF-8", "C", "中é\n".as_bytes()), + ("", "", "C.UTF-8", "中é\n".as_bytes()), + ( + "C", + "C.UTF-8", + "C.UTF-8", + &[0xad, 0xb8, 0xe4, 0xa9, 0xc3, b'\n'], + ), + ("", "C", "C.UTF-8", &[0xad, 0xb8, 0xe4, 0xa9, 0xc3, b'\n']), + ("C.utf8", "C", "C", "中é\n".as_bytes()), + // Label parsing does not require the locale to be installed. + ("C.UTF-8@variant", "C", "C", "中é\n".as_bytes()), + ]; + for &(all, ctype, lang, expected) in cases { + new_ucmd!() + .env("LC_ALL", all) + .env("LC_CTYPE", ctype) + .env("LANG", lang) + .pipe_in("é中\n") + .succeeds() + .stdout_is_bytes(expected); + } +} + +#[cfg(target_vendor = "apple")] +#[test] +fn test_macos_dotless_utf8_locale() { + new_ucmd!() + .env("LC_ALL", "") + .env("LC_CTYPE", "UTF-8") + .pipe_in("é中\n") + .succeeds() + .stdout_is_bytes("中é\n".as_bytes()); +} + +#[cfg(not(target_vendor = "apple"))] +#[test] +fn test_dotless_utf8_locale_keeps_byte_reversal() { + new_ucmd!() + .env("LC_ALL", "") + .env("LC_CTYPE", "UTF-8") + .pipe_in("é中\n") + .succeeds() + .stdout_is_bytes([0xad, 0xb8, 0xe4, 0xa9, 0xc3, b'\n']); +} + +#[test] +fn test_mixed_valid_and_invalid_utf8_records() { + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in([ + 0xc3, 0xa9, b'\n', 0xc3, b'A', b'\n', 0xe4, 0xb8, 0xad, b'\n', + ]) + .succeeds() + .stdout_is_bytes([ + 0xc3, 0xa9, b'\n', b'A', 0xc3, b'\n', 0xe4, 0xb8, 0xad, b'\n', + ]); +} + +#[test] +fn test_utf8_records_with_ascii_ends() { + let ascii: String = ('a'..='z').chain('A'..='Z').chain('0'..='9').collect(); + let mut records: Vec = (0..=ascii.len()).map(|n| ascii[..n].to_string()).collect(); + records.extend((0..=ascii.len()).map(|at| format!("{}é{}", &ascii[..at], &ascii[at..]))); + let input: String = records.iter().map(|r| format!("{r}\n")).collect(); + let expected: String = records + .iter() + .map(|r| format!("{}\n", r.chars().rev().collect::())) + .collect(); + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in(input) + .succeeds() + .stdout_is_bytes(expected.as_bytes()); +} + +#[test] +fn test_invalid_utf8_between_ascii_ends_keeps_byte_reversal() { + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in(&b"0123456789abcdef\xc3ghijklmnopqrstuv\n"[..]) + .succeeds() + .stdout_is_bytes(b"vutsrqponmlkjihg\xc3fedcba9876543210\n"); +} + +#[test] +fn test_long_ascii_record_in_utf8_locale() { + let input: Vec = (0..65_535).map(|i| b'a' + (i % 26) as u8).collect(); + let mut expected = input.clone(); + expected.reverse(); + expected.push(b'\n'); + let mut input = input; + input.push(b'\n'); + new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in(input) + .succeeds() + .stdout_is_bytes(expected); +} + +fn utf8_reversed(record: &[u8]) -> Vec { + match std::str::from_utf8(record) { + Ok(text) => text.chars().rev().collect::().into_bytes(), + Err(_) => record.iter().rev().copied().collect(), + } +} + +// Compare records separately to identify content mismatches. +fn check_utf8_records(records: &[Vec]) { + let mut input = Vec::new(); + for record in records { + input.extend_from_slice(record); + input.push(b'\n'); + } + let result = new_ucmd!() + .env("LC_ALL", "C.UTF-8") + .pipe_in(input) + .succeeds(); + let mut lines: Vec<&[u8]> = result.stdout().split(|&b| b == b'\n').collect(); + assert_eq!(lines.pop(), Some(&b""[..])); + assert_eq!(lines.len(), records.len()); + for (line, record) in lines.iter().zip(records) { + assert_eq!(*line, &utf8_reversed(record)[..], "record {record:02x?}"); + } +} + +#[test] +fn test_long_ascii_record_ending_in_invalid_utf8() { + let mut record = vec![b'a'; 65_534]; + record.push(0xe9); + check_utf8_records(&[record]); +} + +#[test] +fn test_long_records_with_ascii_ends() { + let ascii: Vec = (0..150).map(|i| b'a' + (i % 26) as u8).collect(); + let pieces: [&[u8]; 5] = [ + "é".as_bytes(), + "中".as_bytes(), + "🙂".as_bytes(), + b"\xe9", + b"\x80", + ]; + let records: Vec> = pieces + .iter() + .flat_map(|piece| (1..ascii.len()).map(|at| [&ascii[..at], piece, &ascii[at..]].concat())) + .collect(); + check_utf8_records(&records); +} + +#[test] +fn test_last_non_ascii_character() { + // The last-character check must not accept a record that starts with a stray + // continuation byte. + let ends: [&[u8]; 8] = [ + "é".as_bytes(), + "中".as_bytes(), + "🙂".as_bytes(), + b"\xe9", + b"\xe4\xb8", + b"\xf0\x9f\x99", + b"\x80", + b"\xc3\xa9\x80\x80\x80", + ]; + let mut records = Vec::new(); + for len in [0, 1, 31, 32, 33, 130] { + for end in ends { + for after in [&b""[..], b"\r", b". ", b"1234567", b"12345678"] { + let record = [&vec![b'x'; len][..], end, after].concat(); + records.push([&b"\x80"[..], &record].concat()); + records.push(record); + } + } + } + check_utf8_records(&records); +} + +#[test] +fn test_non_ascii_after_ascii_prefix() { + // Exercise ASCII-prefix skipping across 64-byte boundaries. + let mut records = Vec::new(); + for at in 0..=140 { + let ascii = vec![b'x'; at]; + records.push([&ascii[..], "é-中".as_bytes()].concat()); + records.push([&ascii[..], b"\x80", "é-中".as_bytes()].concat()); + } + check_utf8_records(&records); +} + #[test] fn test_existing_file() { let (at, mut ucmd) = at_and_ucmd!();