Skip to main content

ntex_codec/
lib.rs

1//! Utilities for encoding and decoding frames.
2
3use std::{fmt, io, rc::Rc};
4
5use ntex_bytes::{BytePages, Bytes, BytesMut};
6
7/// Trait of helper objects to write out messages as bytes.
8pub trait Encoder {
9    /// The type of items consumed by the `Encoder`
10    type Item;
11
12    /// The type of encoding errors.
13    type Error: fmt::Debug;
14
15    #[deprecated(since = "1.2.0", note = "Implement .encodev() method.")]
16    /// Encodes a frame into the buffer provided.
17    fn encode(&self, _: Self::Item, _: &mut BytesMut) -> Result<(), Self::Error> {
18        panic!("Encoder::encodev() must be implemented")
19    }
20
21    /// Encodes a frame into the buffer provided.
22    fn encodev(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
23        #[allow(deprecated)]
24        dst.with_bytes_mut(|buf| self.encode(item, buf))
25    }
26}
27
28/// Decoding of frames via buffers.
29pub trait Decoder {
30    /// The type of decoded frames.
31    type Item: fmt::Debug;
32
33    /// The type of unrecoverable frame decoding errors.
34    ///
35    /// If an individual message is ill-formed but can be ignored without
36    /// interfering with the processing of future messages, it may be more
37    /// useful to report the failure as an `Item`.
38    type Error: fmt::Debug;
39
40    /// Attempts to decode a frame from the provided buffer of bytes.
41    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
42}
43
44impl<T> Encoder for Rc<T>
45where
46    T: Encoder,
47{
48    type Item = T::Item;
49    type Error = T::Error;
50
51    #[allow(deprecated)]
52    fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
53        (**self).encode(item, dst)
54    }
55
56    fn encodev(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
57        (**self).encodev(item, dst)
58    }
59}
60
61impl<T> Decoder for Rc<T>
62where
63    T: Decoder,
64{
65    type Item = T::Item;
66    type Error = T::Error;
67
68    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
69        (**self).decode(src)
70    }
71}
72
73/// Bytes codec.
74///
75/// Reads/Writes chunks of bytes from a stream.
76#[derive(Debug, Copy, Clone)]
77pub struct BytesCodec;
78
79impl Encoder for BytesCodec {
80    type Item = Bytes;
81    type Error = io::Error;
82
83    #[inline]
84    fn encodev(&self, item: Bytes, dst: &mut BytePages) -> Result<(), Self::Error> {
85        dst.append(item);
86        Ok(())
87    }
88}
89
90impl Decoder for BytesCodec {
91    type Item = Bytes;
92    type Error = io::Error;
93
94    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
95        if src.is_empty() {
96            Ok(None)
97        } else {
98            Ok(Some(src.split_to(src.len())))
99        }
100    }
101}