distant_net/common/transport/framed/
codec.rs

1use 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
19/// Represents abstraction that implements specific encoder and decoder logic to transform an
20/// arbitrary collection of bytes. This can be used to encrypt and authenticate bytes sent and
21/// received by transports.
22pub trait Codec: DynClone {
23    /// Encodes a frame's item
24    fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>>;
25
26    /// Decodes a frame's item
27    fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>>;
28}
29
30/// Represents a [`Box`]ed version of [`Codec`]
31pub 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
58/// Interface that provides extensions to the codec interface
59pub trait CodecExt {
60    /// Chains this codec with another codec
61    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}