From b0ed37c2e04829952f5b1be22895ee683f160f81 Mon Sep 17 00:00:00 2001 From: Neeraj Jaiswal Date: Fri, 24 Feb 2023 21:26:13 +0530 Subject: [PATCH] format: support whitespace padding in str formatting --- fish-rust/src/wutil/format/format.rs | 18 +++++++++++++++++- fish-rust/src/wutil/format/tests.rs | 7 +++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/fish-rust/src/wutil/format/format.rs b/fish-rust/src/wutil/format/format.rs index bab7bcb92..b71e3203b 100644 --- a/fish-rust/src/wutil/format/format.rs +++ b/fish-rust/src/wutil/format/format.rs @@ -478,7 +478,7 @@ impl Printf for &wstr { impl Printf for &str { fn format(&self, spec: &ConversionSpecifier) -> Result { if spec.conversion_type == ConversionType::String { - Ok((*self).into()) + add_padding((*self).into(), spec) } else { Err(PrintfError::WrongType) } @@ -514,3 +514,19 @@ impl Printf for &WString { self.as_utfstr().format(spec) } } + +fn add_padding(mut s: WString, spec: &ConversionSpecifier) -> Result { + let width: usize = match spec.width { + NumericParam::Literal(w) => w, + _ => { + return Err(PrintfError::Unknown); // should not happen at this point!! + } + } + .try_into() + .unwrap_or_default(); + if s.len() < width { + let padding = L!(" ").repeat(width - s.len()); + s.insert_utfstr(0, &padding); + }; + Ok(s) +} diff --git a/fish-rust/src/wutil/format/tests.rs b/fish-rust/src/wutil/format/tests.rs index 309a7e507..94fce7c29 100644 --- a/fish-rust/src/wutil/format/tests.rs +++ b/fish-rust/src/wutil/format/tests.rs @@ -29,6 +29,12 @@ fn check_fmt(nfmt: &str, arg: T, expected: &str) { assert_eq!(our_result, expected); } +fn check_fmt_2(nfmt: &str, arg: T, arg2: T2, expected: &str) { + let fmt: WString = nfmt.into(); + let our_result = sprintf!(&fmt, arg, arg2); + assert_eq!(our_result, expected); +} + #[test] fn test_int() { check_fmt("%d", 12, "12"); @@ -89,6 +95,7 @@ fn test_str() { "test % with string: FOO yay\n", ); check_fmt("test char %c", '~', "test char ~"); + check_fmt_2("%*ls", 5, "^", " ^"); } #[test]