Skip to content

Commit 61a55cc

Browse files
committed
wc: derive column width from the size of stdin
A regular file redirected onto stdin has a size known up front, so it sets the column width the same way a named file does, as GNU wc does. Pipes and other streams keep the minimum-width fallback.
1 parent a68dc1e commit 61a55cc

2 files changed

Lines changed: 94 additions & 15 deletions

File tree

‎src/uu/wc/src/wc.rs‎

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -776,14 +776,15 @@ fn word_count_from_input(input: &Input<'_>, settings: &Settings) -> CountResult
776776

777777
/// Compute the number of digits needed to represent all counts in all inputs.
778778
///
779-
/// For [`Inputs::Stdin`], [`MINIMUM_WIDTH`] is returned, unless there is only one counter number
780-
/// to be printed, in which case 1 is returned.
779+
/// For [`Inputs::Stdin`], the width is derived from the size of stdin when stdin is a regular
780+
/// file, and [`MINIMUM_WIDTH`] otherwise; if there is only one counter number to be printed,
781+
/// 1 is returned.
781782
///
782783
/// For [`Inputs::Files0From`], [`MINIMUM_WIDTH`] is returned.
783784
///
784785
/// An [`Inputs::Paths`] may include zero or more "-" entries, each of which represents reading
785-
/// from `stdin`. The presence of any such entry causes this function to return a width that is at
786-
/// least [`MINIMUM_WIDTH`].
786+
/// from `stdin`. Such an entry contributes the size of stdin when stdin is a regular file, and
787+
/// otherwise causes this function to return a width that is at least [`MINIMUM_WIDTH`].
787788
///
788789
/// If an [`Inputs::Paths`] contains only one path and only one number needs to be printed then
789790
/// this function is optimized to return 1 without making any calls to get file metadata.
@@ -794,7 +795,10 @@ fn word_count_from_input(input: &Input<'_>, settings: &Settings) -> CountResult
794795
fn compute_number_width(inputs: &Inputs, settings: &Settings) -> usize {
795796
match inputs {
796797
Inputs::Stdin if settings.number_enabled() == 1 => 1,
797-
Inputs::Stdin => MINIMUM_WIDTH,
798+
Inputs::Stdin => match stdin_size() {
799+
Some(size) => width_of(size, 1),
800+
None => MINIMUM_WIDTH,
801+
},
798802
Inputs::Files0From(_) => 1,
799803
Inputs::Paths(inputs) => {
800804
if settings.number_enabled() == 1 && inputs.len() == 1 {
@@ -805,7 +809,10 @@ fn compute_number_width(inputs: &Inputs, settings: &Settings) -> usize {
805809
let mut total: u64 = 0;
806810
for input in inputs {
807811
match input {
808-
Input::Stdin(_) => minimum_width = MINIMUM_WIDTH,
812+
Input::Stdin(_) => match stdin_size() {
813+
Some(size) => total += size,
814+
None => minimum_width = MINIMUM_WIDTH,
815+
},
809816
Input::Path(path) => {
810817
if let Ok(meta) = fs::metadata(path) {
811818
if meta.is_file() {
@@ -818,18 +825,50 @@ fn compute_number_width(inputs: &Inputs, settings: &Settings) -> usize {
818825
}
819826
}
820827

821-
if total == 0 {
822-
minimum_width
823-
} else {
824-
let total_width = (1 + total.ilog10())
825-
.try_into()
826-
.expect("ilog of a u64 should fit into a usize");
827-
max(total_width, minimum_width)
828-
}
828+
width_of(total, minimum_width)
829829
}
830830
}
831831
}
832832

833+
/// The width in digits of `total`, but never less than `minimum_width`.
834+
///
835+
/// A `total` of zero carries no information about the counts, so it leaves
836+
/// `minimum_width` untouched.
837+
fn width_of(total: u64, minimum_width: usize) -> usize {
838+
if total == 0 {
839+
minimum_width
840+
} else {
841+
let total_width = (1 + total.ilog10())
842+
.try_into()
843+
.expect("ilog of a u64 should fit into a usize");
844+
max(total_width, minimum_width)
845+
}
846+
}
847+
848+
/// The size of stdin, if stdin refers to a regular file.
849+
///
850+
/// Counts read from a stream of unknown length are formatted with
851+
/// [`MINIMUM_WIDTH`], but when stdin is a regular file its size is known up
852+
/// front and dictates the width the same way a named file's size does.
853+
fn stdin_size() -> Option<u64> {
854+
// Only Unix is handled: on Windows, `metadata()` of a pipe handle reports a
855+
// regular file of length 0, which would shrink the width to 1 instead of
856+
// falling back to `MINIMUM_WIDTH`.
857+
#[cfg(unix)]
858+
{
859+
use std::os::fd::AsFd;
860+
861+
let stdin = io::stdin();
862+
let cloned = stdin.as_fd().try_clone_to_owned().ok()?;
863+
let metadata = File::from(cloned).metadata().ok()?;
864+
metadata.is_file().then_some(metadata.len())
865+
}
866+
#[cfg(not(unix))]
867+
{
868+
None
869+
}
870+
}
871+
833872
type InputIterItem<'a> = Result<Input<'a>, Box<dyn UError>>;
834873

835874
/// To be used with `--files0-from=-`, this applies a filter on the results of [`files0_iter`] to

‎tests/by-util/test_wc.rs‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,45 @@ fn test_multiple_default() {
236236
));
237237
}
238238

239+
/// Test that the size of stdin dictates the display width when stdin is a
240+
/// regular file.
241+
///
242+
/// A stream of unknown length falls back to the minimum width, but a regular
243+
/// file redirected onto stdin has a size known up front, so it dictates the
244+
/// width just like a named file does.
245+
#[test]
246+
// `at_and_ucmd!` is only imported on unix in this file.
247+
#[cfg(unix)]
248+
#[uutests::wasi_ignore(StdioHandlesOpaque)]
249+
fn test_stdin_size_dictates_width() {
250+
use std::fs::File;
251+
252+
// lorem_ipsum.txt contains 772 bytes, a width of 3.
253+
let (at, mut ucmd) = at_and_ucmd!();
254+
ucmd.set_stdin(File::open(at.plus("lorem_ipsum.txt")).unwrap())
255+
.succeeds()
256+
.stdout_is(" 13 109 772\n");
257+
258+
// The same content piped in has no size known in advance, so the counts
259+
// are padded to the minimum width instead.
260+
new_ucmd!()
261+
.pipe_in_fixture("lorem_ipsum.txt")
262+
.succeeds()
263+
.stdout_is(" 13 109 772\n");
264+
265+
// "-" contributes the size of stdin to the total, so 772 + 302 = 1074
266+
// bytes give a width of 4.
267+
let (at, mut ucmd) = at_and_ucmd!();
268+
ucmd.args(&["-", "alice_in_wonderland.txt"])
269+
.set_stdin(File::open(at.plus("lorem_ipsum.txt")).unwrap())
270+
.succeeds()
271+
.stdout_is(concat!(
272+
" 13 109 772 -\n",
273+
" 5 57 302 alice_in_wonderland.txt\n",
274+
" 18 166 1074 total\n",
275+
));
276+
}
277+
239278
/// Test that the total size of all the files in the input dictates
240279
/// the display width.
241280
///
@@ -848,6 +887,7 @@ fn test_count_bytes_from_partial_stdin_offset(#[case] size: u64, #[case] offset:
848887

849888
#[cfg(unix)]
850889
#[test]
890+
#[uutests::wasi_ignore(StdioHandlesOpaque)]
851891
fn test_count_bytes_from_repeated_redirected_stdin() {
852892
use std::io::Seek;
853893
let (at, mut command) = at_and_ucmd!();
@@ -857,6 +897,6 @@ fn test_count_bytes_from_repeated_redirected_stdin() {
857897
.args(&["-c", "-", "-"])
858898
.set_stdin(input.try_clone().unwrap())
859899
.succeeds()
860-
.stdout_only(" 6 -\n 0 -\n 6 total\n");
900+
.stdout_only(" 6 -\n 0 -\n 6 total\n");
861901
assert_eq!(input.stream_position().unwrap(), 6);
862902
}

0 commit comments

Comments
 (0)