pub struct Hex<'a> { /* private fields */ }Expand description
A borrowed hexadecimal view of a byte slice, available without allocation.
Display and LowerHex use lowercase digits;
UpperHex uses uppercase. Every byte produces two digits in
source order, including leading zeroes. The slice is borrowed, not copied.
This is a byte-sequence view: it does not interpret the input as an integer
or reverse bytes according to the machine’s endianness.
§Formatting
All three formatting traits use the following integer-style flags:
#adds0x, also for uppercase output and an empty slice.+adds a leading plus sign. Width includes the sign and prefix.- Width, fill and alignment apply to the complete value; default alignment is right. Width counts Unicode characters, so a non-ASCII fill character counts as one.
0pads after the sign/prefix, overriding fill and alignment.- Precision and
-are ignored. Precision never truncates a byte sequence.
§Allocation and writer errors
Available without alloc or std. Formatting uses bounded stack storage and
allocates no intermediate string; the destination writer may still allocate.
For example, format! allocates its resulting string, while write! can write
into existing storage.
An error from the writer is returned immediately and no further writes are attempted. Text already accepted by the writer remains written, including a partial write from the failing call. The number and size of writes are unspecified. To make output atomic, format into a separate buffer first.
§Examples
use faster_hex::Hex;
let bytes = [0, 0xab, 0xcd];
let hex = Hex::new(&bytes);
assert_eq!(format!("{hex}"), "00abcd");
assert_eq!(format!("{hex:#010X}"), "0x0000ABCD");
assert_eq!(format!("{hex:.2}"), "00abcd");Append to a text destination without creating an intermediate hex string:
use core::fmt::Write;
use faster_hex::Hex;
let mut output = String::with_capacity(64);
write!(output, "hash={:#X}", Hex::new(&[0, 0xab, 0xcd]))?;
assert_eq!(output, "hash=0x00ABCD");Implementations§
Source§impl<'a> Hex<'a>
impl<'a> Hex<'a>
Sourcepub const fn new(bytes: &'a [u8]) -> Self
pub const fn new(bytes: &'a [u8]) -> Self
Borrows bytes for hexadecimal formatting without copying or allocating.
The view cannot outlive bytes. It accepts an empty slice and is usable
in constant expressions. Creating a view does not perform any encoding.
§Examples
use faster_hex::Hex;
const ID: Hex<'static> = Hex::new(&[0, 0xab]);
assert_eq!(format!("{ID}"), "00ab");
assert_eq!(format!("{ID:#X}"), "0x00AB");