nandi/rustnimpublic Fork 0
99b837678a29fedd20bb68a5117a6621d8d178b4
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.

Add display.rs and the alloc half: all of base16ct now goes through afb2a6e · on 99b837678a29fedd20bb68a5117a6621d8d178b4 · nandithebull · 6h ago
028-formatter-and-asserts.rs · 46 lines · 1.2 KBRust Blame HistoryRaw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// A `fmt` body may write repeatedly, so a formatter write appends rather than
// assigns. `UpperHex` here writes once per element.
use core::fmt;

struct Bytes<'a>(&'a [u8]);

impl fmt::UpperHex for Bytes<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for &b in self.0 {
            write!(f, "{:02X}", b)?;
        }
        Ok(())
    }
}

impl fmt::LowerHex for Bytes<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for &b in self.0 {
            write!(f, "{:02x}", b)?;
        }
        Ok(())
    }
}

impl fmt::Display for Bytes<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("<")?;
        write!(f, "{self:x}")?;
        f.write_str(">")
    }
}

fn main() {
    let raw: Vec<u8> = vec![0xab, 0xcd, 0x01, 0x00];
    println!("{:X}", Bytes(&raw));
    println!("{:x}", Bytes(&raw));
    println!("{}", Bytes(&raw));
    println!("[{}]", Bytes(&[]));

    // `debug_assert*` fires in debug builds, which is the profile modelled.
    assert!(raw.len() == 4);
    assert_eq!(raw.len(), 4);
    assert_ne!(raw.len(), 5);
    debug_assert_eq!(raw[0], 0xab);
    println!("asserts passed");
}