From 4dae902429ee0a54a46cd219526a2493e312c3bf Mon Sep 17 00:00:00 2001 From: Terts Diepraam Date: Wed, 7 Feb 2024 12:38:25 +0100 Subject: [PATCH] printf: pad octal numbers with zeros on the left --- .../src/lib/features/format/num_format.rs | 8 ++++-- tests/by-util/test_printf.rs | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/uucore/src/lib/features/format/num_format.rs b/src/uucore/src/lib/features/format/num_format.rs index 607c028c3..819ba6a5f 100644 --- a/src/uucore/src/lib/features/format/num_format.rs +++ b/src/uucore/src/lib/features/format/num_format.rs @@ -143,11 +143,13 @@ impl Formatter for UnsignedInt { UnsignedIntVariant::Octal(Prefix::No) => format!("{x:o}"), UnsignedIntVariant::Octal(Prefix::Yes) => { // The prefix that rust uses is `0o`, but GNU uses `0`. - // We also need to take into account that 0 should not be 00 + // We also need to take into account that 0 should not be 00 and + // that GNU pads prefixed octals with zeros. + // // Since this is an unsigned int, we do not need to take the minus // sign into account. - if x == 0 { - format!("{x:o}") + if x < 8u64.pow(self.precision.saturating_sub(1) as u32) { + format!("{x:0>width$o}", width = self.precision) } else { format!("0{x:o}") } diff --git a/tests/by-util/test_printf.rs b/tests/by-util/test_printf.rs index db4c5aa7f..86d9060ae 100644 --- a/tests/by-util/test_printf.rs +++ b/tests/by-util/test_printf.rs @@ -680,3 +680,31 @@ fn char_as_byte() { fn no_infinite_loop() { new_ucmd!().args(&["a", "b"]).succeeds().stdout_only("a"); } + +#[test] +fn pad_octal_with_prefix() { + new_ucmd!() + .args(&[">%#15.6o<", "0"]) + .succeeds() + .stdout_only("> 000000<"); + + new_ucmd!() + .args(&[">%#15.6o<", "01"]) + .succeeds() + .stdout_only("> 000001<"); + + new_ucmd!() + .args(&[">%#15.6o<", "01234"]) + .succeeds() + .stdout_only("> 001234<"); + + new_ucmd!() + .args(&[">%#15.6o<", "012345"]) + .succeeds() + .stdout_only("> 012345<"); + + new_ucmd!() + .args(&[">%#15.6o<", "0123456"]) + .succeeds() + .stdout_only("> 0123456<"); +}