| Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 11h ago | 1 | // A `fmt` body may write repeatedly, so a formatter write appends rather than |
| 2 | // assigns. `UpperHex` here writes once per element. |
| 3 | use core::fmt; |
| 4 | |
| 5 | struct Bytes<'a>(&'a [u8]); |
| 6 | |
| 7 | impl fmt::UpperHex for Bytes<'_> { |
| 8 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 9 | for &b in self.0 { |
| 10 | write!(f, "{:02X}", b)?; |
| 11 | } |
| 12 | Ok(()) |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | impl fmt::LowerHex for Bytes<'_> { |
| 17 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 18 | for &b in self.0 { |
| 19 | write!(f, "{:02x}", b)?; |
| 20 | } |
| 21 | Ok(()) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | impl fmt::Display for Bytes<'_> { |
| 26 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 27 | f.write_str("<")?; |
| 28 | write!(f, "{self:x}")?; |
| 29 | f.write_str(">") |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn main() { |
| 34 | let raw: Vec<u8> = vec![0xab, 0xcd, 0x01, 0x00]; |
| 35 | println!("{:X}", Bytes(&raw)); |
| 36 | println!("{:x}", Bytes(&raw)); |
| 37 | println!("{}", Bytes(&raw)); |
| 38 | println!("[{}]", Bytes(&[])); |
| 39 | |
| 40 | // `debug_assert*` fires in debug builds, which is the profile modelled. |
| 41 | assert!(raw.len() == 4); |
| 42 | assert_eq!(raw.len(), 4); |
| 43 | assert_ne!(raw.len(), 5); |
| 44 | debug_assert_eq!(raw[0], 0xab); |
| 45 | println!("asserts passed"); |
| 46 | } |