Impl LowerHex For Wire Formats

Implement LowerHex and UpperHex so {:x} and {:X} render a custom struct as fixed-width hex wire fields, lowercase and uppercase.

RustData Integrity

Code

rustsnippet
28 lines
use std::fmt;

struct Packet {
    kind: u8,
    len: u16,
}

// LowerHex formats the wire fields in lowercase, kind 2 + len 4 digits
impl fmt::LowerHex for Packet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:02x}{:04x}", self.kind, self.len)
    }
}

// UpperHex: the uppercase variant of the same wire format
impl fmt::UpperHex for Packet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:02X}{:04X}", self.kind, self.len)
    }
}

fn main() {
    let packet = Packet { kind: 0x1a, len: 443 };

    // {:x} dispatches LowerHex; {:X} dispatches UpperHex
    println!("lower: {packet:x}");
    println!("upper: {packet:X}");
}

What the demo formats

Packet implements both hex traits over the same wire layout: LowerHex writes kind as two lowercase digits and len as four, so {packet:x} prints 1a01bb for kind 0x1a and len 443.

UpperHex mirrors it in capitals, and the second print shows 1A01BB. Width and zero-padding live inside the impl via the {:02x}/{:04x} specs, so callers get fixed-width wire fields from either specifier without any per-call formatting.

Points worth noting

  • The two traits are independent impls on the same struct.
  • Zero-padding at the impl level keeps every field fixed-width.

Interactive Tools for This Topic

FAQ

Why implement both hex traits?
Logs and wire dumps often want either case: {:x} and {:X} each dispatch to their own impl, and the demo prints both renderings of the same packet.