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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use crate::errors::DecodeError;
/// Marks a type which can be serialized to and from a binary encoding of either
/// fixed or variable length.
pub trait BinaryEncoding: Sized {
/// The binary type which is returned by serialization. Should either
/// be `[u8; N]` or `Vec<u8>`.
type Serialized;
/// Serialize this data structure to its binary representation.
fn to_bytes(&self) -> Self::Serialized;
/// Deserialize this data structure from a binary representation.
fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError<Self>>;
}
/// Implements various binary encoding traits for both fixed or
/// variable-length encoded data structures.
///
/// Use this macro by first implementing [`BinaryEncoding`] on a type,
/// and then invoking `impl_encoding_traits` on the type.
macro_rules! impl_encoding_traits {
// Fixed length encoding
($typename:ty, $byte_len:expr) => {
/// assert that $typename implements `BinaryEncoding`
const _: () = {
fn __(x: $typename) -> impl BinaryEncoding<Serialized = [u8; $byte_len]> {
x
}
};
impl std::fmt::LowerHex for $typename {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut buffer = [0; $byte_len * 2];
let encoded = base16ct::lower::encode_str(&self.to_bytes(), &mut buffer).unwrap();
f.write_str(encoded)
}
}
impl std::fmt::UpperHex for $typename {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut buffer = [0; $byte_len * 2];
let encoded = base16ct::upper::encode_str(&self.to_bytes(), &mut buffer).unwrap();
f.write_str(encoded)
}
}
impl std::str::FromStr for $typename {
type Err = DecodeError<Self>;
/// Parses this type from a hex string, which can be either upper or
/// lower case. The binary format of the decoded hex data should
/// match that returned by [`to_bytes`][Self::to_bytes].
///
/// Same as [`Self::from_hex`].
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let mut buffer = [0; $byte_len];
let bytes = base16ct::mixed::decode(hex, &mut buffer)?;
Self::from_bytes(bytes)
}
}
impl TryFrom<&[u8]> for $typename {
type Error = DecodeError<Self>;
/// Parse this type from a variable-length byte slice.
///
/// Same as [`Self::from_bytes`][Self::from_bytes].
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
Self::from_bytes(bytes)
}
}
impl TryFrom<[u8; $byte_len]> for $typename {
type Error = DecodeError<Self>;
/// Parse this type from its fixed-length binary representation.
fn try_from(bytes: [u8; $byte_len]) -> Result<Self, Self::Error> {
Self::from_bytes(&bytes)
}
}
impl TryFrom<&[u8; $byte_len]> for $typename {
type Error = DecodeError<Self>;
/// Parse this type from its fixed-length binary representation.
///
/// Same as [`Self::from_bytes`][Self::from_bytes].
fn try_from(bytes: &[u8; $byte_len]) -> Result<Self, Self::Error> {
Self::from_bytes(bytes)
}
}
impl From<$typename> for [u8; $byte_len] {
/// Serialize this type to a fixed-length byte array.
fn from(value: $typename) -> Self {
value.to_bytes()
}
}
impl From<$typename> for Vec<u8> {
/// Serialize this type to a heap-allocated byte vector.
fn from(value: $typename) -> Self {
Vec::from(value.to_bytes())
}
}
impl $typename {
/// Alias to [the `BinaryEncoding` trait implementation of `to_bytes`][Self::to_bytes].
pub fn serialize(&self) -> [u8; $byte_len] {
<Self as BinaryEncoding>::to_bytes(self)
}
/// Alias to [the `BinaryEncoding` trait implementation of `from_bytes`][Self::from_bytes].
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError<Self>> {
<Self as BinaryEncoding>::from_bytes(bytes)
}
/// Parses this type from a hex string, which can be either upper or
/// lower case. The binary format of the decoded hex data should
/// match that returned by [`to_bytes`][Self::to_bytes].
///
/// Same as [`Self::from_str`](#method.from_str).
pub fn from_hex(hex: &str) -> Result<Self, DecodeError<Self>> {
hex.parse()
}
}
#[cfg(any(test, feature = "serde"))]
impl serde::Serialize for $typename {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let bytes = self.to_bytes();
serdect::array::serialize_hex_lower_or_bin(&bytes, serializer)
}
}
#[cfg(any(test, feature = "serde"))]
impl<'de> serde::Deserialize<'de> for $typename {
/// Deserializes this type from a byte array or a hex
/// string, depending on the human-readability of the data format.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[allow(unused_mut, unused_variables)]
let mut buffer = [0u8; $byte_len];
let bytes = serdect::slice::deserialize_hex_or_bin(&mut buffer, deserializer)?;
<$typename>::from_bytes(bytes).map_err(|_| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Bytes(&bytes),
&concat!("a byte array representing ", stringify!($typename)),
)
})
}
}
};
// Variable-length encoding
($typename:ty) => {
/// assert that $typename implements `BinaryEncoding`
const _: () = {
fn __(x: $typename) -> impl BinaryEncoding<Serialized = Vec<u8>> {
x
}
};
impl std::fmt::LowerHex for $typename {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let bytes = self.to_bytes();
let mut buffer = vec![0; bytes.len() * 2];
let encoded = base16ct::lower::encode_str(&bytes, &mut buffer).unwrap();
f.write_str(encoded)
}
}
impl std::fmt::UpperHex for $typename {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let bytes = self.to_bytes();
let mut buffer = vec![0; bytes.len() * 2];
let encoded = base16ct::upper::encode_str(&bytes, &mut buffer).unwrap();
f.write_str(encoded)
}
}
impl std::str::FromStr for $typename {
type Err = DecodeError<Self>;
/// Parses this type from a hex string, which can be either upper or
/// lower case. The binary format of the decoded hex data should
/// match that returned by [`to_bytes`][Self::to_bytes].
///
/// Same as [`Self::from_hex`].
fn from_str(hex: &str) -> Result<Self, Self::Err> {
let bytes = base16ct::mixed::decode_vec(hex)?;
Self::from_bytes(&bytes)
}
}
impl TryFrom<&[u8]> for $typename {
type Error = DecodeError<Self>;
/// Parse this type from a variable-length byte slice.
///
/// Same as [`Self::from_bytes`][Self::from_bytes].
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
Self::from_bytes(bytes)
}
}
impl From<$typename> for Vec<u8> {
/// Serialize this type to a heap-allocated byte vector.
fn from(value: $typename) -> Self {
value.to_bytes()
}
}
impl $typename {
/// Alias to [the `BinaryEncoding` trait implementation of `to_bytes`][Self::to_bytes].
pub fn serialize(&self) -> Vec<u8> {
<Self as BinaryEncoding>::to_bytes(self)
}
/// Alias to [the `BinaryEncoding` trait implementation of `from_bytes`][Self::from_bytes].
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError<Self>> {
<Self as BinaryEncoding>::from_bytes(bytes)
}
/// Parses this type from a hex string, which can be either upper or
/// lower case. The binary format of the decoded hex data should
/// match that returned by [`to_bytes`][Self::to_bytes].
///
/// Same as [`Self::from_str`](#method.from_str).
pub fn from_hex(hex: &str) -> Result<Self, DecodeError<Self>> {
hex.parse()
}
}
#[cfg(any(test, feature = "serde"))]
impl serde::Serialize for $typename {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let bytes = self.to_bytes();
serdect::slice::serialize_hex_lower_or_bin(&bytes, serializer)
}
}
#[cfg(any(test, feature = "serde"))]
impl<'de> serde::Deserialize<'de> for $typename {
/// Deserializes this type from a byte vector or a hex
/// string, depending on the human-readability of the data format.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
<$typename>::from_bytes(&bytes).map_err(|_| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Bytes(&bytes),
&concat!("a byte vector representing ", stringify!($typename)),
)
})
}
}
};
}
/// Implements the Display trait for a type by formatting it as a lower-case
/// hex string.
macro_rules! impl_hex_display {
($typename:ident) => {
impl std::fmt::Display for $typename {
/// Formats this type as a lower-case hex string.
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:x}", self)
}
}
};
}