ntex_codec/
lib.rs

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