derive-hex 0.1.3

A simple companion macro for dusk-bytes crate
Documentation

derive-hex

derive-hex provides two small derive macros that implement hex formatting for types that expose a to_bytes() method.

This crate is primarily meant to be used alongside the [dusk-bytes] crate where to_bytes() is provided by the Serializable trait.

Derives

#[derive(Hex)] implements core::fmt::LowerHex ({:x} / {:#x}) and core::fmt::UpperHex ({:X} / {:#X}).

#[derive(HexDebug)] includes everything from Hex and additionally implements core::fmt::Debug. Ordinary {:?} formatting emits lowercase hexadecimal, while {:X?} emits uppercase hexadecimal; alternate forms add the 0x prefix.

Do not derive Hex or HexDebug for types containing secrets or other confidential material. Both derives expose the complete serialized representation: Hex through hexadecimal formatting such as {:x} and HexDebug additionally through ordinary debug formatting such as {:?}.

Both derives format the output by iterating over self.to_bytes() and writing each byte as two hexadecimal digits.

Example

use derive_hex::HexDebug;

#[derive(Copy, Clone, PartialEq, Eq, HexDebug)]
struct IdPrefix([u8; 4]);

impl IdPrefix {
    // The derives only require a `to_bytes()` method.
    pub fn to_bytes(&self) -> [u8; 4] {
        self.0
    }
}

let p = IdPrefix([0xde, 0xad, 0xbe, 0xef]);

assert_eq!(format!("{:x}", p), "deadbeef");
assert_eq!(format!("{:#x}", p), "0xdeadbeef");
assert_eq!(format!("{:X}", p), "DEADBEEF");

// `HexDebug` also formats ordinary and flagged debug output as hex.
assert_eq!(format!("{p:?}"), "deadbeef");
assert_eq!(format!("{:x?}", p), "deadbeef");
assert_eq!(format!("{:#X?}", p), "0xDEADBEEF");

License

Licensed under the Mozilla Public License 2.0 (MPL-2.0).