Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/wasi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,6 @@ jobs:
test_paste:: test_pathchk:: test_pr:: test_printenv:: test_printf:: test_ptx:: \
test_pwd:: test_readlink:: test_realpath:: test_rmdir:: test_sha1sum:: test_sha224sum:: test_sha256sum:: \
Comment thread
eduardomourar marked this conversation as resolved.
Resolved
test_sha384sum:: test_sha512sum:: test_shred:: test_shuf:: test_sleep:: \
test_sum:: test_tail:: test_tee:: \
test_sort::sort_multiple test_sort::test_check test_sum:: test_tail:: test_tee:: \
test_test:: test_touch:: test_tr:: test_true:: test_truncate:: test_tsort:: test_uname:: \
test_uniq:: test_unexpand:: test_unlink:: test_vdir:: test_wc:: test_yes::
172 changes: 126 additions & 46 deletions src/uu/sort/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,85 @@ use crate::{
compare_by, open,
};
use itertools::Itertools;
use std::{cmp::Ordering, ffi::OsStr};
#[cfg(not(target_os = "wasi"))]
use std::{
cmp::Ordering,
ffi::OsStr,
io::Read,
iter,
sync::mpsc::{Receiver, SyncSender, sync_channel},
thread,
};
use uucore::error::UResult;

fn buffer_size(settings: &GlobalSettings) -> usize {
if settings.buffer_size < 100 * 1024 {
// when the buffer size is smaller than 100KiB we choose it instead of the default.
// this improves testability.
settings.buffer_size
} else {
100 * 1024
}
}

/// Checks `chunk` against the end of `prev_chunk` (if any) and within itself.
///
/// Returns [`SortError::Disorder`] for the first line that violates the requested
/// ordering. `line_idx` is the running line count and is advanced as lines are checked.
fn check_chunk(
path: &OsStr,
settings: &GlobalSettings,
max_allowed_cmp: Ordering,
prev_chunk: Option<&Chunk>,
chunk: &Chunk,
line_idx: &mut usize,
) -> UResult<()> {
*line_idx += 1;
if let Some(prev_chunk) = prev_chunk {
// Check if the first element of the new chunk is greater than the last
// element from the previous chunk
let prev_last = prev_chunk.lines().last().unwrap();
let new_first = chunk.lines().first().unwrap();

if compare_by(
prev_last,
new_first,
settings,
prev_chunk.line_data(),
chunk.line_data(),
) > max_allowed_cmp
{
return Err(SortError::Disorder {
file: path.to_owned(),
line_number: *line_idx,
line: String::from_utf8_lossy(new_first.line).into_owned(),
silent: settings.check_silent,
}
.into());
}
}

for (a, b) in chunk.lines().iter().tuple_windows() {
*line_idx += 1;
if compare_by(a, b, settings, chunk.line_data(), chunk.line_data()) > max_allowed_cmp {
return Err(SortError::Disorder {
file: path.to_owned(),
line_number: *line_idx,
line: String::from_utf8_lossy(b.line).into_owned(),
silent: settings.check_silent,
}
.into());
}
}

Ok(())
}

/// Check if the file at `path` is ordered.
///
/// # Returns
///
/// The code we should exit with.
#[cfg(not(target_os = "wasi"))]
pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
let max_allowed_cmp = if settings.unique {
// If `unique` is enabled, the previous line must compare _less_ to the next one.
Expand All @@ -42,13 +106,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
move || reader(file, &recycled_receiver, &loaded_sender, &settings)
});
for _ in 0..2 {
let _ = recycled_sender.send(RecycledChunk::new(if settings.buffer_size < 100 * 1024 {
// when the buffer size is smaller than 100KiB we choose it instead of the default.
// this improves testability.
settings.buffer_size
} else {
100 * 1024
}));
let _ = recycled_sender.send(RecycledChunk::new(buffer_size(settings)));
}

let mut prev_chunk: Option<Chunk> = None;
Expand All @@ -60,47 +118,21 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
// disorder, the reader is usually still working at that point, so we shut it down
// in an orderly fashion below instead of just dropping our end.
'outer: for chunk in &loaded_receiver {
line_idx += 1;
if let Err(e) = check_chunk(
path,
settings,
max_allowed_cmp,
prev_chunk.as_ref(),
&chunk,
&mut line_idx,
) {
result = Err(e);
break 'outer;
}
if let Some(prev_chunk) = prev_chunk.take() {
// Check if the first element of the new chunk is greater than the last
// element from the previous chunk
let prev_last = prev_chunk.lines().last().unwrap();
let new_first = chunk.lines().first().unwrap();

if compare_by(
prev_last,
new_first,
settings,
prev_chunk.line_data(),
chunk.line_data(),
) > max_allowed_cmp
{
result = Err(SortError::Disorder {
file: path.to_owned(),
line_number: line_idx,
line: String::from_utf8_lossy(new_first.line).into_owned(),
silent: settings.check_silent,
}
.into());
break 'outer;
}
let _ = recycled_sender.send(prev_chunk.recycle());
}

for (a, b) in chunk.lines().iter().tuple_windows() {
line_idx += 1;
if compare_by(a, b, settings, chunk.line_data(), chunk.line_data()) > max_allowed_cmp {
result = Err(SortError::Disorder {
file: path.to_owned(),
line_number: line_idx,
line: String::from_utf8_lossy(b.line).into_owned(),
silent: settings.check_silent,
}
.into());
break 'outer;
}
}

prev_chunk = Some(chunk);
}

Expand All @@ -117,7 +149,55 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
result.and(reader_result)
}

/// Check if the file at `path` is ordered.
///
/// WASI has no threads, so chunks are read and checked on the current thread,
/// one chunk at a time, stopping as soon as a disorder is found.
#[cfg(target_os = "wasi")]
pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
let max_allowed_cmp = if settings.unique {
Ordering::Less
} else {
Ordering::Equal
};

let mut file = open(path)?;
let mut carry_over = vec![];
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
let mut prev_chunk: Option<Chunk> = None;
let mut line_idx = 0;
loop {
let recycled = RecycledChunk::new(buffer_size(settings));
let should_continue = chunks::read(
&sender,
recycled,
None,
&mut carry_over,
&mut file,
&mut std::iter::empty(),
settings.line_ending.into(),
settings,
)?;
while let Ok(chunk) = receiver.try_recv() {
check_chunk(
path,
settings,
max_allowed_cmp,
prev_chunk.as_ref(),
&chunk,
&mut line_idx,
)?;
prev_chunk = Some(chunk);
}
if !should_continue {
break;
}
}
Ok(())
}

/// The function running on the reader thread.
#[cfg(not(target_os = "wasi"))]
fn reader(
mut file: Box<dyn Read + Send>,
receiver: &Receiver<RecycledChunk>,
Expand Down
4 changes: 4 additions & 0 deletions src/uu/sort/src/ext_sort/wasi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ pub fn ext_sort(
// moderately sized inputs; very large files may cause OOM.
let mut input = Vec::new();
for file in files {
// Without a separator the last line of one file merges with the first line of the next.
if !input.is_empty() && input.last() != Some(&separator) {
input.push(separator);
}
file?.read_to_end(&mut input)?;
}

Expand Down
Loading
Loading