distant_net/common/transport/framed/
codec.rs1use std::io;
2
3use dyn_clone::DynClone;
4
5use super::Frame;
6
7mod chain;
8mod compression;
9mod encryption;
10mod plain;
11mod predicate;
12
13pub use chain::*;
14pub use compression::*;
15pub use encryption::*;
16pub use plain::*;
17pub use predicate::*;
18
19pub trait Codec: DynClone {
23 fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>>;
25
26 fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>>;
28}
29
30pub type BoxedCodec = Box<dyn Codec + Send + Sync>;
32
33macro_rules! impl_traits {
34 ($($x:tt)+) => {
35 impl Clone for Box<dyn $($x)+> {
36 fn clone(&self) -> Self {
37 dyn_clone::clone_box(&**self)
38 }
39 }
40
41 impl Codec for Box<dyn $($x)+> {
42 fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
43 Codec::encode(self.as_mut(), frame)
44 }
45
46 fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
47 Codec::decode(self.as_mut(), frame)
48 }
49 }
50 };
51}
52
53impl_traits!(Codec);
54impl_traits!(Codec + Send);
55impl_traits!(Codec + Sync);
56impl_traits!(Codec + Send + Sync);
57
58pub trait CodecExt {
60 fn chain<T>(self, codec: T) -> ChainCodec<Self, T>
62 where
63 Self: Sized;
64}
65
66impl<C: Codec> CodecExt for C {
67 fn chain<T>(self, codec: T) -> ChainCodec<Self, T> {
68 ChainCodec::new(self, codec)
69 }
70}