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
use std::fmt::Display;
use std::str::FromStr;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
#[derive(Clone, Copy, Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SerdeStr<T> {
pub value: T,
}
impl<T> SerdeStr<T> {
#[inline]
pub fn value(&self) -> &T {
&self.value
}
#[inline]
pub fn value_mut(&mut self) -> &mut T {
&mut self.value
}
#[inline]
pub fn set_value(&mut self, t: T) {
self.value = t;
}
#[inline]
pub fn unwrap(self) -> T {
self.value
}
}
impl<T> From<T> for SerdeStr<T> {
#[inline]
fn from(value: T) -> Self {
Self { value }
}
}
impl<'de, T: FromStr> Deserialize<'de> for SerdeStr<T>
where
T: FromStr,
<T as FromStr>::Err: Display,
{
#[inline]
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self {
value: String::deserialize(de)?
.parse()
.map_err(|err| Error::custom(err))?,
})
}
}
impl<T> Serialize for SerdeStr<T>
where
T: Display,
{
#[inline]
fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.value.to_string().serialize(ser)
}
}
#[cfg(test)]
mod test_de {
use std::collections::HashMap;
use serde_derive::Deserialize;
use crate::SerdeStr;
#[derive(Debug, PartialEq)]
struct IsParsed(i32);
impl std::str::FromStr for IsParsed {
type Err = &'static str;
fn from_str(str: &str) -> Result<Self, Self::Err> {
Ok(IsParsed(str.len() as i32))
}
}
#[derive(Debug, Deserialize, PartialEq)]
struct Schema {
data: SerdeStr<IsParsed>,
}
#[test]
fn test_parse() {
let mut map = HashMap::new();
map.insert("data", "abc");
let json = serde_json::to_string(&map).unwrap();
let parsed = serde_json::from_str::<Schema>(&json);
assert_eq!(
parsed.unwrap(),
Schema {
data: SerdeStr { value: IsParsed(3) }
}
);
}
}
#[cfg(test)]
mod test_ser {
use std::fmt::{Display, Formatter, Result};
use serde_derive::Serialize;
use crate::SerdeStr;
#[derive(Debug)]
struct CanDisplay(&'static str);
impl Display for CanDisplay {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "{}", self.0.len())
}
}
#[derive(Debug, Serialize)]
struct Schema {
data: SerdeStr<CanDisplay>,
}
#[test]
fn test_display() {
let json = serde_json::to_string(&Schema {
data: SerdeStr {
value: CanDisplay("abc"),
},
});
assert_eq!(json.unwrap(), r##"{"data":"3"}"##);
}
}