mirror of
https://github.com/fish-shell/fish-shell
synced 2024-12-26 12:53:13 +00:00
format: support whitespace padding in str formatting
This commit is contained in:
parent
e384e63b24
commit
b0ed37c2e0
2 changed files with 24 additions and 1 deletions
|
@ -478,7 +478,7 @@ impl Printf for &wstr {
|
|||
impl Printf for &str {
|
||||
fn format(&self, spec: &ConversionSpecifier) -> Result<WString> {
|
||||
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<WString> {
|
||||
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)
|
||||
}
|
||||
|
|
|
@ -29,6 +29,12 @@ fn check_fmt<T: Printf>(nfmt: &str, arg: T, expected: &str) {
|
|||
assert_eq!(our_result, expected);
|
||||
}
|
||||
|
||||
fn check_fmt_2<T: Printf, T2: Printf>(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]
|
||||
|
|
Loading…
Reference in a new issue