1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

printf: pad octal numbers with zeros on the left

This commit is contained in:
Terts Diepraam 2024-02-07 12:38:25 +01:00 committed by Daniel Hofstetter
parent d4ee5ebc85
commit 4dae902429
2 changed files with 33 additions and 3 deletions

View file

@ -143,11 +143,13 @@ impl Formatter for UnsignedInt {
UnsignedIntVariant::Octal(Prefix::No) => format!("{x:o}"), UnsignedIntVariant::Octal(Prefix::No) => format!("{x:o}"),
UnsignedIntVariant::Octal(Prefix::Yes) => { UnsignedIntVariant::Octal(Prefix::Yes) => {
// The prefix that rust uses is `0o`, but GNU uses `0`. // 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 // Since this is an unsigned int, we do not need to take the minus
// sign into account. // sign into account.
if x == 0 { if x < 8u64.pow(self.precision.saturating_sub(1) as u32) {
format!("{x:o}") format!("{x:0>width$o}", width = self.precision)
} else { } else {
format!("0{x:o}") format!("0{x:o}")
} }

View file

@ -680,3 +680,31 @@ fn char_as_byte() {
fn no_infinite_loop() { fn no_infinite_loop() {
new_ucmd!().args(&["a", "b"]).succeeds().stdout_only("a"); 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<");
}