base16ct/
mixed.rs

1use crate::{decode_inner, Error};
2#[cfg(feature = "alloc")]
3use crate::{decoded_len, Vec};
4
5/// Decode a mixed Base16 (hex) string into the provided destination buffer.
6pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
7    decode_inner(src.as_ref(), dst, decode_nibble)
8}
9
10/// Decode a mixed Base16 (hex) string into a byte vector.
11#[cfg(feature = "alloc")]
12#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
13pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
14    let mut output = vec![0u8; decoded_len(input.as_ref())?];
15    decode(input, &mut output)?;
16    Ok(output)
17}
18
19/// Decode a single nibble of lower hex
20#[inline(always)]
21fn decode_nibble(src: u8) -> u16 {
22    // 0-9  0x30-0x39
23    // A-F  0x41-0x46 or a-f  0x61-0x66
24    let byte = src as i16;
25    let mut ret: i16 = -1;
26
27    // 0-9  0x30-0x39
28    // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47
29    ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
30    // A-F  0x41-0x46
31    // if (byte > 0x40 && byte < 0x47) ret += byte - 0x41 + 10 + 1; // -54
32    ret += (((0x40i16 - byte) & (byte - 0x47)) >> 8) & (byte - 54);
33    // a-f  0x61-0x66
34    // if (byte > 0x60 && byte < 0x67) ret += byte - 0x61 + 10 + 1; // -86
35    ret += (((0x60i16 - byte) & (byte - 0x67)) >> 8) & (byte - 86);
36
37    ret as u16
38}