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
|
use karyon_core::util::{decode, encode, encode_into_slice};
use karyon_net::{
codec::{Codec, Decoder, Encoder, LengthCodec},
Result,
};
use crate::message::{NetMsg, RefreshMsg};
#[derive(Clone)]
pub struct NetMsgCodec {
inner_codec: LengthCodec,
}
impl NetMsgCodec {
pub fn new() -> Self {
Self {
inner_codec: LengthCodec {},
}
}
}
impl Codec for NetMsgCodec {
type Item = NetMsg;
}
impl Encoder for NetMsgCodec {
type EnItem = NetMsg;
fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result<usize> {
let src = encode(src)?;
self.inner_codec.encode(&src, dst)
}
}
impl Decoder for NetMsgCodec {
type DeItem = NetMsg;
fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeItem)>> {
match self.inner_codec.decode(src)? {
Some((n, s)) => {
let (m, _) = decode::<Self::DeItem>(&s)?;
Ok(Some((n, m)))
}
None => Ok(None),
}
}
}
#[derive(Clone)]
pub struct RefreshMsgCodec {}
impl Codec for RefreshMsgCodec {
type Item = RefreshMsg;
}
impl Encoder for RefreshMsgCodec {
type EnItem = RefreshMsg;
fn encode(&self, src: &Self::EnItem, dst: &mut [u8]) -> Result<usize> {
let n = encode_into_slice(src, dst)?;
Ok(n)
}
}
impl Decoder for RefreshMsgCodec {
type DeItem = RefreshMsg;
fn decode(&self, src: &mut [u8]) -> Result<Option<(usize, Self::DeItem)>> {
let (m, n) = decode::<Self::DeItem>(src)?;
Ok(Some((n, m)))
}
}
|