Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,29 @@ impl Printf for f32 {
impl Printf for &str {
fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
if spec.conversion_type == ConversionType::String {
Ok((*self).to_owned())
let mut s = String::new();

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 spec.left_adj {
s.push_str(self);
while s.len() < width {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a shame String has no resize() method like Vec does... (but I suppose that wouldn't work well with multi-byte characters)

s.push(' ');
}
} else {
while s.len() + self.len() < width {
s.push(' ');
}
s.push_str(self);
}
Ok(s)
} else {
Err(PrintfError::WrongType)
}
Expand All @@ -486,7 +508,27 @@ impl Printf for char {
fn format(&self, spec: &ConversionSpecifier) -> Result<String> {
if spec.conversion_type == ConversionType::Char {
let mut s = String::new();
s.push(*self);

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 spec.left_adj {
s.push(*self);
while s.len() < width {
s.push(' ');
}
} else {
while s.len() + self.len_utf8() < width {
s.push(' ');
}
s.push(*self);
}
Ok(s)
} else {
Err(PrintfError::WrongType)
Expand Down
6 changes: 6 additions & 0 deletions tests/compare_to_libc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ fn test_str() {
let c_string = CString::new("test").unwrap();
check_fmt("%s", c_string.as_c_str());
check_fmt("%s", c_string);
check_fmt_s("%4s", "A");
check_fmt_s("%4s", "𒀀"); // multi-byte character test (4 bytes)
check_fmt_s("%-4sX", "A");
check_fmt_s("%-4sX", "𒀀"); // multi-byte character test (4 bytes)
}

#[test]
Expand All @@ -125,6 +129,8 @@ fn test_char() {
check_fmt("%c", b'x' as c_char);
check_fmt("%c", u16::try_from('x').unwrap());
check_fmt("%c", u32::try_from('x').unwrap());
check_fmt("%4c", 'A');
check_fmt("%-4cX", 'A');
}

#[test]
Expand Down