Skip to main content

hex_encode

Function hex_encode 

Source
pub fn hex_encode<'a>(
    src: &[u8],
    dst: &'a mut [u8],
) -> Result<&'a mut str, Error>
Expand description

Encodes all of src as lowercase hex into dst without allocation.

Every input byte produces two ASCII digits. dst must have room for at least src.len() * 2 bytes; extra capacity is allowed and remains unchanged. The returned string covers only the written prefix and borrows only dst, so src can be dropped or reused while the result is still in use.

No prefix or separators are written. Empty input returns an empty string and leaves dst unchanged. For uppercase digits, use hex_encode_upper.

§Errors

Returns Error::Overflow if the encoded length cannot be represented as a usize, or Error::OutputTooSmall if dst is too short. Its required field is the full output size in bytes. The entire destination is unchanged on either error; a short buffer is never partially filled.

§Examples

use faster_hex::hex_encode;

let mut destination = [0xff; 8];
let text = hex_encode(&[0, 0xab, 0xcd], &mut destination)?;
assert_eq!(text, "00abcd");
// Only the returned prefix is modified.
text.make_ascii_uppercase();
assert_eq!(&destination[..6], b"00ABCD");
assert_eq!(&destination[6..], &[0xff; 2]);

An insufficient destination is reported without modifying it:

use faster_hex::{hex_encode, Error};

let mut destination = [0xa5; 3];
assert!(matches!(hex_encode(&[0xab, 0xcd], &mut destination),
    Err(Error::OutputTooSmall { required: 4, .. })));
assert_eq!(destination, [0xa5; 3]);