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
1 change: 1 addition & 0 deletions src/uu/split/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ split-help-number = generate CHUNKS output files; see explanation below
split-help-additional-suffix = additional SUFFIX to append to output file names
split-help-filter = write to shell COMMAND; file name is $FILE (Currently not implemented for Windows)
split-help-elide-empty-files = do not generate empty output files with '-n'
split-help-unbuffered = immediately copy input to output with '-n r/...'
split-help-numeric-suffixes-short = use numeric suffixes starting at 0, not alphabetic
split-help-numeric-suffixes = same as -d, but allow setting the start value
split-help-hex-suffixes-short = use hex suffixes starting at 0, not alphabetic
Expand Down
1 change: 1 addition & 0 deletions src/uu/split/locales/fr-FR.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ split-help-number = générer CHUNKS fichiers de sortie ; voir l'explication ci-
split-help-additional-suffix = SUFFIXE supplémentaire à ajouter aux noms de fichiers de sortie
split-help-filter = écrire vers la COMMANDE shell ; le nom de fichier est $FILE (Actuellement non implémenté pour Windows)
split-help-elide-empty-files = ne pas générer de fichiers de sortie vides avec '-n'
split-help-unbuffered = copier immédiatement l'entrée vers la sortie avec '-n r/...'
split-help-numeric-suffixes-short = utiliser des suffixes numériques commençant à 0, pas alphabétiques
split-help-numeric-suffixes = identique à -d, mais permet de définir la valeur de départ
split-help-hex-suffixes-short = utiliser des suffixes hexadécimaux commençant à 0, pas alphabétiques
Expand Down
8 changes: 8 additions & 0 deletions src/uu/split/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub mod options {
pub const VERBOSE: &str = "verbose";
pub const SEPARATOR: &str = "separator";
pub const ELIDE_EMPTY_FILES: &str = "elide-empty-files";
pub const UNBUFFERED: &str = "unbuffered";
pub const IO_BLKSIZE: &str = "-io-blksize";
}

Expand Down Expand Up @@ -96,6 +97,13 @@ pub fn uu_app() -> Command {
.help(translate!("split-help-elide-empty-files"))
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::UNBUFFERED)
.long(options::UNBUFFERED)
.short('u')
.help(translate!("split-help-unbuffered"))
.action(ArgAction::SetTrue),
)
.arg(
Arg::new(options::NUMERIC_SUFFIXES_SHORT)
.short('d')
Expand Down
33 changes: 30 additions & 3 deletions src/uu/split/src/split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,9 @@ struct Settings {
/// chunks. If this is `false`, then empty files will not be
/// created.
elide_empty_files: bool,
/// `-u`: with `-n r/...`, pass input on as soon as it is read, even part
/// of a record. Output files and filters are not buffered anyway.
unbuffered: bool,
io_blksize: Option<u64>,
}

Expand Down Expand Up @@ -379,6 +382,7 @@ impl Settings {
verbose: matches.value_source(options::VERBOSE) == Some(ValueSource::CommandLine),
separator,
elide_empty_files: matches.get_flag(options::ELIDE_EMPTY_FILES),
unbuffered: matches.get_flag(options::UNBUFFERED),
io_blksize,
};

Expand Down Expand Up @@ -1303,17 +1307,25 @@ fn n_chunks_by_line_round_robin(
let mut line = Vec::new();
loop {
line.clear();
let num_bytes_read = reader.by_ref().read_until(sep, &mut line)?;
let record_complete = if settings.unbuffered {
read_available(&mut reader, sep, &mut line)?
} else {
reader.by_ref().read_until(sep, &mut line)?;
true
};

// if there is nothing else to read - exit the loop
if num_bytes_read == 0 {
if line.is_empty() {
break;
}

let bytes = line.as_slice();
if let Some(chunk_number) = kth_chunk {
if (i % num_chunks) == chunk_number - 1 {
stdout_writer.write_all(bytes)?;
if settings.unbuffered {
stdout_writer.flush()?;
}
}
} else {
let writer = out_files.get_writer((i % num_chunks) as usize, settings)?;
Expand All @@ -1326,11 +1338,26 @@ fn n_chunks_by_line_round_robin(
break;
}
}
i += 1;
if record_complete {
i += 1;
}
}
Ok(())
}

/// For `-u`: append to `line` what has been read so far, up to and including
/// `sep`, without waiting for the rest of the record. Returns whether the
/// record is complete. Kept out of line so the buffered loop stays as fast.
#[inline(never)]
fn read_available(reader: &mut impl BufRead, sep: u8, line: &mut Vec<u8>) -> io::Result<bool> {
let available = reader.fill_buf()?;
let end = memchr::memchr(sep, available).map(|pos| pos + 1);
let len = end.unwrap_or(available.len());
line.extend_from_slice(&available[..len]);
reader.consume(len);
Ok(end.is_some())
}

/// Like `io::Lines`, but includes the line ending character.
///
/// This struct is generally created by calling `lines_with_sep` on a
Expand Down
44 changes: 44 additions & 0 deletions tests/by-util/test_split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2662,6 +2662,50 @@ fn test_number_with_plus_prefix(
assert_eq!(files, expected_files, "-n {number}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this gives the same output with or without -u. Could you please add a case with records longer than the buffer (---io-blksize=2)? That is where record_complete matters.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_unbuffered_record_longer_than_buffer with ---io-blksize=2, to files and with r/K/N. It fails if the chunk number moves on after a partial record.

}

#[test]
fn test_unbuffered() {
let (at, mut ucmd) = at_and_ucmd!();
ucmd.args(&["-u", "-n", "r/2"])
.pipe_in("1\n2\n3\n4\n5\n")
.succeeds()
.no_output();
assert_eq!(at.read("xaa"), "1\n3\n5\n");
assert_eq!(at.read("xab"), "2\n4\n");

new_ucmd!()
.args(&["--unbuffered", "-t", "\\0", "-n", "r/2/3"])
.pipe_in("1\x002\x003\x004\x005\x00")
.succeeds()
.stdout_is("2\x005\x00");

// The other modes accept it too, where it changes nothing.
let (at, mut ucmd) = at_and_ucmd!();
ucmd.args(&["-u", "-l", "2"])
.pipe_in("1\n2\n3\n")
.succeeds()
.no_output();
assert_eq!(at.read("xaa"), "1\n2\n");
assert_eq!(at.read("xab"), "3\n");
}

#[test]
fn test_unbuffered_record_longer_than_buffer() {
let input = "abcde\nf\nghijk\nl\n";
let (at, mut ucmd) = at_and_ucmd!();
ucmd.args(&["-u", "---io-blksize=2", "-n", "r/2"])
.pipe_in(input)
.succeeds()
.no_output();
assert_eq!(at.read("xaa"), "abcde\nghijk\n");
assert_eq!(at.read("xab"), "f\nl\n");

new_ucmd!()
.args(&["-u", "---io-blksize=2", "-n", "r/1/2"])
.pipe_in(input)
.succeeds()
.stdout_only("abcde\nghijk\n");
}

#[cfg(unix)]
#[uutests::wasi_ignore(NoSubprocessSpawning)]
#[test]
Expand Down
Loading