base16ct/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
5    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
6)]
7#![warn(
8    clippy::mod_module_files,
9    clippy::unwrap_used,
10    missing_docs,
11    rust_2018_idioms,
12    unused_lifetimes,
13    unused_qualifications
14)]
15
16//! Pure Rust implementation of Base16 ([RFC 4648], a.k.a. hex).
17//!
18//! Implements lower and upper case Base16 variants without data-dependent branches
19//! or lookup  tables, thereby providing portable "best effort" constant-time
20//! operation. Not constant-time with respect to message length (only data).
21//!
22//! Supports `no_std` environments and avoids heap allocations in the core API
23//! (but also provides optional `alloc` support for convenience).
24//!
25//! Based on code from: <https://github.com/Sc00bz/ConstTimeEncoding/blob/master/hex.cpp>
26//!
27//! # Examples
28//! ```
29//! let lower_hex_str = "abcd1234";
30//! let upper_hex_str = "ABCD1234";
31//! let mixed_hex_str = "abCD1234";
32//! let raw = b"\xab\xcd\x12\x34";
33//!
34//! let mut buf = [0u8; 16];
35//! // length of return slice can be different from the input buffer!
36//! let res = base16ct::lower::decode(lower_hex_str, &mut buf).unwrap();
37//! assert_eq!(res, raw);
38//! let res = base16ct::lower::encode(raw, &mut buf).unwrap();
39//! assert_eq!(res, lower_hex_str.as_bytes());
40//! // you also can use `encode_str` and `encode_string` to get
41//! // `&str` and `String` respectively
42//! let res: &str = base16ct::lower::encode_str(raw, &mut buf).unwrap();
43//! assert_eq!(res, lower_hex_str);
44//!
45//! let res = base16ct::upper::decode(upper_hex_str, &mut buf).unwrap();
46//! assert_eq!(res, raw);
47//! let res = base16ct::upper::encode(raw, &mut buf).unwrap();
48//! assert_eq!(res, upper_hex_str.as_bytes());
49//!
50//! // In cases when you don't know if input contains upper or lower
51//! // hex-encoded value, then use functions from the `mixed` module
52//! let res = base16ct::mixed::decode(lower_hex_str, &mut buf).unwrap();
53//! assert_eq!(res, raw);
54//! let res = base16ct::mixed::decode(upper_hex_str, &mut buf).unwrap();
55//! assert_eq!(res, raw);
56//! let res = base16ct::mixed::decode(mixed_hex_str, &mut buf).unwrap();
57//! assert_eq!(res, raw);
58//! ```
59//!
60//! [RFC 4648]: https://tools.ietf.org/html/rfc4648
61
62#[cfg(feature = "alloc")]
63#[macro_use]
64extern crate alloc;
65#[cfg(feature = "std")]
66extern crate std;
67
68/// Function for decoding and encoding lower Base16 (hex)
69pub mod lower;
70/// Function for decoding mixed Base16 (hex)
71pub mod mixed;
72/// Function for decoding and encoding upper Base16 (hex)
73pub mod upper;
74
75/// Display formatter for hex.
76mod display;
77/// Error types.
78mod error;
79
80pub use crate::{
81    display::HexDisplay,
82    error::{Error, Result},
83};
84
85#[cfg(feature = "alloc")]
86use alloc::{string::String, vec::Vec};
87
88/// Compute decoded length of the given hex-encoded input.
89#[inline(always)]
90pub fn decoded_len(bytes: &[u8]) -> Result<usize> {
91    if bytes.len() & 1 == 0 {
92        Ok(bytes.len() / 2)
93    } else {
94        Err(Error::InvalidLength)
95    }
96}
97
98/// Get the length of Base16 (hex) produced by encoding the given bytes.
99#[inline(always)]
100pub fn encoded_len(bytes: &[u8]) -> usize {
101    bytes.len() * 2
102}
103
104fn decode_inner<'a>(
105    src: &[u8],
106    dst: &'a mut [u8],
107    decode_nibble: impl Fn(u8) -> u16,
108) -> Result<&'a [u8]> {
109    let dst = dst
110        .get_mut(..decoded_len(src)?)
111        .ok_or(Error::InvalidLength)?;
112
113    let mut err: u16 = 0;
114    for (src, dst) in src.chunks_exact(2).zip(dst.iter_mut()) {
115        let byte = (decode_nibble(src[0]) << 4) | decode_nibble(src[1]);
116        err |= byte >> 8;
117        *dst = byte as u8;
118    }
119
120    match err {
121        0 => Ok(dst),
122        _ => Err(Error::InvalidEncoding),
123    }
124}