1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! Modified from `hex`.

#![allow(clippy::ptr_as_ptr, clippy::borrow_as_ptr, clippy::missing_errors_doc)]

use core::iter;

#[cfg(feature = "alloc")]
use alloc::{
    borrow::{Cow, ToOwned},
    boxed::Box,
    rc::Rc,
    sync::Arc,
    vec::Vec,
};

/// Encoding values as hex string.
///
/// This trait is implemented for all `T` which implement `AsRef<[u8]>`. This
/// includes `String`, `str`, `Vec<u8>` and `[u8]`.
///
/// *Note*: instead of using this trait, you might want to use [`encode`].
///
/// # Examples
///
/// ```
/// #![allow(deprecated)]
/// use const_hex::ToHex;
///
/// assert_eq!("Hello world!".encode_hex::<String>(), "48656c6c6f20776f726c6421");
/// ```
#[cfg_attr(feature = "alloc", doc = "\n[`encode`]: crate::encode")]
#[cfg_attr(not(feature = "alloc"), doc = "\n[`encode`]: crate::encode_to_slice")]
#[deprecated(note = "use `encode` or other specialized functions instead")]
pub trait ToHex {
    /// Encode the hex strict representing `self` into the result. Lower case
    /// letters are used (e.g. `f9b4ca`)
    fn encode_hex<T: iter::FromIterator<char>>(&self) -> T;

    /// Encode the hex strict representing `self` into the result. Upper case
    /// letters are used (e.g. `F9B4CA`)
    fn encode_hex_upper<T: iter::FromIterator<char>>(&self) -> T;
}

struct BytesToHexChars<'a, const UPPER: bool> {
    inner: core::slice::Iter<'a, u8>,
    next: Option<char>,
}

impl<'a, const UPPER: bool> BytesToHexChars<'a, UPPER> {
    fn new(inner: &'a [u8]) -> Self {
        BytesToHexChars {
            inner: inner.iter(),
            next: None,
        }
    }
}

impl<const UPPER: bool> Iterator for BytesToHexChars<'_, UPPER> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        match self.next.take() {
            Some(current) => Some(current),
            None => self.inner.next().map(|byte| {
                let (high, low) = crate::byte2hex::<UPPER>(*byte);
                self.next = Some(low as char);
                high as char
            }),
        }
    }
}

#[inline]
fn encode_to_iter<T: iter::FromIterator<char>, const UPPER: bool>(source: &[u8]) -> T {
    BytesToHexChars::<UPPER>::new(source).collect()
}

#[allow(deprecated)]
impl<T: AsRef<[u8]>> ToHex for T {
    #[inline]
    fn encode_hex<U: iter::FromIterator<char>>(&self) -> U {
        encode_to_iter::<_, false>(self.as_ref())
    }

    #[inline]
    fn encode_hex_upper<U: iter::FromIterator<char>>(&self) -> U {
        encode_to_iter::<_, true>(self.as_ref())
    }
}

/// Types that can be decoded from a hex string.
///
/// This trait is implemented for `Vec<u8>` and small `u8`-arrays.
///
/// # Example
///
/// ```
/// use const_hex::FromHex;
///
/// let buffer = <[u8; 12]>::from_hex("48656c6c6f20776f726c6421")?;
/// assert_eq!(buffer, *b"Hello world!");
/// # Ok::<(), const_hex::FromHexError>(())
/// ```
pub trait FromHex: Sized {
    /// The associated error which can be returned from parsing.
    type Error;

    /// Creates an instance of type `Self` from the given hex string, or fails
    /// with a custom error type.
    ///
    /// Both, upper and lower case characters are valid and can even be
    /// mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings).
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error>;
}

#[cfg(feature = "alloc")]
impl<U: FromHex> FromHex for Box<U> {
    type Error = U::Error;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        Ok(Box::new(FromHex::from_hex(hex.as_ref())?))
    }
}

#[cfg(feature = "alloc")]
impl<U> FromHex for Cow<'_, U>
where
    U: Clone + ToOwned,
    U::Owned: FromHex,
{
    type Error = <U::Owned as FromHex>::Error;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        Ok(Cow::Owned(FromHex::from_hex(hex.as_ref())?))
    }
}

#[cfg(feature = "alloc")]
impl<U: FromHex> FromHex for Rc<U> {
    type Error = U::Error;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        Ok(Rc::new(FromHex::from_hex(hex.as_ref())?))
    }
}

#[cfg(feature = "alloc")]
impl<U: FromHex> FromHex for Arc<U> {
    type Error = U::Error;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        Ok(Arc::new(FromHex::from_hex(hex.as_ref())?))
    }
}

#[cfg(feature = "alloc")]
impl FromHex for Vec<u8> {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        crate::decode(hex.as_ref())
    }
}

#[cfg(feature = "alloc")]
impl FromHex for Vec<i8> {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        let vec = crate::decode(hex.as_ref())?;
        // SAFETY: transmuting `u8` to `i8` is safe.
        Ok(unsafe { core::mem::transmute::<Vec<u8>, Vec<i8>>(vec) })
    }
}

#[cfg(feature = "alloc")]
impl FromHex for Box<[u8]> {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        <Vec<u8>>::from_hex(hex).map(Vec::into_boxed_slice)
    }
}

#[cfg(feature = "alloc")]
impl FromHex for Box<[i8]> {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        <Vec<i8>>::from_hex(hex).map(Vec::into_boxed_slice)
    }
}

impl<const N: usize> FromHex for [u8; N] {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        let mut buf = [0u8; N];
        crate::decode_to_slice(hex.as_ref(), &mut buf)?;
        Ok(buf)
    }
}

impl<const N: usize> FromHex for [i8; N] {
    type Error = crate::FromHexError;

    #[inline]
    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
        let mut buf = [0u8; N];
        crate::decode_to_slice(hex.as_ref(), &mut buf)?;
        // SAFETY: casting `[u8]` to `[i8]` is safe.
        Ok(unsafe { *(&buf as *const [u8; N] as *const [i8; N]) })
    }
}