1use alloc::string::String;
2use alloc::vec::Vec;
3use core::fmt::Debug;
4use core::str;
5use faster_hex::Error;
6use serde::{Deserialize, Deserializer, Serializer};
7use smallvec::{SmallVec, smallvec};
8
9pub trait ToHex {
10 fn to_hex(&self) -> String;
11}
12
13pub fn serialize<S, T>(this: T, serializer: S) -> Result<S::Ok, S::Error>
14where
15 S: Serializer,
16 T: ToHex,
17{
18 let hex = this.to_hex();
19 serializer.serialize_str(&hex)
20}
21
22pub trait FromHex: Sized {
23 type Error: core::fmt::Display;
24 fn from_hex(hex_str: &str) -> Result<Self, Self::Error>;
25}
26
27pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
28where
29 D: Deserializer<'de>,
30 T: FromHex,
31{
32 use serde::de::Error;
33 let buff: &[u8] = Deserialize::deserialize(deserializer)?;
34 T::from_hex(str::from_utf8(buff).unwrap()).map_err(D::Error::custom)
35}
36
37impl ToHex for &[u8] {
40 fn to_hex(&self) -> String {
41 if self.is_empty() {
43 return String::new();
44 }
45
46 let mut hex = alloc::vec![0u8; self.len() * 2];
47 faster_hex::hex_encode(self, hex.as_mut_slice()).expect("The output is exactly twice the size of the input");
48 let result = unsafe { str::from_utf8_unchecked(&hex) };
49 String::from(result)
50 }
51}
52
53impl ToHex for Vec<u8> {
56 fn to_hex(&self) -> String {
57 (&**self).to_hex()
58 }
59}
60
61impl FromHex for Vec<u8> {
64 type Error = faster_hex::Error;
65 fn from_hex(hex_str: &str) -> Result<Self, Self::Error> {
66 if hex_str.is_empty() {
68 return Ok(alloc::vec![]);
69 }
70
71 let mut bytes = alloc::vec![0u8; hex_str.len() / 2];
72 faster_hex::hex_decode(hex_str.as_bytes(), bytes.as_mut_slice())?;
73 Ok(bytes)
74 }
75}
76
77#[derive(Debug, thiserror::Error)]
78pub enum FixedArrayError<const N: usize> {
79 #[error("encoding error: {0}")]
80 Deserialize(faster_hex::Error),
81 #[error("unexpected length of hex string. actual: {0}")]
82 WrongLength(usize),
83}
84
85impl<const N: usize> From<faster_hex::Error> for FixedArrayError<N> {
86 fn from(value: Error) -> Self {
87 Self::Deserialize(value)
88 }
89}
90
91impl<const N: usize> FromHex for [u8; N] {
94 type Error = FixedArrayError<N>;
95 fn from_hex(hex_str: &str) -> Result<Self, Self::Error> {
96 let len = hex_str.len();
97 if len != N * 2 {
98 return Err(Self::Error::WrongLength(len));
99 }
100
101 let mut bytes = [0u8; N];
102 faster_hex::hex_decode(hex_str.as_bytes(), bytes.as_mut_slice())?;
103 Ok(bytes)
104 }
105}
106
107impl<A: smallvec::Array<Item = u8>> ToHex for SmallVec<A> {
110 fn to_hex(&self) -> String {
111 (&**self).to_hex()
112 }
113}
114
115impl<A: smallvec::Array<Item = u8>> FromHex for SmallVec<A> {
118 type Error = faster_hex::Error;
119 fn from_hex(hex_str: &str) -> Result<Self, Self::Error> {
120 if hex_str.is_empty() {
122 return Ok(smallvec![]);
123 }
124
125 let mut bytes: SmallVec<A> = smallvec![0u8; hex_str.len() / 2];
126 faster_hex::hex_decode(hex_str.as_bytes(), bytes.as_mut_slice())?;
127 Ok(bytes)
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134 use std::string::ToString;
135 #[test]
136 fn test_vec_hex_convert() {
137 let v: Vec<u8> = alloc::vec![0x0, 0xab, 0x55, 0x30, 0x1f, 0x63];
138 let k = "00ab55301f63";
139 assert_eq!(k.len(), v.len() * 2);
140 assert_eq!(k.to_string(), v.to_hex());
141 assert_eq!(Vec::from_hex(k).unwrap(), v);
142
143 assert!(Vec::from_hex("not a number").is_err());
144 assert!(Vec::from_hex("ab01").is_ok());
145
146 assert!(Vec::from_hex("ab0").is_err());
148 assert_eq!(Vec::from_hex("").unwrap().len(), 0);
150 }
151
152 #[test]
153 fn test_smallvec_hex_convert() {
154 type TestVec = SmallVec<[u8; 35]>;
155
156 let v: TestVec = smallvec![0x0, 0xab, 0x55, 0x30, 0x1f, 0x63];
157 let k = "00ab55301f63";
158 assert_eq!(k.len(), v.len() * 2);
159 assert_eq!(k.to_string(), v.to_hex());
160 assert_eq!(SmallVec::<[u8; 35]>::from_hex(k).unwrap(), v);
161
162 assert!(TestVec::from_hex("not a number").is_err());
163 assert!(TestVec::from_hex("ab01").is_ok());
164
165 assert!(TestVec::from_hex("ab0").is_err());
167 assert_eq!(TestVec::from_hex("").unwrap().len(), 0);
169 }
170}