diff --git a/src/uu/split/locales/en-US.ftl b/src/uu/split/locales/en-US.ftl index 99f506fce76..db7b461c67c 100644 --- a/src/uu/split/locales/en-US.ftl +++ b/src/uu/split/locales/en-US.ftl @@ -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 diff --git a/src/uu/split/locales/fr-FR.ftl b/src/uu/split/locales/fr-FR.ftl index d6e40230495..6b8bfaa9aee 100644 --- a/src/uu/split/locales/fr-FR.ftl +++ b/src/uu/split/locales/fr-FR.ftl @@ -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 diff --git a/src/uu/split/src/cli.rs b/src/uu/split/src/cli.rs index bf4fe9302c1..fe861c54c58 100644 --- a/src/uu/split/src/cli.rs +++ b/src/uu/split/src/cli.rs @@ -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"; } @@ -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') diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 7cd4283bdd0..10181591ef3 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -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, } @@ -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, }; @@ -1303,10 +1307,15 @@ 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; } @@ -1314,6 +1323,9 @@ fn n_chunks_by_line_round_robin( 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)?; @@ -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) -> io::Result { + 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 diff --git a/tests/by-util/test_split.rs b/tests/by-util/test_split.rs index c431fbeb5e7..37f3f5dd7d0 100644 --- a/tests/by-util/test_split.rs +++ b/tests/by-util/test_split.rs @@ -2662,6 +2662,50 @@ fn test_number_with_plus_prefix( assert_eq!(files, expected_files, "-n {number}"); } +#[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]