1#![deny(rust_2018_idioms, warnings)]
2use std::{io, rc::Rc};
5
6use ntex_bytes::{Bytes, BytesMut};
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
20pub trait Decoder {
22 type Item;
24
25 type Error: std::fmt::Debug;
31
32 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>;
34}
35
36impl<T> Encoder for Rc<T>
37where
38 T: Encoder,
39{
40 type Item = T::Item;
41 type Error = T::Error;
42
43 fn encode(&self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
44 (**self).encode(item, dst)
45 }
46}
47
48impl<T> Decoder for Rc<T>
49where
50 T: Decoder,
51{
52 type Item = T::Item;
53 type Error = T::Error;
54
55 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
56 (**self).decode(src)
57 }
58}
59
60#[derive(Debug, Copy, Clone)]
64pub struct BytesCodec;
65
66impl Encoder for BytesCodec {
67 type Item = Bytes;
68 type Error = io::Error;
69
70 #[inline]
71 fn encode(&self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
72 dst.extend_from_slice(&item[..]);
73 Ok(())
74 }
75}
76
77impl Decoder for BytesCodec {
78 type Item = Bytes;
79 type Error = io::Error;
80
81 fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
82 if src.is_empty() {
83 Ok(None)
84 } else {
85 Ok(Some(src.split_to(src.len())))
86 }
87 }
88}