#hex-string #byte-array #hex #string-literal #compile-time #literals #macro

hex-literal

Macro for converting hexadecimal string to a byte array at compile time

15 releases

0.4.1 Apr 5, 2023
0.3.4 Nov 11, 2021
0.3.3 Jul 17, 2021
0.3.1 Aug 2, 2020
0.1.1 Feb 9, 2018

#8 in Value formatting

Download history 198238/week @ 2024-08-16 218006/week @ 2024-08-23 212846/week @ 2024-08-30 227216/week @ 2024-09-06 196609/week @ 2024-09-13 225617/week @ 2024-09-20 225408/week @ 2024-09-27 241881/week @ 2024-10-04 237289/week @ 2024-10-11 247106/week @ 2024-10-18 232480/week @ 2024-10-25 221940/week @ 2024-11-01 222970/week @ 2024-11-08 251187/week @ 2024-11-15 215395/week @ 2024-11-22 203107/week @ 2024-11-29

933,078 downloads per month
Used in 2,027 crates (863 directly)

MIT/Apache

9KB
75 lines

RustCrypto: hex-literal

Crate Docs Apache 2.0/MIT Licensed MSRV Build Status

This crate provides the hex! macro for converting hexadecimal string literals to a byte array at compile time.

It accepts the following characters in the input string:

  • '0'...'9', 'a'...'f', 'A'...'F' — hex characters which will be used in construction of the output byte array
  • ' ', '\r', '\n', '\t' — formatting characters which will be ignored

Examples

use hex_literal::hex;

// The macro can be used in const contexts
const DATA: [u8; 4] = hex!("01020304");
assert_eq!(DATA, [1, 2, 3, 4]);

// Both upper and lower hex values are supported
assert_eq!(hex!("a1 b2 c3 d4"), [0xA1, 0xB2, 0xC3, 0xD4]);
assert_eq!(hex!("E5 E6 90 92"), [0xE5, 0xE6, 0x90, 0x92]);
assert_eq!(hex!("0a0B 0C0d"), [10, 11, 12, 13]);

// Multi-line literals
let bytes1 = hex!("
    00010203 04050607
    08090a0b 0c0d0e0f
");
assert_eq!(
    bytes1,
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
);

// It's possible to use several literals
// (results will be concatenated)
let bytes2 = hex!(
    "00010203 04050607" // first half
    "08090a0b 0c0d0e0f" // second half
);
assert_eq!(bytes1, bytes2);

Using an unsupported character inside literals will result in a compilation error:

hex_literal::hex!("АА"); // Cyrillic "А"
hex_literal::hex!("11 22"); // Japanese space

Сomments inside literals are not supported:

hex_literal::hex!("0123 // foo");

Each literal must contain an even number of hex characters:

hex_literal::hex!(
    "01234"
    "567"
);

Minimum Supported Rust Version

Rust 1.57 or newer.

In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this crate's SemVer guarantees), however when we do it will be accompanied by a minor version bump.

License

Licensed under either of:

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps