Skip to content

Commit

Permalink
printf: pad octal numbers with zeros on the left
Browse files Browse the repository at this point in the history
  • Loading branch information
tertsdiepraam committed Feb 7, 2024
1 parent 5c2ae5b commit 8904e50
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/uucore/src/lib/features/format/num_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
}
Expand Down
28 changes: 28 additions & 0 deletions tests/by-util/test_printf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<");
}

0 comments on commit 8904e50

Please sign in to comment.