Skip to main content

codec_hex/
decode.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use crate::HexError;
6
7/// Decode canonical lowercase hexadecimal bytes.
8pub fn lower_hex_to_bytes(input: &str) -> Result<Vec<u8>, HexError> {
9    if !input.len().is_multiple_of(2) {
10        return Err(HexError::OddLength);
11    }
12
13    let mut output = Vec::with_capacity(input.len() / 2);
14    for pair in input.as_bytes().chunks_exact(2) {
15        let high = lower_hex_value(pair[0])?;
16        let low = lower_hex_value(pair[1])?;
17        output.push((high << 4) | low);
18    }
19
20    Ok(output)
21}
22
23fn lower_hex_value(byte: u8) -> Result<u8, HexError> {
24    match byte {
25        b'0'..=b'9' => Ok(byte - b'0'),
26        b'a'..=b'f' => Ok(byte - b'a' + 10),
27        b'A'..=b'F' => Err(HexError::Uppercase),
28        _ => Err(HexError::InvalidCharacter),
29    }
30}