codecs/encoding/framing/
bytes.rs

1use bytes::BytesMut;
2use serde::{Deserialize, Serialize};
3use tokio_util::codec::Encoder;
4
5use super::BoxedFramingError;
6
7/// Config used to build a `BytesEncoder`.
8#[derive(Debug, Clone, Deserialize, Serialize)]
9pub struct BytesEncoderConfig;
10
11impl BytesEncoderConfig {
12    /// Creates a `BytesEncoderConfig`.
13    pub const fn new() -> Self {
14        Self
15    }
16
17    /// Build the `BytesEncoder` from this configuration.
18    pub fn build(&self) -> BytesEncoder {
19        BytesEncoder
20    }
21}
22
23/// An encoder for handling of plain bytes.
24///
25/// This encoder does nothing, really. It mainly exists as a symmetric
26/// counterpart to `BytesDeserializer`. `BytesEncoder` can be used to explicitly
27/// disable framing for formats that encode intrinsic length information - since
28/// a sink might set a framing configuration by default depending on the
29/// streaming or message based nature of the sink.
30#[derive(Debug, Clone)]
31pub struct BytesEncoder;
32
33impl Default for BytesEncoderConfig {
34    /// Creates a `BytesEncoder`.
35    fn default() -> Self {
36        Self
37    }
38}
39
40impl Encoder<()> for BytesEncoder {
41    type Error = BoxedFramingError;
42
43    fn encode(&mut self, _: (), _: &mut BytesMut) -> Result<(), BoxedFramingError> {
44        Ok(())
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn encode() {
54        let mut codec = BytesEncoder;
55
56        let mut buffer = BytesMut::from("abc");
57        codec.encode((), &mut buffer).unwrap();
58
59        assert_eq!(b"abc", &buffer[..]);
60    }
61}