From 162f85773e11b0b0b016d3fdf9379c8fdd6f8530 Mon Sep 17 00:00:00 2001 From: Eli Youngs Date: Sat, 5 Feb 2022 00:43:09 -0800 Subject: [PATCH] printf: Support leading zeroes with %0n formatting --- src/uucore/src/lib/features/tokenize/sub.rs | 11 ++++++++++- tests/by-util/test_printf.rs | 8 ++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/uucore/src/lib/features/tokenize/sub.rs b/src/uucore/src/lib/features/tokenize/sub.rs index 6f9196d93..ac471ae3e 100644 --- a/src/uucore/src/lib/features/tokenize/sub.rs +++ b/src/uucore/src/lib/features/tokenize/sub.rs @@ -60,6 +60,7 @@ pub struct Sub { field_char: char, field_type: FieldType, orig: String, + prefix_char: char, } impl Sub { pub fn new( @@ -67,6 +68,7 @@ impl Sub { second_field: CanAsterisk>, field_char: char, orig: String, + prefix_char: char, ) -> Self { // for more dry printing, field characters are grouped // in initialization of token. @@ -90,6 +92,7 @@ impl Sub { field_char, field_type, orig, + prefix_char, } } } @@ -126,6 +129,11 @@ impl SubParser { fn build_token(parser: Self) -> Box { // not a self method so as to allow move of sub-parser vals. // return new Sub struct as token + let prefix_char = match &parser.min_width_tmp { + Some(width) if width.starts_with('0') => '0', + _ => ' ', + }; + let t: Box = Box::new(Sub::new( if parser.min_width_is_asterisk { CanAsterisk::Asterisk @@ -139,6 +147,7 @@ impl SubParser { }, parser.field_char.unwrap(), parser.text_so_far, + prefix_char, )); t } @@ -394,7 +403,7 @@ impl token::Token for Sub { final_str.push_str(&pre_min_width); } for _ in 0..diff { - final_str.push(' '); + final_str.push(self.prefix_char); } if pad_before { final_str.push_str(&pre_min_width); diff --git a/tests/by-util/test_printf.rs b/tests/by-util/test_printf.rs index f8f941ad8..b3e608dc9 100644 --- a/tests/by-util/test_printf.rs +++ b/tests/by-util/test_printf.rs @@ -437,3 +437,11 @@ fn stop_after_additional_escape() { .succeeds() .stdout_only("ABC"); } + +#[test] +fn sub_float_leading_zeroes() { + new_ucmd!() + .args(&["%010f", "1"]) + .succeeds() + .stdout_only("001.000000"); +}