From 7ea2bfbe2680e65e5a6774905a8f380888ca7a25 Mon Sep 17 00:00:00 2001 From: Jan Verbeek Date: Mon, 13 Sep 2021 21:19:49 -0400 Subject: [PATCH] seq: replace loops with a single format string Replace two loops that print leading and trailing 0s when printing a number in fixed-width mode with a single call to `write!()` with the appropriate formatting parameters. --- src/uu/seq/src/seq.rs | 17 ++++++++--------- tests/by-util/test_seq.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/uu/seq/src/seq.rs b/src/uu/seq/src/seq.rs index c4380fd3d..aac8f2280 100644 --- a/src/uu/seq/src/seq.rs +++ b/src/uu/seq/src/seq.rs @@ -317,6 +317,7 @@ fn print_seq( let mut i = 0isize; let is_first_minus_zero = first == -0.0 && first.is_sign_negative(); let mut value = first + i as f64 * increment; + let padding = if pad { padding + 1 + largest_dec } else { 0 }; let mut is_first_iteration = true; while !done_printing(&value, &increment, &last) { if !is_first_iteration { @@ -328,15 +329,13 @@ fn print_seq( width -= 1; } is_first_iteration = false; - let istr = format!("{:.*}", largest_dec, value); - let ilen = istr.len(); - let before_dec = istr.find('.').unwrap_or(ilen); - if pad && before_dec < width { - for _ in 0..(width - before_dec) { - write!(stdout, "0")?; - } - } - write!(stdout, "{}", istr)?; + write!( + stdout, + "{value:>0width$.precision$}", + value = value, + width = width, + precision = largest_dec, + )?; i += 1; value = first + i as f64 * increment; } diff --git a/tests/by-util/test_seq.rs b/tests/by-util/test_seq.rs index 51262ff23..27b5f99bc 100644 --- a/tests/by-util/test_seq.rs +++ b/tests/by-util/test_seq.rs @@ -426,6 +426,15 @@ fn test_width_decimal_scientific_notation_trailing_zeros_end() { .no_stderr(); } +#[test] +fn test_width_floats() { + new_ucmd!() + .args(&["-w", "9.0", "10.0"]) + .succeeds() + .stdout_is("09.0\n10.0\n") + .no_stderr(); +} + // TODO This is duplicated from `test_yes.rs`; refactor them. /// Run `seq`, capture some of the output, close the pipe, and verify it. fn run(args: &[&str], expected: &[u8]) {