diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index cf6262bda9748..7bb395bb644c7 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -1630,6 +1630,38 @@ impl Debug for *mut T { fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) } } +// Implementation of specific formatters for slices of supporting types + +macro_rules! additional_slice_formatting { + ($($tr:ident),*) => { + $( + #[stable(feature = "additional_slice_formatting", since = "1.22.0")] + impl $tr for [T] { + fn fmt(&self, f: &mut Formatter) -> Result { + let mut has_items = false; + + f.write_str("[")?; + + for i in self.iter() { + if has_items { + f.write_str(", ")?; + } + + ::fmt(i, f)?; + has_items = true; + } + + f.write_str("]")?; + + Ok(()) + } + } + )* + } +} + +additional_slice_formatting!( Binary, Octal, LowerHex, UpperHex, LowerExp, UpperExp, Pointer ); + macro_rules! peel { ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) } diff --git a/src/libcore/tests/fmt/mod.rs b/src/libcore/tests/fmt/mod.rs index 5d204c7d523d6..5d4a7d8a50429 100644 --- a/src/libcore/tests/fmt/mod.rs +++ b/src/libcore/tests/fmt/mod.rs @@ -38,3 +38,22 @@ 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_additional_slice_formatting() { + let a: &[u8] = &[1, 2, 7, 8, 120, 255]; + let b: &[f32] = &[3e5, 5e7]; + + // Test all hex forms + assert_eq!(format!("{:x}", a), "[1, 2, 7, 8, 78, ff]"); + assert_eq!(format!("{:X}", a), "[1, 2, 7, 8, 78, FF]"); + assert_eq!(format!("{:02x}", a), "[01, 02, 07, 08, 78, ff]"); + assert_eq!(format!("{:#x}", a), "[0x1, 0x2, 0x7, 0x8, 0x78, 0xff]"); + assert_eq!(format!("{:#04x}", a), "[0x01, 0x02, 0x07, 0x08, 0x78, 0xff]"); + + // Superficial tests for the rest of the forms + assert_eq!(format!("{:o}", a), "[1, 2, 7, 10, 170, 377]"); + assert_eq!(format!("{:b}", a), "[1, 10, 111, 1000, 1111000, 11111111]"); + assert_eq!(format!("{:e}", b), "[3e5, 5e7]"); + assert_eq!(format!("{:E}", b), "[3E5, 5E7]"); +}