1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::{decode_inner, encoded_len, Error};
#[cfg(feature = "alloc")]
use crate::{decoded_len, String, Vec};
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
decode_inner(src.as_ref(), dst, decode_nibble)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn decode_vec(input: impl AsRef<[u8]>) -> Result<Vec<u8>, Error> {
let mut output = vec![0u8; decoded_len(input.as_ref())?];
decode(input, &mut output)?;
Ok(output)
}
pub fn encode<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a [u8], Error> {
let dst = dst
.get_mut(..encoded_len(src))
.ok_or(Error::InvalidLength)?;
for (src, dst) in src.iter().zip(dst.chunks_exact_mut(2)) {
dst[0] = encode_nibble(src >> 4);
dst[1] = encode_nibble(src & 0x0f);
}
Ok(dst)
}
pub fn encode_str<'a>(src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, Error> {
encode(src, dst).map(|r| unsafe { core::str::from_utf8_unchecked(r) })
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn encode_string(input: &[u8]) -> String {
let elen = encoded_len(input);
let mut dst = vec![0u8; elen];
let res = encode(input, &mut dst).expect("dst length is correct");
debug_assert_eq!(elen, res.len());
unsafe { String::from_utf8_unchecked(dst) }
}
#[inline(always)]
fn decode_nibble(src: u8) -> u16 {
let byte = src as i16;
let mut ret: i16 = -1;
ret += (((0x2fi16 - byte) & (byte - 0x3a)) >> 8) & (byte - 47);
ret += (((0x60i16 - byte) & (byte - 0x67)) >> 8) & (byte - 86);
ret as u16
}
#[inline(always)]
fn encode_nibble(src: u8) -> u8 {
let mut ret = src as i16 + 0x30;
ret += ((0x39i16 - ret) >> 8) & (0x61i16 - 0x3a);
ret as u8
}