diff --git a/library/core/src/bstr/mod.rs b/library/core/src/bstr/mod.rs index 34e1ea66c99ad..2be7dfc9bfdda 100644 --- a/library/core/src/bstr/mod.rs +++ b/library/core/src/bstr/mod.rs @@ -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}")?; } diff --git a/library/std/tests/path.rs b/library/std/tests/path.rs index 4094b7acd8749..8997b8ad192dc 100644 --- a/library/std/tests/path.rs +++ b/library/std/tests/path.rs @@ -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";