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
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use crate::error;
pub trait SerializableId: Clone {
fn try_create(id: impl Into<String>) -> Result<Self, error::Error>
where
Self: Sized;
fn as_str(&self) -> &str;
fn id(&self) -> String;
fn key(&self) -> &'static str;
}
pub trait SerializableSocket<T> {
fn try_create(id: Option<String>, ip: &str, port: u16) -> Result<Self, error::Error>
where
Self: Sized;
fn get_id(&self) -> Option<T>;
fn key(&self) -> &'static str;
fn addr(&self) -> &SocketAddr;
fn ip(&self) -> IpAddr;
fn port(&self) -> u16;
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct SocketInfo<T: SerializableId> {
id: Option<T>,
socket: SocketAddr,
}
impl<T: SerializableId> SerializableSocket<T> for SocketInfo<T> {
fn try_create(id: Option<String>, ip: &str, port: u16) -> Result<Self, error::Error> {
let ip: IpAddr = ip.parse()?;
let socket = SocketAddr::new(ip, port);
match id {
Some(id) => Ok(Self {
id: Some(T::try_create(id)?),
socket: socket,
}),
None => Ok(Self {
id: None,
socket: socket,
}),
}
}
fn get_id(&self) -> Option<T> {
self.id.clone()
}
fn key(&self) -> &'static str {
match self.id {
Some(ref id) => id.key(),
None => "",
}
}
fn addr(&self) -> &SocketAddr {
&self.socket
}
fn ip(&self) -> IpAddr {
self.socket.ip()
}
fn port(&self) -> u16 {
self.socket.port()
}
}
impl<T: SerializableId> Serialize for SocketInfo<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let key = self.key();
let id = self.get_id();
let mut serial;
if key.len() == 0 {
serial = serializer.serialize_struct("SocketAddr", 2)?
} else {
serial = serializer.serialize_struct("SocketAddr", 3)?;
serial.serialize_field(key, &(id.expect("no id")).id())?;
};
let ip = self.ip();
if ip.is_ipv4() {
serial.serialize_field("ip_v4", &ip.to_string())?;
} else {
serial.serialize_field("ip_v6", &ip.to_string())?;
}
serial.serialize_field("port", &self.port())?;
serial.end()
}
}
impl<'de, X: SerializableId> Deserialize<'de> for SocketInfo<X> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use std::marker::PhantomData;
enum Field {
IP,
PORT,
ID,
}
impl<'de> Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
where
D: Deserializer<'de>,
{
struct FieldVisitor;
impl<'de> Visitor<'de> for FieldVisitor {
type Value = Field;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("`ip_v4` or `ip_v6` or `port` or `*_id`")
}
fn visit_str<E>(self, value: &str) -> Result<Field, E>
where
E: de::Error,
{
match value {
"ip_v4" => Ok(Field::IP),
"ip_v6" => Ok(Field::IP),
"port" => Ok(Field::PORT),
id if id.ends_with("_id") => Ok(Field::ID),
_ => Err(de::Error::unknown_field(value, FIELDS)),
}
}
}
deserializer.deserialize_identifier(FieldVisitor)
}
}
struct SocketInfoVisitor<T>(PhantomData<T>);
impl<'de, T: SerializableId> Visitor<'de> for SocketInfoVisitor<T> {
type Value = SocketInfo<T>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct SocketAddr")
}
fn visit_map<V>(self, mut map: V) -> Result<SocketInfo<T>, V::Error>
where
V: MapAccess<'de>,
{
let mut ip: Option<String> = None;
let mut id: Option<String> = None;
let mut port: Option<u16> = None;
while let Some(key) = map.next_key()? {
match key {
Field::PORT => {
if port.is_some() {
return Err(de::Error::duplicate_field("port"));
}
port = Some(map.next_value()?);
}
Field::IP => {
if ip.is_some() {
return Err(de::Error::duplicate_field("ip_v4"));
}
ip = Some(map.next_value()?);
}
Field::ID => {
if id.is_some() {
return Err(de::Error::duplicate_field("id"));
}
id = Some(map.next_value()?);
}
}
}
let ip = ip.ok_or_else(|| de::Error::missing_field("ip_v4 or ip_v6"))?;
let port = port.ok_or_else(|| de::Error::missing_field("port"))?;
let socket_info = SocketInfo::<T>::try_create(id, &ip, port);
if let Err(_err) = socket_info {
use serde::de::Error;
return Err(V::Error::custom(format!("fail to deserialize socket")));
}
Ok(socket_info.unwrap())
}
}
const FIELDS: &'static [&'static str] = &["ip_v4", "ip_v6", "port", "*_id"];
deserializer.deserialize_struct("SocketAddr", FIELDS, SocketInfoVisitor(PhantomData))
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct PhantomId(String);
impl SerializableId for PhantomId {
fn try_create(id: impl Into<String>) -> Result<Self, error::Error>
where
Self: Sized,
{
Ok(PhantomId(id.into()))
}
fn as_str(&self) -> &str {
""
}
fn id(&self) -> String {
String::from("")
}
fn key(&self) -> &'static str {
""
}
}
#[cfg(test)]
mod test_socket_info {
use super::*;
#[test]
fn v4() {
let socket_info = SocketInfo::<PhantomId>::try_create(None, "127.0.0.1", 8000).unwrap();
let json = serde_json::to_string(&socket_info).expect("serialize failed");
let decoded_socket_info: SocketInfo<PhantomId> =
serde_json::from_str(&json).expect("deserialize failed");
assert_eq!(socket_info, decoded_socket_info);
}
#[test]
fn v6() {
let socket_info =
SocketInfo::<PhantomId>::try_create(None, "2001:DB8:0:0:8:800:200C:417A", 8000)
.unwrap();
let json = serde_json::to_string(&socket_info).expect("serialize failed");
let decoded_socket_info: SocketInfo<PhantomId> =
serde_json::from_str(&json).expect("deserialize failed");
assert_eq!(socket_info, decoded_socket_info);
}
}