Skip to content

Commit 9521e7a

Browse files
authored
hex-literal: use const block to force const promotion (#1153)
Also includes minor code tweaks.
1 parent 6045028 commit 9521e7a

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

hex-literal/src/lib.rs

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
#![doc = include_str!("../README.md")]
21
#![no_std]
2+
#![doc = include_str!("../README.md")]
33
#![doc(
44
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
55
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
@@ -56,23 +56,22 @@ pub const fn len(strings: &[&[u8]]) -> usize {
5656
///
5757
/// This function is an implementation detail and SHOULD NOT be called directly!
5858
#[doc(hidden)]
59-
pub const fn decode<const LEN: usize>(strings: &[&[u8]]) -> [u8; LEN] {
60-
let mut i = 0;
59+
pub const fn decode<const LEN: usize>(strings: &[&[u8]]) -> Option<[u8; LEN]> {
60+
let mut string_pos = 0;
6161
let mut buf = [0u8; LEN];
6262
let mut buf_pos = 0;
63-
while i < strings.len() {
63+
while string_pos < strings.len() {
6464
let mut pos = 0;
65-
while let Some((byte, new_pos)) = next_byte(strings[i], pos) {
65+
let string = &strings[string_pos];
66+
string_pos += 1;
67+
68+
while let Some((byte, new_pos)) = next_byte(string, pos) {
6669
buf[buf_pos] = byte;
6770
buf_pos += 1;
6871
pos = new_pos;
6972
}
70-
i += 1;
7173
}
72-
if LEN != buf_pos {
73-
panic!("Length mismatch. Please report this bug.");
74-
}
75-
buf
74+
if LEN == buf_pos { Some(buf) } else { None }
7675
}
7776

7877
/// Macro for converting sequence of string literals containing hex-encoded data
@@ -81,8 +80,9 @@ pub const fn decode<const LEN: usize>(strings: &[&[u8]]) -> [u8; LEN] {
8180
macro_rules! hex {
8281
($($s:literal)*) => {{
8382
const STRINGS: &[&'static [u8]] = &[$($s.as_bytes(),)*];
84-
const LEN: usize = $crate::len(STRINGS);
85-
const RES: [u8; LEN] = $crate::decode(STRINGS);
86-
RES
83+
const {
84+
$crate::decode::<{ $crate::len(STRINGS) }>(STRINGS)
85+
.expect("Output array length should be correct")
86+
}
8787
}};
8888
}

0 commit comments

Comments
 (0)