hex_conservative/lib.rs
1// SPDX-License-Identifier: CC0-1.0
2
3//! Hex encoding and decoding.
4//!
5//! General purpose hex encoding/decoding library with a conservative MSRV and dependency policy.
6//!
7//! ## Basic Usage
8//! ```
9//! # #[cfg(feature = "alloc")] {
10//! // In your manifest use the `package` key to improve import ergonomics.
11//! // hex = { package = "hex-conservative", version = "*" }
12//! # use hex_conservative as hex; // No need for this if using `package` as above.
13//! use hex::prelude::*;
14//!
15//! // Decode an arbitrary length hex string into a vector.
16//! let v = Vec::from_hex("deadbeef").expect("valid hex digits");
17//! // Or a known length hex string into a fixed size array.
18//! let a = <[u8; 4]>::from_hex("deadbeef").expect("valid length and valid hex digits");
19//!
20//! // We support `LowerHex` and `UpperHex` out of the box for `[u8]` slices.
21//! println!("An array as lower hex: {:x}", a.as_hex());
22//! // And for vecs since `Vec` derefs to byte slice.
23//! println!("A vector as upper hex: {:X}", v.as_hex());
24//!
25//! // Allocate a new string (also `to_upper_hex_string`).
26//! let s = v.to_lower_hex_string();
27//!
28//! // Please note, mixed case strings will still parse successfully but we only
29//! // support displaying hex in a single case.
30//! assert_eq!(
31//! Vec::from_hex("dEaDbEeF").expect("valid mixed case hex digits"),
32//! Vec::from_hex("deadbeef").expect("valid hex digits"),
33//! );
34//! # }
35//! ```
36
37#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
38// Experimental features we need.
39#![cfg_attr(docsrs, feature(doc_cfg))]
40// Coding conventions
41#![warn(missing_docs)]
42
43#[cfg(feature = "alloc")]
44extern crate alloc;
45
46#[doc(hidden)]
47pub mod _export {
48 /// A re-export of core::*
49 pub mod _core {
50 pub use core::*;
51 }
52}
53
54pub mod buf_encoder;
55pub mod display;
56pub mod error;
57mod iter;
58pub mod parse;
59#[cfg(feature = "serde")]
60pub mod serde;
61
62/// Re-exports of the common crate traits.
63pub mod prelude {
64 #[doc(inline)]
65 pub use crate::{display::DisplayHex, parse::FromHex};
66}
67
68pub(crate) use table::Table;
69
70#[rustfmt::skip] // Keep public re-exports separate.
71#[doc(inline)]
72pub use self::{
73 display::DisplayHex,
74 error::{OddLengthStringError, HexToBytesError, HexToArrayError, InvalidCharError},
75 iter::{BytesToHexIter, HexToBytesIter, HexSliceToBytesIter},
76 parse::FromHex,
77};
78
79/// Possible case of hex.
80#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
81pub enum Case {
82 /// Produce lower-case chars (`[0-9a-f]`).
83 ///
84 /// This is the default.
85 Lower,
86
87 /// Produce upper-case chars (`[0-9A-F]`).
88 Upper,
89}
90
91impl Default for Case {
92 #[inline]
93 fn default() -> Self { Case::Lower }
94}
95
96impl Case {
97 /// Returns the encoding table.
98 ///
99 /// The returned table may only contain displayable ASCII chars.
100 #[inline]
101 #[rustfmt::skip]
102 pub(crate) fn table(self) -> &'static Table {
103 match self {
104 Case::Lower => &Table::LOWER,
105 Case::Upper => &Table::UPPER,
106 }
107 }
108}
109
110/// Correctness boundary for `Table`.
111mod table {
112 /// Table of hex chars.
113 //
114 // Correctness invariant: each byte in the table must be ASCII.
115 pub(crate) struct Table([u8; 16]);
116
117 impl Table {
118 pub(crate) const LOWER: Self = Table([
119 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd',
120 b'e', b'f',
121 ]);
122 pub(crate) const UPPER: Self = Table([
123 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'A', b'B', b'C', b'D',
124 b'E', b'F',
125 ]);
126
127 /// Encodes single byte as two ASCII chars using the given table.
128 ///
129 /// The function guarantees only returning values from the provided table.
130 #[inline]
131 pub(crate) fn byte_to_chars(&self, byte: u8) -> [char; 2] {
132 let left = self.0[usize::from(byte >> 4)];
133 let right = self.0[usize::from(byte & 0x0F)];
134 [char::from(left), char::from(right)]
135 }
136
137 /// Writes the single byte as two ASCII chars in the provided buffer, and returns a `&str`
138 /// to that buffer.
139 ///
140 /// The function guarantees only returning values from the provided table.
141 #[inline]
142 pub(crate) fn byte_to_str<'a>(&self, dest: &'a mut [u8; 2], byte: u8) -> &'a str {
143 dest[0] = self.0[usize::from(byte >> 4)];
144 dest[1] = self.0[usize::from(byte & 0x0F)];
145 // SAFETY: Table inner array contains only valid ascii
146 let hex_str = unsafe { core::str::from_utf8_unchecked(dest) };
147 hex_str
148 }
149 }
150}
151
152/// Quick and dirty macro for parsing hex in tests.
153///
154/// For improved ergonomics import with: `use hex_conservative::test_hex_unwrap as hex;`
155#[macro_export]
156macro_rules! test_hex_unwrap (($hex:expr) => (<Vec<u8> as $crate::FromHex>::from_hex($hex).unwrap()));
157
158#[cfg(test)]
159mod tests {
160 use crate::test_hex_unwrap as hex;
161
162 #[test]
163 fn parse_hex_into_vector() {
164 let got = hex!("deadbeef");
165 let want = vec![0xde, 0xad, 0xbe, 0xef];
166 assert_eq!(got, want)
167 }
168}