1use std::{fmt, io, rc::Rc};
4
5use ntex_bytes::{BytePages, Bytes, BytesMut};
6
7pub trait Encoder {
9 type Item;
11
12 type Error: fmt::Debug;
14
15 #[deprecated(since = "1.2.0", note = "Implement .encodev() method.")]
16 fn encode(&self, _: Self::Item, _: &mut BytesMut) -> Result<(), Self::Error> {
18 panic!("Encoder::encodev() must be implemented")
19 }
20
21 fn encodev(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
23 #[allow(deprecated)]
24 dst.with_bytes_mut(|buf| self.encode(item, buf))
25 }
26}
27
28pub trait Decoder {
30 type Item: fmt::Debug;
32
33 type Error: fmt::Debug;
39
40 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
42}
43
44impl<T> Encoder for Rc<T>
45where
46 T: Encoder,
47{
48 type Item = T::Item;
49 type Error = T::Error;
50
51 #[allow(deprecated)]
52 fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
53 (**self).encode(item, dst)
54 }
55
56 fn encodev(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
57 (**self).encodev(item, dst)
58 }
59}
60
61impl<T> Decoder for Rc<T>
62where
63 T: Decoder,
64{
65 type Item = T::Item;
66 type Error = T::Error;
67
68 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
69 (**self).decode(src)
70 }
71}
72
73#[derive(Debug, Copy, Clone)]
77pub struct BytesCodec;
78
79impl Encoder for BytesCodec {
80 type Item = Bytes;
81 type Error = io::Error;
82
83 #[inline]
84 fn encodev(&self, item: Bytes, dst: &mut BytePages) -> Result<(), Self::Error> {
85 dst.append(item);
86 Ok(())
87 }
88}
89
90impl Decoder for BytesCodec {
91 type Item = Bytes;
92 type Error = io::Error;
93
94 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
95 if src.is_empty() {
96 Ok(None)
97 } else {
98 Ok(Some(src.split_to(src.len())))
99 }
100 }
101}