Module delog::hex

source ·
Expand description

Convenient Display and other traits for binary data.

Standard Rust uses the fmt::UpperHex and LowerHex traits to implement hexadecimal representations for use in format strings. For instance, format_args!("{:02X?}", &[7, 0xA1, 0xFF]) produces the string "[07, A1, FF]".

assert_eq!(format!("{:02X?}", [7u8, 0xA1, 0xFF].as_ref()), "[07, A1, FF]");

However, this only works for the Debug trait, not Display; needs extra dancing to pad with leading zeros, and is not very compact when debugging binary data formats.

The idea of this module is to generate newtypes around byte arrays/slices, and implement the fmt traits on these. In release builds, this is all compiled out and translates to direct instructions for the formatting machinery.

The ide to implement truncated outputs comes from the hex_fmt library, which we refer to for additional newtypes that can be used.

use delog::{hex_str, hexstr};

let data = &[7u8, 0xA1, 255, 0xC7];

assert_eq!(format!("{}", hexstr!(data)), "07A1FFC7");
assert_eq!(format!("{:x}", hexstr!(data)), "07a1ffc7");
assert_eq!(format!("{:2x}", hex_str!(data)), "07..c7");
assert_eq!(format!("{:<3x}", hex_str!(data)), "07 a1 ff..");
assert_eq!(format!("{:>3x}", hex_str!(data)), "..a1 ff c7");
assert_eq!(format!("{}", hex_str!(data, 2)), "07A1 FFC7");
assert_eq!(format!("{:<3}", hex_str!(data, sep: "|")), "07|A1|FF..");

Structs

  • Zero-sized wrapper newtype, allowing grouping bytes in blocks of N hexadecimals during formatting.
  • A type that represents the integer 1.

Traits

  • A type that specifies a separator str.
  • A type that specifies an unsigned integer.

Functions

  • Explicitly construct a newtype to format with.