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
use std::io;
use std::marker::PhantomData;
use bytes::{BufMut, BytesMut};
use tokio_io::_tokio_codec::{Encoder, Decoder};
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct JsonCodec<ENC, DEC, ERR>
{
enc: PhantomData<ENC>,
dec: PhantomData<DEC>,
err: PhantomData<ERR>,
}
#[derive(Debug)]
pub enum JsonError {
Io(io::Error),
Json(serde_json::Error),
}
impl From<io::Error> for JsonError {
fn from(e: io::Error) -> JsonError {
return JsonError::Io(e);
}
}
impl From<serde_json::Error> for JsonError {
fn from(e: serde_json::Error) -> JsonError {
return JsonError::Json(e);
}
}
impl <ENC, DEC, ERR>JsonCodec<ENC, DEC, ERR>
where
for<'de> DEC: Deserialize<'de> + Clone + Send + 'static,
for<'de> ENC: Serialize + Clone + Send + 'static,
ERR: From<serde_json::Error> + From<io::Error> + 'static,
{
pub fn new() -> JsonCodec<ENC, DEC, ERR> {
JsonCodec {enc: PhantomData, dec: PhantomData, err: PhantomData}
}
}
impl <ENC, DEC, ERR>Default for JsonCodec<ENC, DEC, ERR>
where
for<'de> DEC: Deserialize<'de> + Clone + Send + 'static,
for<'de> ENC: Serialize + Clone + Send + 'static,
ERR: From<serde_json::Error> + From<io::Error> + 'static,
{
fn default() -> JsonCodec<ENC, DEC, ERR> {
JsonCodec::new()
}
}
impl <ENC, DEC, ERR>Decoder for JsonCodec<ENC, DEC, ERR>
where
for<'de> DEC: Deserialize<'de> + Clone + Send + 'static,
for<'de> ENC: Serialize + Clone + Send + 'static,
ERR: From<serde_json::Error> + From<io::Error> + 'static,
{
type Item = DEC;
type Error = ERR;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let offset;
let res;
{
let de = serde_json::Deserializer::from_slice(&buf);
let mut iter = de.into_iter::<DEC>();
res = match iter.next() {
Some(Ok(v)) => Ok(Some(v)),
Some(Err(ref e)) if e.is_eof() => {
Ok(None)
},
Some(Err(e)) => Err(e.into()),
None => Ok(None),
};
offset = iter.byte_offset();
}
buf.advance(offset);
res
}
}
impl <ENC, DEC, ERR>Encoder for JsonCodec<ENC, DEC, ERR>
where
for<'de> DEC: Deserialize<'de> + Clone + Send + 'static,
for<'de> ENC: Serialize + Clone + Send + 'static,
ERR: From<serde_json::Error> + From<io::Error> + 'static,
{
type Item = ENC;
type Error = ERR;
fn encode(&mut self, data: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> {
let j = serde_json::to_string(&data)?;
buf.reserve(j.len());
buf.put_slice(&j.as_bytes());
Ok(())
}
}
#[cfg(test)]
mod test {
use bytes::BytesMut;
use tokio_codec::{Encoder, Decoder};
use super::{JsonCodec, JsonError};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct TestStruct {
pub name: String,
}
#[test]
fn json_codec_encode_decode() {
let mut codec = JsonCodec::<TestStruct, TestStruct, JsonError>::new();
let mut buff = BytesMut::new();
let item1 = TestStruct{name: "Test name".to_owned()};
codec.encode(item1.clone(), &mut buff).unwrap();
let item2 = codec.decode(&mut buff).unwrap().unwrap();
assert_eq!(item1, item2);
assert_eq!(codec.decode(&mut buff).unwrap(), None);
assert_eq!(buff.len(), 0);
}
#[test]
fn json_codec_partial_decode() {
let mut codec = JsonCodec::<TestStruct, TestStruct, JsonError>::new();
let mut buff = BytesMut::new();
let item1 = TestStruct{name: "Test name".to_owned()};
codec.encode(item1.clone(), &mut buff).unwrap();
let mut start = buff.clone().split_to(4);
assert_eq!(codec.decode(&mut start).unwrap(), None);
codec.decode(&mut buff).unwrap().unwrap();
assert_eq!(buff.len(), 0);
}
}