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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use serde::{
de::{Error as DeError, Unexpected, Visitor},
Deserializer, Serializer,
};
use alloc::{borrow::Cow, vec::Vec};
use core::{convert::TryFrom, fmt, marker::PhantomData};
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub trait Hex<T> {
type Error: fmt::Display;
fn create_bytes(value: &T) -> Cow<'_, [u8]>;
fn from_bytes(bytes: &[u8]) -> Result<T, Self::Error>;
fn serialize<S: Serializer>(value: &T, serializer: S) -> Result<S::Ok, S::Error> {
let value = Self::create_bytes(value);
if serializer.is_human_readable() {
serializer.serialize_str(&hex::encode(value))
} else {
serializer.serialize_bytes(value.as_ref())
}
}
fn deserialize<'de, D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
{
struct HexVisitor;
impl<'de> Visitor<'de> for HexVisitor {
type Value = Vec<u8>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("hex-encoded byte array")
}
fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
hex::decode(value).map_err(|_| E::invalid_type(Unexpected::Str(value), &self))
}
fn visit_bytes<E: DeError>(self, value: &[u8]) -> Result<Self::Value, E> {
Ok(value.to_vec())
}
}
struct BytesVisitor;
impl<'de> Visitor<'de> for BytesVisitor {
type Value = Vec<u8>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("byte array")
}
fn visit_bytes<E: DeError>(self, value: &[u8]) -> Result<Self::Value, E> {
Ok(value.to_vec())
}
fn visit_byte_buf<E: DeError>(self, value: Vec<u8>) -> Result<Self::Value, E> {
Ok(value)
}
}
let maybe_bytes = if deserializer.is_human_readable() {
deserializer.deserialize_str(HexVisitor)
} else {
deserializer.deserialize_byte_buf(BytesVisitor)
};
maybe_bytes.and_then(|bytes| Self::from_bytes(&bytes).map_err(D::Error::custom))
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[derive(Debug)]
pub struct HexForm<T>(PhantomData<T>);
impl<T, E> Hex<T> for HexForm<T>
where
T: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = E>,
E: fmt::Display,
{
type Error = E;
fn create_bytes(buffer: &T) -> Cow<'_, [u8]> {
Cow::Borrowed(buffer.as_ref())
}
fn from_bytes(bytes: &[u8]) -> Result<T, Self::Error> {
T::try_from(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_derive::{Deserialize, Serialize};
use serde_json::json;
use alloc::{
borrow::ToOwned,
string::{String, ToString},
vec,
};
use core::array::TryFromSliceError;
#[derive(Debug, Serialize, Deserialize)]
struct Buffer([u8; 8]);
impl AsRef<[u8]> for Buffer {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl TryFrom<&[u8]> for Buffer {
type Error = TryFromSliceError;
fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
<[u8; 8]>::try_from(slice).map(Buffer)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct Test {
#[serde(with = "HexForm::<Buffer>")]
buffer: Buffer,
other_field: String,
}
#[test]
fn internal_type() {
let json = json!({ "buffer": "0001020304050607", "other_field": "abc" });
let value: Test = serde_json::from_value(json.clone()).unwrap();
assert!(value
.buffer
.0
.iter()
.enumerate()
.all(|(i, &byte)| i == usize::from(byte)));
let json_copy = serde_json::to_value(&value).unwrap();
assert_eq!(json, json_copy);
}
#[test]
fn error_reporting() {
let bogus_jsons = vec![
serde_json::json!({
"buffer": "bogus",
"other_field": "test",
}),
serde_json::json!({
"buffer": "c0ffe",
"other_field": "test",
}),
];
for bogus_json in bogus_jsons {
let err = serde_json::from_value::<Test>(bogus_json)
.unwrap_err()
.to_string();
assert!(err.contains("expected hex-encoded byte array"), "{}", err);
}
}
#[test]
fn internal_type_with_derived_serde_code() {
#[derive(Serialize, Deserialize)]
struct OriginalTest {
buffer: Buffer,
other_field: String,
}
let test = Test {
buffer: Buffer([1; 8]),
other_field: "a".to_owned(),
};
assert_eq!(
serde_json::to_value(test).unwrap(),
json!({
"buffer": "0101010101010101",
"other_field": "a",
})
);
let test = OriginalTest {
buffer: Buffer([1; 8]),
other_field: "a".to_owned(),
};
assert_eq!(
serde_json::to_value(test).unwrap(),
json!({
"buffer": [1, 1, 1, 1, 1, 1, 1, 1],
"other_field": "a",
})
);
}
#[test]
fn external_type() {
#[derive(Debug, PartialEq, Eq)]
pub struct Buffer([u8; 8]);
struct BufferHex(());
impl Hex<Buffer> for BufferHex {
type Error = &'static str;
fn create_bytes(buffer: &Buffer) -> Cow<'_, [u8]> {
Cow::Borrowed(&buffer.0)
}
fn from_bytes(bytes: &[u8]) -> Result<Buffer, Self::Error> {
if bytes.len() == 8 {
let mut inner = [0; 8];
inner.copy_from_slice(bytes);
Ok(Buffer(inner))
} else {
Err("invalid buffer length")
}
}
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Test {
#[serde(with = "BufferHex")]
buffer: Buffer,
other_field: String,
}
let json = json!({ "buffer": "0001020304050607", "other_field": "abc" });
let value: Test = serde_json::from_value(json.clone()).unwrap();
assert!(value
.buffer
.0
.iter()
.enumerate()
.all(|(i, &byte)| i == usize::from(byte)));
let json_copy = serde_json::to_value(&value).unwrap();
assert_eq!(json, json_copy);
let buffer = bincode::serialize(&value).unwrap();
let buffer_hex = hex::encode(&buffer);
let needle = "0001020304050607";
assert!(buffer_hex.contains(needle));
let value_copy: Test = bincode::deserialize(&buffer).unwrap();
assert_eq!(value_copy, value);
}
#[test]
fn deserializing_flattened_field() {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Inner {
#[serde(with = "HexForm")]
x: Vec<u8>,
#[serde(with = "HexForm")]
y: [u8; 16],
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Outer {
#[serde(flatten)]
inner: Inner,
z: String,
}
let value = Outer {
inner: Inner {
x: vec![1; 8],
y: [0; 16],
},
z: "test".to_owned(),
};
let bytes = serde_cbor::to_vec(&value).unwrap();
let bytes_hex = hex::encode(&bytes);
assert!(bytes_hex.contains(&"01".repeat(8)));
assert!(bytes_hex.contains(&"00".repeat(16)));
let value_copy = serde_cbor::from_slice(&bytes).unwrap();
assert_eq!(value, value_copy);
}
}