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 let mut buf = BytesMut::new();
24 #[allow(deprecated)]
25 self.encode(item, &mut buf)?;
26 dst.append(buf.freeze());
27 Ok(())
28 }
29}
30
31pub trait Decoder {
33 type Item: fmt::Debug;
35
36 type Error: fmt::Debug;
42
43 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
45}
46
47impl<T> Encoder for Rc<T>
48where
49 T: Encoder,
50{
51 type Item = T::Item;
52 type Error = T::Error;
53
54 #[allow(deprecated)]
55 fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
56 (**self).encode(item, dst)
57 }
58
59 fn encodev(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
60 (**self).encodev(item, dst)
61 }
62}
63
64impl<T> Decoder for Rc<T>
65where
66 T: Decoder,
67{
68 type Item = T::Item;
69 type Error = T::Error;
70
71 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
72 (**self).decode(src)
73 }
74}
75
76#[derive(Debug, Copy, Clone)]
80pub struct BytesCodec;
81
82impl Encoder for BytesCodec {
83 type Item = Bytes;
84 type Error = io::Error;
85
86 #[inline]
87 fn encodev(&self, item: Bytes, dst: &mut BytePages) -> Result<(), Self::Error> {
88 dst.append(item);
89 Ok(())
90 }
91}
92
93impl Decoder for BytesCodec {
94 type Item = Bytes;
95 type Error = io::Error;
96
97 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
98 if src.is_empty() {
99 Ok(None)
100 } else {
101 Ok(Some(src.split_to(src.len())))
102 }
103 }
104}