| Add trait impls and slice iterators; base16ct's decoder now goes through ae9f986 nandithebull 17h ago | 1 | use crate::{Error, decode_inner}; |
| 2 | #[cfg(feature = "alloc")] |
| 3 | use crate::{Vec, decoded_len}; |
| 4 | |
| 5 | /// Decode a mixed Base16 (hex) string into the provided destination buffer. |
| 6 | pub 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 | pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> { |
| 13 | let mut output = vec![0u8; decoded_len(input.as_ref())?]; |
| 14 | decode(input, &mut output)?; |
| 15 | Ok(output) |
| 16 | } |
| 17 | |
| 18 | /// Decode a single nibble of lower hex |
| 19 | #[inline(always)] |
| 20 | fn decode_nibble(src: u8) -> u16 { |
| 21 | // 0-9 0x30-0x39 |
| 22 | // A-F 0x41-0x46 or a-f 0x61-0x66 |
| 23 | let byte = src as i16; |
| 24 | let mut ret: i16 = -1; |
| 25 | |
| 26 | // 0-9 0x30-0x39 |
| 27 | // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47 |
| 28 | 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 | 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 | ret += (((0x60i16 - byte) & (byte - 0x67)) >> 8) & (byte - 86); |
| 35 | |
| 36 | ret as u16 |
| 37 | } |