lowercase_hex/
traits.rs

1//! Modified from `hex`.
2
3#![allow(clippy::ptr_as_ptr, clippy::borrow_as_ptr, clippy::missing_errors_doc)]
4
5use core::iter;
6
7#[cfg(feature = "alloc")]
8#[allow(unused_imports)]
9use alloc::{
10    borrow::{Cow, ToOwned},
11    boxed::Box,
12    rc::Rc,
13    string::String,
14    vec::Vec,
15};
16
17#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
18#[allow(unused_imports)]
19use alloc::sync::Arc;
20
21/// Encoding values as hex string.
22///
23/// This trait is implemented for all `T` which implement `AsRef<[u8]>`. This
24/// includes `String`, `str`, `Vec<u8>` and `[u8]`.
25///
26/// # Examples
27///
28/// ```
29/// #![allow(deprecated)]
30/// use lowercase_hex::ToHex;
31///
32/// assert_eq!("Hello world!".encode_hex::<String>(), "48656c6c6f20776f726c6421");
33/// ```
34#[cfg_attr(feature = "alloc", doc = "\n[`encode`]: crate::encode")]
35#[cfg_attr(not(feature = "alloc"), doc = "\n[`encode`]: crate::encode_to_slice")]
36#[deprecated(note = "use `ToHexExt` instead")]
37pub trait ToHex {
38    /// Encode the hex strict representing `self` into the result.
39    /// Lower case letters are used (e.g. `f9b4ca`).
40    fn encode_hex<T: iter::FromIterator<char>>(&self) -> T;
41}
42
43/// Encoding values as hex string.
44///
45/// This trait is implemented for all `T` which implement `AsRef<[u8]>`. This
46/// includes `String`, `str`, `Vec<u8>` and `[u8]`.
47///
48/// # Examples
49///
50/// ```
51/// use lowercase_hex::ToHexExt;
52///
53/// assert_eq!("Hello world!".encode_hex(), "48656c6c6f20776f726c6421");
54/// ```
55#[cfg(feature = "alloc")]
56pub trait ToHexExt {
57    /// Encode the hex strict representing `self` into the result.
58    /// Lower case letters are used (e.g. `f9b4ca`).
59    fn encode_hex(&self) -> String;
60}
61
62struct BytesToHexChars<'a> {
63    inner: core::slice::Iter<'a, u8>,
64    next: Option<char>,
65}
66
67impl<'a> BytesToHexChars<'a> {
68    fn new(inner: &'a [u8]) -> Self {
69        BytesToHexChars {
70            inner: inner.iter(),
71            next: None,
72        }
73    }
74}
75
76impl Iterator for BytesToHexChars<'_> {
77    type Item = char;
78
79    fn next(&mut self) -> Option<Self::Item> {
80        match self.next.take() {
81            Some(current) => Some(current),
82            None => self.inner.next().map(|byte| {
83                let (high, low) = crate::byte2hex(*byte);
84                self.next = Some(low as char);
85                high as char
86            }),
87        }
88    }
89}
90
91#[inline]
92fn encode_to_iter<T: iter::FromIterator<char>>(source: &[u8]) -> T {
93    BytesToHexChars::new(source).collect()
94}
95
96#[allow(deprecated)]
97impl<T: AsRef<[u8]>> ToHex for T {
98    #[inline]
99    fn encode_hex<U: iter::FromIterator<char>>(&self) -> U {
100        encode_to_iter(self.as_ref())
101    }
102}
103
104#[cfg(feature = "alloc")]
105impl<T: AsRef<[u8]>> ToHexExt for T {
106    #[inline]
107    fn encode_hex(&self) -> String {
108        crate::encode(self)
109    }
110}
111
112/// Types that can be decoded from a hex string.
113///
114/// This trait is implemented for `Vec<u8>` and small `u8`-arrays.
115///
116/// # Example
117///
118/// ```
119/// use lowercase_hex::FromHex;
120///
121/// let buffer = <[u8; 12]>::from_hex("48656c6c6f20776f726c6421")?;
122/// assert_eq!(buffer, *b"Hello world!");
123/// # Ok::<(), lowercase_hex::FromHexError>(())
124/// ```
125pub trait FromHex: Sized {
126    /// The associated error which can be returned from parsing.
127    type Error;
128
129    /// Creates an instance of type `Self` from the given hex string, or fails
130    /// with a custom error type.
131    ///
132    /// Both, upper and lower case characters are valid and can even be
133    /// mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings).
134    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error>;
135}
136
137#[cfg(feature = "alloc")]
138impl<T: FromHex> FromHex for Box<T> {
139    type Error = T::Error;
140
141    #[inline]
142    fn from_hex<U: AsRef<[u8]>>(hex: U) -> Result<Self, Self::Error> {
143        FromHex::from_hex(hex.as_ref()).map(Self::new)
144    }
145}
146
147#[cfg(feature = "alloc")]
148impl<T> FromHex for Cow<'_, T>
149where
150    T: ToOwned + ?Sized,
151    T::Owned: FromHex,
152{
153    type Error = <T::Owned as FromHex>::Error;
154
155    #[inline]
156    fn from_hex<U: AsRef<[u8]>>(hex: U) -> Result<Self, Self::Error> {
157        FromHex::from_hex(hex.as_ref()).map(Cow::Owned)
158    }
159}
160
161#[cfg(feature = "alloc")]
162impl<T: FromHex> FromHex for Rc<T> {
163    type Error = T::Error;
164
165    #[inline]
166    fn from_hex<U: AsRef<[u8]>>(hex: U) -> Result<Self, Self::Error> {
167        FromHex::from_hex(hex.as_ref()).map(Self::new)
168    }
169}
170
171#[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
172impl<T: FromHex> FromHex for Arc<T> {
173    type Error = T::Error;
174
175    #[inline]
176    fn from_hex<U: AsRef<[u8]>>(hex: U) -> Result<Self, Self::Error> {
177        FromHex::from_hex(hex.as_ref()).map(Self::new)
178    }
179}
180
181#[cfg(feature = "alloc")]
182impl FromHex for Vec<u8> {
183    type Error = crate::FromHexError;
184
185    #[inline]
186    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
187        crate::decode(hex.as_ref())
188    }
189}
190
191#[cfg(feature = "alloc")]
192impl FromHex for Vec<i8> {
193    type Error = crate::FromHexError;
194
195    #[inline]
196    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
197        // SAFETY: transmuting `u8` to `i8` is safe.
198        crate::decode(hex.as_ref()).map(|vec| unsafe { core::mem::transmute::<Vec<u8>, Self>(vec) })
199    }
200}
201
202#[cfg(feature = "alloc")]
203impl FromHex for Box<[u8]> {
204    type Error = crate::FromHexError;
205
206    #[inline]
207    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
208        <Vec<u8>>::from_hex(hex).map(Vec::into_boxed_slice)
209    }
210}
211
212#[cfg(feature = "alloc")]
213impl FromHex for Box<[i8]> {
214    type Error = crate::FromHexError;
215
216    #[inline]
217    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
218        <Vec<i8>>::from_hex(hex).map(Vec::into_boxed_slice)
219    }
220}
221
222impl<const N: usize> FromHex for [u8; N] {
223    type Error = crate::FromHexError;
224
225    #[inline]
226    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
227        crate::decode_to_array(hex.as_ref())
228    }
229}
230
231impl<const N: usize> FromHex for [i8; N] {
232    type Error = crate::FromHexError;
233
234    #[inline]
235    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
236        // SAFETY: casting `[u8]` to `[i8]` is safe.
237        crate::decode_to_array(hex.as_ref())
238            .map(|buf| unsafe { *(&buf as *const [u8; N] as *const [i8; N]) })
239    }
240}