1#![deny(rust_2018_idioms, warnings)]
2use std::{io, rc::Rc};
5
6use ntex_bytes::{Bytes, BytesMut, BytesVec};
7
8pub trait Encoder {
10 type Item;
12
13 type Error: std::fmt::Debug;
15
16 fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error>;
18
19 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
25pub trait Decoder {
27 type Item;
29
30 type Error: std::fmt::Debug;
36
37 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
39
40 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#[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}