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
35 changes: 17 additions & 18 deletions library/core/src/bstr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,39 +174,38 @@ impl fmt::Debug for ByteStr {
#[unstable(feature = "bstr", issue = "134915")]
impl fmt::Display for ByteStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fn fmt_nopad(this: &ByteStr, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for chunk in this.utf8_chunks() {
f.write_str(chunk.valid())?;
if !chunk.invalid().is_empty() {
f.write_str("\u{FFFD}")?;
}
}
Ok(())
}

let Some(align) = f.align() else {
return fmt_nopad(self, f);
};
let nchars: usize = self
.utf8_chunks()
.map(|chunk| {
chunk.valid().chars().count() + if chunk.invalid().is_empty() { 0 } else { 1 }
})
.sum();

let padding = f.width().unwrap_or(0).saturating_sub(nchars);
let fill = f.fill();
let (lpad, rpad) = match align {
fmt::Alignment::Left => (0, padding),
fmt::Alignment::Right => (padding, 0),
fmt::Alignment::Center => {

let (lpad, rpad) = match f.align() {
Some(fmt::Alignment::Right) => (padding, 0),
Some(fmt::Alignment::Center) => {
let half = padding / 2;
(half, half + padding % 2)
}
// Either alignment is not specified or it's left aligned
// which behaves the same with padding
_ => (0, padding),
};

for _ in 0..lpad {
write!(f, "{fill}")?;
}
fmt_nopad(self, f)?;

for chunk in self.utf8_chunks() {
f.write_str(chunk.valid())?;
if !chunk.invalid().is_empty() {
f.write_str("\u{FFFD}")?;
}
}

for _ in 0..rpad {
write!(f, "{fill}")?;
}
Expand Down
20 changes: 20 additions & 0 deletions library/std/tests/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2291,6 +2291,26 @@ fn display_format_flags() {
assert_eq!(format!("a{:#<5}b", Path::new("a").display()), "aa####b");
}

#[test]
fn display_path_with_padding_no_align() {
assert_eq!(format!("{:10}", Path::new("/foo/bar").display()), "/foo/bar ");
}

#[test]
fn display_path_with_padding_align_left() {
assert_eq!(format!("{:<10}", Path::new("/foo/bar").display()), "/foo/bar ");
}

#[test]
fn display_path_with_padding_align_right() {
assert_eq!(format!("{:>10}", Path::new("/foo/bar").display()), " /foo/bar");
}

#[test]
fn display_path_with_padding_align_center() {
assert_eq!(format!("{:^10}", Path::new("/foo/bar").display()), " /foo/bar ");
}

#[test]
fn into_rc() {
let orig = "hello/world";
Expand Down
Loading