Skip to content

Implement and forward more formatting traits for slices and arrays #46215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
18 changes: 17 additions & 1 deletion src/libcore/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,12 @@ macro_rules! array_impls {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug> fmt::Debug for [T; $N] {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&&self[..], f)
fmt::Debug::fmt(&self[..], f)
}
}

fmt_array_impls!($N, Octal, LowerHex, UpperHex, Pointer, Binary, LowerExp, UpperExp);

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> IntoIterator for &'a [T; $N] {
type Item = &'a T;
Expand Down Expand Up @@ -256,6 +258,20 @@ macro_rules! array_impls {
}
}

macro_rules! fmt_array_impls {
($N: expr, $( $Trait: ident ),+) => {
$(
#[unstable(feature = "slice_more_fmt_traits", issue = /* FIXME */ "0")]
impl<T: fmt::$Trait> fmt::$Trait for [T; $N] {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::$Trait::fmt(&self[..], f)
}
}
)+
}
}

array_impls! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
Expand Down
24 changes: 24 additions & 0 deletions src/libcore/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1699,6 +1699,30 @@ impl<T: Debug> Debug for [T] {
}
}

macro_rules! slice_impls {
($( $Trait: ident ),+) => {
$(
#[unstable(feature = "slice_more_fmt_traits", issue = /* FIXME */ "0")]
impl<T: $Trait> $Trait for [T] {
fn fmt(&self, f: &mut Formatter) -> Result {
f.write_char('[')?;
let mut iter = self.iter();
if let Some(item) = iter.next() {
$Trait::fmt(item, f)?;
for item in iter {
f.write_str(", ")?;
$Trait::fmt(item, f)?;
}
}
f.write_char(']')
}
}
)+
}
}

slice_impls!(Octal, LowerHex, UpperHex, Pointer, Binary, LowerExp, UpperExp);

#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for () {
fn fmt(&self, f: &mut Formatter) -> Result {
Expand Down
5 changes: 5 additions & 0 deletions src/libcore/tests/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ fn test_estimated_capacity() {
assert_eq!(format_args!("{}, hello!", "World").estimated_capacity(), 0);
assert_eq!(format_args!("{}. 16-bytes piece", "World").estimated_capacity(), 32);
}

#[test]
fn test_slice_hex() {
assert_eq!(format!("{:02X}", b"AZaz\0"), "[41, 5A, 61, 7A, 00]");
}