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
extern crate bytes;
extern crate tokio_io;
use bytes::BytesMut;
use tokio_io::codec::{Decoder, Encoder};
#[derive(Debug)]
pub enum Error {
Fmt(std::fmt::Error),
Io(std::io::Error),
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
#[derive(Default)]
pub struct U8Codec {}
impl Encoder for U8Codec {
type Item = u8;
type Error = Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
Ok(dst.extend(&[item]))
}
}
impl Decoder for U8Codec {
type Item = u8;
type Error = std::io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.is_empty() {
Ok(None)
} else {
Ok(Some(src.split_to(1)[0]))
}
}
}