crypto_service_sdk/
encoding.rs1use std::fmt;
9use std::ops::Deref;
10
11use base64::engine::general_purpose::STANDARD;
12use base64::Engine as _;
13use serde::de::{self, Visitor};
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16#[derive(Clone, Default, PartialEq, Eq, Hash)]
20pub struct Hex(Vec<u8>);
21
22#[derive(Clone, Default, PartialEq, Eq, Hash)]
26pub struct Base64(Vec<u8>);
27
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
30#[error("not valid {0}")]
31pub struct EncodingError(&'static str);
32
33macro_rules! byte_string {
34 ($name:ident) => {
35 impl $name {
36 pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
38 Self(bytes.into())
39 }
40
41 #[must_use]
43 pub fn as_bytes(&self) -> &[u8] {
44 &self.0
45 }
46
47 #[must_use]
49 pub fn into_vec(self) -> Vec<u8> {
50 self.0
51 }
52 }
53
54 impl Deref for $name {
55 type Target = [u8];
56
57 fn deref(&self) -> &[u8] {
58 &self.0
59 }
60 }
61
62 impl AsRef<[u8]> for $name {
63 fn as_ref(&self) -> &[u8] {
64 &self.0
65 }
66 }
67
68 impl From<Vec<u8>> for $name {
69 fn from(bytes: Vec<u8>) -> Self {
70 Self(bytes)
71 }
72 }
73
74 impl From<&[u8]> for $name {
75 fn from(bytes: &[u8]) -> Self {
76 Self(bytes.to_vec())
77 }
78 }
79
80 impl<const N: usize> From<[u8; N]> for $name {
81 fn from(bytes: [u8; N]) -> Self {
82 Self(bytes.to_vec())
83 }
84 }
85
86 impl Serialize for $name {
87 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
88 serializer.serialize_str(&self.to_string())
89 }
90 }
91
92 impl<'de> Deserialize<'de> for $name {
93 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
94 deserializer.deserialize_str(Text(Self::parse))
95 }
96 }
97 };
98}
99
100byte_string!(Hex);
101byte_string!(Base64);
102
103impl Hex {
104 pub fn parse(text: &str) -> Result<Self, EncodingError> {
110 decode_hex(text).map(Self)
111 }
112}
113
114impl Base64 {
115 pub fn parse(text: &str) -> Result<Self, EncodingError> {
121 STANDARD
122 .decode(text)
123 .map(Self)
124 .map_err(|_| EncodingError("base64"))
125 }
126}
127
128impl fmt::Display for Hex {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.write_str(&encode_hex(&self.0))
131 }
132}
133
134impl fmt::Debug for Hex {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 write!(f, "Hex({self})")
137 }
138}
139
140impl fmt::Display for Base64 {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.write_str(&STANDARD.encode(&self.0))
143 }
144}
145
146impl fmt::Debug for Base64 {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 write!(f, "Base64(<{} bytes>)", self.0.len())
150 }
151}
152
153pub(crate) fn encode_hex(bytes: &[u8]) -> String {
155 const DIGITS: &[u8; 16] = b"0123456789abcdef";
156 let mut out = String::with_capacity(bytes.len() * 2);
157 for byte in bytes {
158 out.push(char::from(DIGITS[usize::from(byte >> 4)]));
159 out.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
160 }
161 out
162}
163
164pub(crate) fn decode_hex(text: &str) -> Result<Vec<u8>, EncodingError> {
166 let digits = text.as_bytes();
167 if digits.len() % 2 != 0 {
168 return Err(EncodingError("hex"));
169 }
170 digits
171 .chunks_exact(2)
172 .map(|pair| Ok(nibble(pair[0])? << 4 | nibble(pair[1])?))
173 .collect()
174}
175
176fn nibble(digit: u8) -> Result<u8, EncodingError> {
177 match digit {
178 b'0'..=b'9' => Ok(digit - b'0'),
179 b'a'..=b'f' => Ok(digit - b'a' + 10),
180 b'A'..=b'F' => Ok(digit - b'A' + 10),
181 _ => Err(EncodingError("hex")),
182 }
183}
184
185pub(crate) struct Text<F>(pub(crate) F);
187
188impl<T, F> Visitor<'_> for Text<F>
189where
190 F: FnOnce(&str) -> Result<T, EncodingError>,
191{
192 type Value = T;
193
194 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.write_str("an encoded byte string")
196 }
197
198 fn visit_str<E: de::Error>(self, text: &str) -> Result<T, E> {
199 (self.0)(text).map_err(E::custom)
200 }
201}
202
203#[cfg(test)]
204mod tests;