dencode/
decoder.rs

1use std::io::Error;
2
3use bytes::BytesMut;
4
5use super::{framed_write::FramedWriteImpl, fuse::Fuse};
6
7/// Decoding of frames via buffers, for use with `FramedRead`.
8pub trait Decoder {
9    /// The type of items returned by `decode`
10    type Item;
11    /// The type of decoding errors.
12    type Error: From<Error>;
13
14    /// Decode an item from the src `BytesMut` into an item
15    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
16
17    /// Called when the input stream reaches EOF, signaling a last attempt to decode
18    ///
19    /// # Notes
20    ///
21    /// The default implementation of this method invokes the `Decoder::decode` method.
22    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
23        self.decode(src)
24    }
25}
26
27impl<T, U: Decoder> Decoder for Fuse<T, U> {
28    type Item = U::Item;
29    type Error = U::Error;
30
31    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
32        self.codec.decode(src)
33    }
34
35    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
36        self.codec.decode_eof(src)
37    }
38}
39
40impl<T: Decoder> Decoder for FramedWriteImpl<T> {
41    type Item = T::Item;
42    type Error = T::Error;
43
44    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
45        self.inner.decode(src)
46    }
47
48    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
49        self.inner.decode_eof(src)
50    }
51}