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

hex-literal

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

16 releases (1 stable)

Uses new Rust 2024

1.0.0 Feb 22, 2025
0.4.1 Apr 5, 2023
0.3.4 Nov 11, 2021
0.3.3 Jul 17, 2021
0.1.1 Feb 9, 2018

#8 in Value formatting

Download history 215395/week @ 2024-11-22 241960/week @ 2024-11-29 247788/week @ 2024-12-06 228578/week @ 2024-12-13 114577/week @ 2024-12-20 112348/week @ 2024-12-27 210696/week @ 2025-01-03 246625/week @ 2025-01-10 230914/week @ 2025-01-17 240009/week @ 2025-01-24 256834/week @ 2025-01-31 271657/week @ 2025-02-07 256985/week @ 2025-02-14 282198/week @ 2025-02-21 272905/week @ 2025-02-28 221941/week @ 2025-03-07

1,078,390 downloads per month
Used in 1,951 crates (923 directly)

MIT/Apache

9KB
74 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"
);

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