1pub mod compression;
7pub mod decode;
8pub mod encode;
9
10use std::{io, marker::PhantomData, mem::size_of};
11
12use bytes::Bytes;
13use pilota::{LinkedBytes, pb::Message};
14
15use crate::{Status, status::Code::Internal};
16
17const PREFIX_LEN: usize = size_of::<u32>() + size_of::<u8>();
18const BUFFER_SIZE: usize = 8 * 1024;
19
20pub trait Encoder {
22 type Item;
24
25 type Error: From<io::Error>;
29
30 fn encode(&mut self, item: Self::Item, dst: &mut LinkedBytes) -> Result<(), Self::Error>;
32}
33
34#[derive(Debug, Clone)]
35pub struct DefaultEncoder<T>(PhantomData<T>);
36
37impl<T: Message> Encoder for DefaultEncoder<T> {
38 type Item = T;
39 type Error = Status;
40
41 fn encode(&mut self, item: Self::Item, dst: &mut LinkedBytes) -> Result<(), Self::Error> {
42 let mut ctx = pilota::pb::EncodeLengthContext::default();
43 let required_len = item.encoded_len(&mut ctx) - ctx.zero_copy_len;
44 dst.reserve(required_len);
45 item.encode(dst)
46 .map_err(|e| Status::new(Internal, e.to_string()))
47 }
48}
49
50impl<T> Default for DefaultEncoder<T> {
51 fn default() -> Self {
52 DefaultEncoder(PhantomData)
53 }
54}
55
56pub trait Decoder {
58 type Item;
60
61 type Error: From<io::Error>;
63
64 fn decode(&mut self, src: Bytes) -> Result<Option<Self::Item>, Self::Error>;
66}
67
68#[derive(Debug, Clone)]
69pub struct DefaultDecoder<T>(PhantomData<fn(T)>);
70
71impl<T: Message + Default> Decoder for DefaultDecoder<T> {
72 type Item = T;
73 type Error = Status;
74
75 fn decode(&mut self, src: Bytes) -> Result<Option<Self::Item>, Self::Error> {
76 Message::decode(src)
77 .map(Some)
78 .map_err(|e| Status::new(Internal, e.to_string()))
79 }
80}
81
82impl<T> Default for DefaultDecoder<T> {
83 fn default() -> Self {
84 DefaultDecoder(PhantomData)
85 }
86}