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
use std::io;
use bytes::BytesMut;
use encoding::label::encoding_from_whatwg_label;
use encoding::{DecoderTrap, EncoderTrap, EncodingRef};
use tokio_util::codec::{Decoder, Encoder};
use crate::error;
pub struct LineCodec {
encoding: EncodingRef,
next_index: usize,
}
impl LineCodec {
pub fn new(label: &str) -> error::Result<LineCodec> {
encoding_from_whatwg_label(label)
.map(|enc| LineCodec {
encoding: enc,
next_index: 0,
})
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Attempted to use unknown codec {}.", label)[..],
)
.into()
})
}
}
impl Decoder for LineCodec {
type Item = String;
type Error = error::ProtocolError;
fn decode(&mut self, src: &mut BytesMut) -> error::Result<Option<String>> {
if let Some(offset) = src[self.next_index..].iter().position(|b| *b == b'\n') {
let line = src.split_to(self.next_index + offset + 1);
self.next_index = 0;
match self.encoding.decode(line.as_ref(), DecoderTrap::Replace) {
Ok(data) => Ok(Some(data)),
Err(data) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Failed to decode {} as {}.", data, self.encoding.name())[..],
)
.into()),
}
} else {
self.next_index = src.len();
Ok(None)
}
}
}
impl Encoder<String> for LineCodec {
type Error = error::ProtocolError;
fn encode(&mut self, msg: String, dst: &mut BytesMut) -> error::Result<()> {
let data: error::Result<Vec<u8>> = self
.encoding
.encode(&msg, EncoderTrap::Replace)
.map_err(|data| {
io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Failed to encode {} as {}.", data, self.encoding.name())[..],
)
.into()
});
dst.extend(&data?);
Ok(())
}
}