nandi/rustnimpublic Fork 0
0777223e3297e14f05bedeb07c87c7ff694732e2
Commits
Clone
git clone https://git.rickub.com/nandi/rustnim.git
git clone ssh://git@rickub.com/nandi/rustnim.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

028-formatter-and-asserts.rs · 46 lines · 1.2 KBRust Blame HistoryRaw
Add display.rs and the alloc half: all of base16ct now goes through afb2a6e nandithebull 17h ago1// A `fmt` body may write repeatedly, so a formatter write appends rather than
2// assigns. `UpperHex` here writes once per element.
3use core::fmt;
4
5struct Bytes<'a>(&'a [u8]);
6
7impl 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
16impl 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
25impl 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
33fn 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}