Skip to main content

parse_hex

Function parse_hex 

Source
pub const fn parse_hex<const N: usize>(text: &str) -> Option<[u8; N]>
Expand description

Reads bytes written in hexadecimal, most significant first, as a network server shows a DevEUI, a JoinEUI or a root key.

It runs at compile time, so a program can take its identifiers from the environment it is built in, with env!, rather than keep a key in its source.

§Arguments

  • text - two hexadecimal digits for each byte, in either case, with nothing between.

§Returns

The bytes, or None when the text is not exactly two digits a byte or holds anything but hexadecimal digits.

§Examples

use pamoja_lorawan::parse_hex;

// In a firmware build: `parse_hex(env!("LORAWAN_DEV_EUI"))`.
const DEV_EUI: [u8; 8] = match parse_hex("70B3D57ED0051234") {
    Some(eui) => eui,
    None => panic!("a DevEUI is eight bytes of hexadecimal"),
};
assert_eq!(DEV_EUI, [0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x05, 0x12, 0x34]);

assert_eq!(parse_hex::<8>("70b3d57ed0051234"), Some(DEV_EUI));
assert_eq!(parse_hex::<8>("70B3D57ED00512"), None, "a byte short");
assert_eq!(parse_hex::<2>("0G12"), None, "not a hexadecimal digit");
assert_eq!(parse_hex::<2>("0x12"), None, "no prefix");