Skip to main content

ntex_codec/
lib.rs

1//! Traits for encoding and decoding frames.
2//!
3//! A codec turns a byte stream into frames and back. [`Decoder`] splits
4//! incoming bytes into frames, [`Encoder`] serializes outgoing frames. The
5//! `ntex-io` crate drives them: `Io::recv()` and `IoRef::decode()` run the
6//! decoder on the read buffer, `Io::send()` and `IoRef::encode()` run the
7//! encoder on the write buffer, and the `ntex-dispatcher` crate uses both to
8//! connect a stream to a service.
9//!
10//! Both traits take `&self`, since a codec is shared between the reading and
11//! writing sides. A codec that keeps state between calls, such as a parser
12//! position or negotiated settings, has to use interior mutability, e.g.
13//! [`Cell`](std::cell::Cell) or [`RefCell`](std::cell::RefCell).
14//!
15//! # Example
16//!
17//! A codec for newline-terminated lines:
18//!
19//! ```
20//! use std::io;
21//!
22//! use ntex_bytes::{BytePages, Bytes, BytesMut};
23//! use ntex_codec::{Decoder, Encoder};
24//!
25//! struct LineCodec;
26//!
27//! impl Decoder for LineCodec {
28//!     type Item = Bytes;
29//!     type Error = io::Error;
30//!
31//!     fn decode(&self, src: &mut BytesMut) -> Result<Option<Bytes>, io::Error> {
32//!         match src.iter().position(|b| *b == b'\n') {
33//!             // consume the line and its terminator
34//!             Some(n) => Ok(Some(src.split_to(n + 1).slice(..n))),
35//!             // incomplete line, wait for more input
36//!             None => Ok(None),
37//!         }
38//!     }
39//!
40//!     fn decode_eof(&self, src: &mut BytesMut) -> Result<Option<Bytes>, io::Error> {
41//!         match self.decode(src)? {
42//!             Some(line) => Ok(Some(line)),
43//!             // the last line has no terminator
44//!             None if !src.is_empty() => Ok(Some(src.split_to(src.len()))),
45//!             None => Ok(None),
46//!         }
47//!     }
48//! }
49//!
50//! impl Encoder for LineCodec {
51//!     type Item = Bytes;
52//!     type Error = io::Error;
53//!
54//!     fn encode(&self, item: Bytes, dst: &mut BytePages) -> Result<(), io::Error> {
55//!         if item.contains(&b'\n') {
56//!             return Err(io::Error::new(io::ErrorKind::InvalidInput, "newline in line"));
57//!         }
58//!         dst.append(item);
59//!         dst.extend_from_slice(b"\n");
60//!         Ok(())
61//!     }
62//! }
63//!
64//! let mut src = BytesMut::from(&b"one\ntwo"[..]);
65//! assert_eq!(LineCodec.decode(&mut src).unwrap().unwrap(), "one");
66//! assert!(LineCodec.decode(&mut src).unwrap().is_none());
67//! assert_eq!(LineCodec.decode_eof(&mut src).unwrap().unwrap(), "two");
68//! assert!(LineCodec.decode_eof(&mut src).unwrap().is_none());
69//! ```
70
71#![forbid(unsafe_code)]
72
73use std::{fmt, io, rc::Rc};
74
75use ntex_bytes::{BytePages, Bytes, BytesMut};
76
77/// Serializes frames into bytes.
78pub trait Encoder {
79    /// The type of frames consumed by the encoder.
80    type Item;
81
82    /// The type of encoding errors.
83    type Error: fmt::Debug;
84
85    /// Encodes a frame and appends it to `dst`.
86    ///
87    /// `dst` is the write buffer, a list of pages. [`BytePages::append`] adds
88    /// a `Bytes` value as a page of its own without copying it, while
89    /// [`BytePages::extend_from_slice`] and the [`BufMut`](ntex_bytes::BufMut)
90    /// methods copy into the pages.
91    ///
92    /// Output written to `dst` is not rolled back when this returns an
93    /// error, it is sent like any other output. Validate the frame before
94    /// writing it, so that an error does not leave a partial frame behind.
95    fn encode(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error>;
96}
97
98/// Splits a byte stream into frames.
99pub trait Decoder {
100    /// The type of decoded frames.
101    type Item: fmt::Debug;
102
103    /// The type of unrecoverable frame decoding errors.
104    ///
105    /// If an individual message is ill-formed but can be ignored without
106    /// interfering with the processing of future messages, it may be more
107    /// useful to report the failure as an `Item`.
108    type Error: fmt::Debug;
109
110    /// Attempts to decode a frame from the buffered input.
111    ///
112    /// Returns `Ok(Some(item))` after removing exactly one frame's bytes from
113    /// the front of `src`, and `Ok(None)` if `src` does not hold a complete
114    /// frame yet. On `None` the partial frame must stay in `src`, it is
115    /// passed in again together with the input that arrives next.
116    ///
117    /// This is called repeatedly while it returns frames, and may be called
118    /// with an empty buffer.
119    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
120
121    /// Attempts to decode a frame once the transport reached a clean EOF.
122    ///
123    /// The peer closed its write half and no further input will arrive, so
124    /// this is the decoder's chance to produce a frame from whatever is left
125    /// in `src`, or to report a truncated one as an error. Once the transport
126    /// is at EOF it is used instead of [`decode`](Self::decode) for every
127    /// decode attempt, it may be called again after it returned `None`, and
128    /// with an empty buffer.
129    ///
130    /// The default implementation calls [`decode`](Self::decode).
131    fn decode_eof(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
132        self.decode(src)
133    }
134}
135
136impl<T> Encoder for Rc<T>
137where
138    T: Encoder,
139{
140    type Item = T::Item;
141    type Error = T::Error;
142
143    fn encode(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
144        (**self).encode(item, dst)
145    }
146}
147
148impl<T> Decoder for Rc<T>
149where
150    T: Decoder,
151{
152    type Item = T::Item;
153    type Error = T::Error;
154
155    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
156        (**self).decode(src)
157    }
158
159    fn decode_eof(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
160        (**self).decode_eof(src)
161    }
162}
163
164/// Passes bytes through unchanged.
165///
166/// Decoding returns everything buffered as one frame, and returns `None` only
167/// when the buffer is empty. Encoding appends the `Bytes` value to the write
168/// buffer as is, without copying it.
169#[derive(Debug, Copy, Clone)]
170pub struct BytesCodec;
171
172impl Encoder for BytesCodec {
173    type Item = Bytes;
174    type Error = io::Error;
175
176    #[inline]
177    fn encode(&self, item: Bytes, dst: &mut BytePages) -> Result<(), Self::Error> {
178        dst.append(item);
179        Ok(())
180    }
181}
182
183impl Decoder for BytesCodec {
184    type Item = Bytes;
185    type Error = io::Error;
186
187    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
188        if src.is_empty() {
189            Ok(None)
190        } else {
191            Ok(Some(src.split_to(src.len())))
192        }
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use std::cell::Cell;
199
200    use super::*;
201
202    /// Decodes one-byte frames and counts `decode_eof` calls.
203    #[derive(Default)]
204    struct ByteCodec {
205        eof: Cell<usize>,
206    }
207
208    impl Decoder for ByteCodec {
209        type Item = u8;
210        type Error = io::Error;
211
212        fn decode(&self, src: &mut BytesMut) -> Result<Option<u8>, io::Error> {
213            if src.is_empty() {
214                Ok(None)
215            } else {
216                Ok(Some(src.split_to(1)[0]))
217            }
218        }
219
220        fn decode_eof(&self, src: &mut BytesMut) -> Result<Option<u8>, io::Error> {
221            self.eof.set(self.eof.get() + 1);
222            self.decode(src)
223        }
224    }
225
226    /// Uses the default `decode_eof`.
227    struct DefaultEof;
228
229    impl Decoder for DefaultEof {
230        type Item = usize;
231        type Error = io::Error;
232
233        fn decode(&self, src: &mut BytesMut) -> Result<Option<usize>, io::Error> {
234            let len = src.len();
235            src.clear();
236            Ok(Some(len))
237        }
238    }
239
240    /// STATEMENT: `BytesCodec` passes bytes through unchanged: decode drains the whole buffer,
241    /// returns `None` when it is empty, and encode appends frames in order.
242    ///
243    /// HOW:
244    /// - Decode an empty buffer with `decode` and `decode_eof`; expect `None`.
245    /// - Decode `hello` and `eof`; expect each whole chunk and an emptied source buffer.
246    /// - Encode `hello `, `world` and an empty frame; expect 11 bytes `hello world`.
247    #[test]
248    fn bytes_codec() {
249        let codec = BytesCodec;
250        let codec2 = codec;
251        assert_eq!(format!("{:?}", codec2.clone()), "BytesCodec");
252
253        let mut src = BytesMut::new();
254        assert!(codec.decode(&mut src).unwrap().is_none());
255        assert!(codec.decode_eof(&mut src).unwrap().is_none());
256
257        src.extend_from_slice(b"hello");
258        assert_eq!(codec.decode(&mut src).unwrap().unwrap(), "hello");
259        assert!(src.is_empty());
260        src.extend_from_slice(b"eof");
261        assert_eq!(codec.decode_eof(&mut src).unwrap().unwrap(), "eof");
262        assert!(src.is_empty());
263
264        let mut dst = BytePages::default();
265        codec
266            .encode(Bytes::from_static(b"hello "), &mut dst)
267            .unwrap();
268        codec
269            .encode(Bytes::from_static(b"world"), &mut dst)
270            .unwrap();
271        codec.encode(Bytes::new(), &mut dst).unwrap();
272        assert_eq!(dst.len(), 11);
273        assert_eq!(dst.freeze(), "hello world");
274    }
275
276    /// STATEMENT: The default `Decoder::decode_eof` delegates to `decode`.
277    ///
278    /// HOW:
279    /// - Call `decode_eof` on a codec that only implements `decode` (returns the consumed
280    ///   length).
281    /// - Expect `Some(3)` for `abc`, then `Some(0)` for the drained buffer.
282    #[test]
283    fn default_decode_eof() {
284        let mut src = BytesMut::from(&b"abc"[..]);
285        assert_eq!(DefaultEof.decode_eof(&mut src).unwrap(), Some(3));
286        assert_eq!(DefaultEof.decode_eof(&mut src).unwrap(), Some(0));
287    }
288
289    /// STATEMENT: `Rc<C>` forwards `decode`, `decode_eof` and `encode` to the inner codec,
290    /// including an overridden `decode_eof`.
291    ///
292    /// HOW:
293    /// - Decode `ab` through `Rc<ByteCodec>`; expect `a`, then `b` from `decode_eof`.
294    /// - Check the inner `decode_eof` counter reached 2, so the override was used.
295    /// - Encode through `Rc<BytesCodec>` and expect the bytes in the output pages.
296    #[test]
297    fn rc_codec() {
298        let codec = Rc::new(ByteCodec::default());
299        let mut src = BytesMut::from(&b"ab"[..]);
300        assert_eq!(codec.decode(&mut src).unwrap(), Some(b'a'));
301        assert_eq!(codec.eof.get(), 0);
302        // forwards to the inner `decode_eof`, not the default one
303        assert_eq!(codec.decode_eof(&mut src).unwrap(), Some(b'b'));
304        assert_eq!(codec.decode_eof(&mut src).unwrap(), None);
305        assert_eq!(codec.eof.get(), 2);
306
307        let codec = Rc::new(BytesCodec);
308        let mut dst = BytePages::default();
309        codec.encode(Bytes::from_static(b"rc"), &mut dst).unwrap();
310        assert_eq!(dst.freeze(), "rc");
311    }
312}