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