Skip to main content

otp/encoding/
hex.rs

1//! Base16 encoding/decoding, using [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648#section-8) alphabet.
2
3/// # Example:
4/// ```rust
5/// use otp::encoding::hex;
6///
7/// let bytes: [u8; 4] = [9, 10, 11, 12];
8/// let encoded = hex::encode(&bytes);
9/// assert_eq!("090a0b0c", encoded.as_str());
10/// ```
11pub fn encode(data: &[u8]) -> String {
12    data.iter()
13        .map(|&b| unsafe {
14            let i = 2 * b as usize;
15            HEX_BYTES.get_unchecked(i..i + 2)
16        })
17        .collect()
18}
19
20/// # Example:
21/// ```rust
22/// use otp::encoding::hex;
23///
24/// let input = "090A0B0C";
25/// let decoded = hex::decode(input).expect("Decoding failed");
26/// assert_eq!([9, 10, 11, 12], decoded.as_slice());
27///
28/// let input_odd_err = "090A0B0CZ";
29/// let result_odd_err = hex::decode(input_odd_err);
30/// assert!(matches!(result_odd_err, Err(hex::DecodeHexError::InvalidLength)));
31///
32/// let input_parse_int_err = "090A0B0CZZ";
33/// let result_parse_int_err = hex::decode(input_parse_int_err);
34/// assert!(matches!(result_parse_int_err, Err(hex::DecodeHexError::ParseInt(_))));
35/// ```
36pub fn decode(data: &str) -> Result<Vec<u8>, DecodeHexError> {
37    if data.len() & 1 != 0 {
38        Err(DecodeHexError::InvalidLength)
39    } else {
40        (0..data.len())
41            .step_by(2)
42            .map(|i| u8::from_str_radix(&data[i..i + 2], 16).map_err(DecodeHexError::ParseInt))
43            .collect()
44    }
45}
46
47#[derive(Debug)]
48pub enum DecodeHexError {
49    InvalidLength,
50    ParseInt(std::num::ParseIntError),
51}
52
53impl std::error::Error for DecodeHexError {}
54
55impl std::fmt::Display for DecodeHexError {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            DecodeHexError::ParseInt(e) => e.fmt(f),
59            DecodeHexError::InvalidLength => "input has an odd number of bytes".fmt(f),
60        }
61    }
62}
63
64const HEX_BYTES: &str = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\
65                         202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f\
66                         404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f\
67                         606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f\
68                         808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f\
69                         a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf\
70                         c0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedf\
71                         e0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff";