pub fn hex_decode<'a>(
src: &[u8],
dst: &'a mut [u8],
) -> Result<&'a mut [u8], Error>Expand description
Decodes all of src into dst without allocation, accepting either letter case.
src must contain an even number of ASCII hex digits, without a prefix,
whitespace or separators. Uppercase and lowercase digits may be mixed. Leading
zeroes are preserved as bytes; this converts a byte sequence, not an integer.
dst must have at least src.len() / 2 bytes. The returned mutable slice
covers exactly the written prefix and borrows only dst. Spare destination
bytes remain unchanged. Empty input returns an empty slice and changes nothing.
Use hex_decode_with_case to restrict letter case, or hex_decode_array
when the decoded size must match a fixed array exactly.
§Errors
Errors are checked in this order:
Error::OddLengthif the input has an odd number of bytes.Error::OutputTooSmallif the destination is too small.requiredcounts the full decoded output size in bytes.Error::InvalidCharfor the first invalid input byte.indexis a zero-based byte offset insrc, not a Unicode character position.
Every error leaves the entire destination unchanged, including when an
invalid byte occurs after a long valid prefix. A short destination never
causes silent prefix decoding; slice src explicitly if that is intended.
§Examples
use faster_hex::hex_decode;
let mut destination = [0xa5; 5];
let bytes = {
let source = *b"00aBcD";
hex_decode(&source, &mut destination)?
}; // The source is no longer needed.
assert_eq!(bytes, &[0, 0xab, 0xcd]);
bytes[0] = 0xff;
assert_eq!(destination, [0xff, 0xab, 0xcd, 0xa5, 0xa5]);Invalid input does not commit a partial result:
use faster_hex::{hex_decode, Error};
let mut destination = [0xa5; 3];
assert!(matches!(hex_decode(b"00ff0g", &mut destination),
Err(Error::InvalidChar { index: 5, byte: b'g', .. })));
assert_eq!(destination, [0xa5; 3]);