base16ct/
upper.rs

1use crate::{decode_inner, encoded_len, Error};
2#[cfg(feature = "alloc")]
3use crate::{decoded_len, String, Vec};
4
5/// Decode an upper 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 an upper 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/// Encode the input byte slice as upper Base16.
20///
21/// Writes the result into the provided destination slice, returning an
22/// ASCII-encoded upper Base16 (hex) string value.
23pub fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a [u8], Error> {
24    let dst = dst
25        .get_mut(..encoded_len(src))
26        .ok_or(Error::InvalidLength)?;
27    for (src, dst) in src.iter().zip(dst.chunks_exact_mut(2)) {
28        dst[0] = encode_nibble(src >> 4);
29        dst[1] = encode_nibble(src & 0x0f);
30    }
31    Ok(dst)
32}
33
34/// Encode input byte slice into a [`&str`] containing upper Base16 (hex).
35pub fn encode_str<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> {
36    encode(src, dst).map(|r| unsafe { core::str::from_utf8_unchecked(r) })
37}
38
39/// Encode input byte slice into a [`String`] containing upper Base16 (hex).
40///
41/// # Panics
42/// If `input` length is greater than `usize::MAX/2`.
43#[cfg(feature = "alloc")]
44#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
45pub fn encode_string(input: &[u8]) -> String {
46    let elen = encoded_len(input);
47    let mut dst = vec![0u8; elen];
48    let res = encode(input, &mut dst).expect("dst length is correct");
49
50    debug_assert_eq!(elen, res.len());
51    unsafe { crate::String::from_utf8_unchecked(dst) }
52}
53
54/// Decode a single nibble of upper hex
55#[inline(always)]
56fn decode_nibble(src: u8) -> u16 {
57    // 0-9  0x30-0x39
58    // A-F  0x41-0x46 or a-f  0x61-0x66
59    let byte = src as i16;
60    let mut ret: i16 = -1;
61
62    // 0-9  0x30-0x39
63    // if (byte > 0x2f && byte < 0x3a) ret += byte - 0x30 + 1; // -47
64    ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
65    // A-F  0x41-0x46
66    // if (byte > 0x40 && byte < 0x47) ret += byte - 0x41 + 10 + 1; // -54
67    ret += (((0x40i16 - byte) & (byte - 0x47)) >> 8) & (byte - 54);
68
69    ret as u16
70}
71
72/// Encode a single nibble of hex
73#[inline(always)]
74fn encode_nibble(src: u8) -> u8 {
75    let mut ret = src as i16 + 0x30;
76    // 0-9  0x30-0x39
77    // A-F  0x41-0x46
78    ret += ((0x39i16 - ret) >> 8) & (0x41i16 - 0x3a);
79    ret as u8
80}