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
use rustc_hex::{FromHex, ToHex};
use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::fmt;
#[derive(Debug, PartialEq, Eq, Default, Hash, Clone)]
pub struct Bytes(pub Vec<u8>);
impl Bytes {
pub fn new(bytes: Vec<u8>) -> Bytes {
Bytes(bytes)
}
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl From<Vec<u8>> for Bytes {
fn from(bytes: Vec<u8>) -> Bytes {
Bytes(bytes)
}
}
impl Into<Vec<u8>> for Bytes {
fn into(self) -> Vec<u8> {
self.0
}
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut serialized = "0x".to_owned();
serialized.push_str(self.0.to_hex().as_ref());
serializer.serialize_str(serialized.as_ref())
}
}
impl<'a> Deserialize<'a> for Bytes {
fn deserialize<D>(deserializer: D) -> Result<Bytes, D::Error>
where
D: Deserializer<'a>,
{
deserializer.deserialize_any(BytesVisitor)
}
}
struct BytesVisitor;
impl<'a> Visitor<'a> for BytesVisitor {
type Value = Bytes;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a 0x-prefixed, hex-encoded vector of bytes")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: Error,
{
if value.len() >= 2 && value.starts_with("0x") && value.len() & 1 == 0 {
Ok(Bytes::new(FromHex::from_hex(&value[2..]).map_err(|e| {
Error::custom(format!("Invalid hex: {}", e))
})?))
} else {
Err(Error::custom(
"Invalid bytes format. Expected a 0x-prefixed hex string with even length",
))
}
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rustc_hex::FromHex;
use serde_json;
#[test]
fn test_bytes_serialize() {
let bytes = Bytes("0123456789abcdef".from_hex().unwrap());
let serialized = serde_json::to_string(&bytes).unwrap();
assert_eq!(serialized, r#""0x0123456789abcdef""#);
}
#[test]
fn test_bytes_deserialize() {
let bytes0: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""∀∂""#);
let bytes1: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""""#);
let bytes2: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""0x123""#);
let bytes3: Result<Bytes, serde_json::Error> = serde_json::from_str(r#""0xgg""#);
let bytes4: Bytes = serde_json::from_str(r#""0x""#).unwrap();
let bytes5: Bytes = serde_json::from_str(r#""0x12""#).unwrap();
let bytes6: Bytes = serde_json::from_str(r#""0x0123""#).unwrap();
assert!(bytes0.is_err());
assert!(bytes1.is_err());
assert!(bytes2.is_err());
assert!(bytes3.is_err());
assert_eq!(bytes4, Bytes(vec![]));
assert_eq!(bytes5, Bytes(vec![0x12]));
assert_eq!(bytes6, Bytes(vec![0x1, 0x23]));
}
}