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
pub mod internal;
pub mod json;
pub mod proto;
use crate::error::Result;
pub trait Encoder: Send + Sync {
fn encode(&self, msg: crate::message::Message) -> Result<Vec<u8>>;
fn decode(&self, bin: &[u8]) -> Result<crate::message::Message>;
}
pub type BoxedEncoder = Box<dyn Encoder>;
impl<E: Encoder + ?Sized> Encoder for Box<E> {
fn encode(&self, msg: crate::message::Message) -> Result<Vec<u8>> {
(**self).encode(msg)
}
fn decode(&self, bin: &[u8]) -> Result<crate::message::Message> {
(**self).decode(bin)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Encoding {
Proto,
Json,
}
impl Encoding {
pub fn new() -> Self {
Self::default()
}
pub fn generate(&self) -> Result<BoxedEncoder> {
match self {
Self::Proto => Ok(Box::new(proto::Encoder)),
Self::Json => Ok(Box::new(json::Encoder)),
}
}
}
impl Default for Encoding {
fn default() -> Self {
Self::Proto
}
}