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