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
#![deny(rust_2018_idioms, warnings)]
use std::{io, rc::Rc};
use ntex_bytes::{Bytes, BytesMut, BytesVec};
pub trait Encoder {
type Item;
type Error: std::fmt::Debug;
fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error>;
fn encode_vec(&self, item: Self::Item, dst: &mut BytesVec) -> Result<(), Self::Error> {
dst.with_bytes_mut(|dst| self.encode(item, dst))
}
}
pub trait Decoder {
type Item;
type Error: std::fmt::Debug;
fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
fn decode_vec(&self, src: &mut BytesVec) -> Result<Option<Self::Item>, Self::Error> {
src.with_bytes_mut(|src| self.decode(src))
}
}
impl<T> Encoder for Rc<T>
where
T: Encoder,
{
type Item = T::Item;
type Error = T::Error;
fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
(**self).encode(item, dst)
}
}
impl<T> Decoder for Rc<T>
where
T: Decoder,
{
type Item = T::Item;
type Error = T::Error;
fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
(**self).decode(src)
}
}
#[derive(Debug, Copy, Clone)]
pub struct BytesCodec;
impl Encoder for BytesCodec {
type Item = Bytes;
type Error = io::Error;
#[inline]
fn encode(&self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
dst.extend_from_slice(&item[..]);
Ok(())
}
}
impl Decoder for BytesCodec {
type Item = BytesMut;
type Error = io::Error;
fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.is_empty() {
Ok(None)
} else {
let len = src.len();
Ok(Some(src.split_to(len)))
}
}
}