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
|
//! Implement [`Serialize`] and [`Deserialize`] for [`Check`] and [`Ck`].
use crate::{Check, Ck, Invariant};
use serde::de::{Deserialize, Deserializer, Error};
use serde::ser::{Serialize, Serializer};
impl<I: Invariant, B: AsRef<str>> Serialize for Check<I, B> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<I: Invariant> Serialize for Ck<I> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<'de, I, B> Deserialize<'de> for Check<I, B>
where
I: Invariant,
B: AsRef<str> + Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let buf = Deserialize::deserialize(deserializer)?;
Check::from_buf(buf).map_err(Error::custom)
}
}
impl<'de: 'a, 'a, I: Invariant> Deserialize<'de> for &'a Ck<I> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let slice = Deserialize::deserialize(deserializer)?;
Ck::from_slice(slice).map_err(Error::custom)
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use strck_ident::{Ident, IntoCk};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Player<'a> {
#[serde(borrow)]
username: &'a Ident,
level: u32,
}
#[test]
fn test_zero_copy_deserialization() {
let qnn = Player {
username: "qnn".ck().unwrap(),
level: 100,
};
fn get() -> Player<'static> {
let ser = r#"{"username":"qnn","level":100}"#;
serde_json::from_str(&ser).unwrap()
}
let de = get();
assert_eq!(qnn, de);
}
}
|