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};
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
20/// Decoding of frames via buffers.
21pub trait Decoder {
22    /// The type of decoded frames.
23    type Item;
24
25    /// The type of unrecoverable frame decoding errors.
26    ///
27    /// If an individual message is ill-formed but can be ignored without
28    /// interfering with the processing of future messages, it may be more
29    /// useful to report the failure as an `Item`.
30    type Error: std::fmt::Debug;
31
32    /// Attempts to decode a frame from the provided buffer of bytes.
33    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
34}
35
36impl<T> Encoder for Rc<T>
37where
38    T: Encoder,
39{
40    type Item = T::Item;
41    type Error = T::Error;
42
43    fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
44        (**self).encode(item, dst)
45    }
46}
47
48impl<T> Decoder for Rc<T>
49where
50    T: Decoder,
51{
52    type Item = T::Item;
53    type Error = T::Error;
54
55    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
56        (**self).decode(src)
57    }
58}
59
60/// Bytes codec.
61///
62/// Reads/Writes chunks of bytes from a stream.
63#[derive(Debug, Copy, Clone)]
64pub struct BytesCodec;
65
66impl Encoder for BytesCodec {
67    type Item = Bytes;
68    type Error = io::Error;
69
70    #[inline]
71    fn encode(&self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
72        dst.extend_from_slice(&item[..]);
73        Ok(())
74    }
75}
76
77impl Decoder for BytesCodec {
78    type Item = Bytes;
79    type Error = io::Error;
80
81    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
82        if src.is_empty() {
83            Ok(None)
84        } else {
85            Ok(Some(src.split_to(src.len())))
86        }
87    }
88}