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
15 changes: 13 additions & 2 deletions src/uu/uniq/src/uniq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ impl Uniq {

fn key_bounds(&self, line: &[u8]) -> (usize, usize) {
let mut start = self.skip_fields_offset(line);
if let Some(skip_bytes) = self.slice_start {
start = start.saturating_add(skip_bytes).min(line.len());
if let Some(skip_chars) = self.slice_start {
start = self.char_offset(line, start, skip_chars);
}

let end = self.key_end_index(line, start);
Expand Down Expand Up @@ -242,6 +242,17 @@ impl Uniq {
}
}

/// The index `count` characters after `start`: bytes in the C locale or
/// for invalid UTF-8, characters otherwise, as for `-w`.
fn char_offset(&self, line: &[u8], start: usize, count: usize) -> usize {
if !self.is_c_locale
&& let Ok(valid) = std::str::from_utf8(&line[start..])
{
return start + Self::char_prefix_len(valid, count);
}
start.saturating_add(count).min(line.len())
}

fn char_prefix_len(text: &str, limit: usize) -> usize {
for (count, (idx, _)) in text.char_indices().enumerate() {
if count == limit {
Expand Down
19 changes: 19 additions & 0 deletions tests/by-util/test_uniq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1214,6 +1214,25 @@ fn test_stdin_w1_multibyte() {
.stdout_is("à\ná\n");
}

#[uutests::wasi_ignore(NoLocaleData)]
#[test]
fn test_skip_chars_multibyte() {
// Skipping two characters leaves "y" and "xy", which differ.
new_ucmd!()
.args(&["-s", "2", "-c"])
.env("LC_ALL", "en_US.UTF-8")
.pipe_in("éxy\nABxy\n")
.succeeds()
.stdout_is(" 1 éxy\n 1 ABxy\n");
// In the C locale, two bytes are skipped and both keys are "xy".
new_ucmd!()
.args(&["-s", "2", "-c"])
.env("LC_ALL", "C")
.pipe_in("éxy\nABxy\n")
.succeeds()
.stdout_is(" 2 éxy\n");
}

#[test]
fn test_c_locale_counts_bytes() {
let input = "가나다라마\n가나다바사\n";
Expand Down
Loading