1use std::{io::Write, marker::PhantomData};
3
4use prost::bytes::{Buf, BufMut, Bytes};
5use tonic::{
6 Status,
7 codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder},
8};
9
10#[derive(Debug)]
11pub struct TransparentEncoder(PhantomData<Bytes>);
12
13impl Encoder for TransparentEncoder {
14 type Error = Status;
15 type Item = Bytes;
16
17 fn encode(&mut self, item: Self::Item, buf: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
18 buf.writer()
19 .write_all(&item)
20 .map_err(|e| Status::internal(e.to_string()))?;
21 Ok(())
22 }
23}
24
25#[derive(Debug)]
26pub struct TransparentDecoder(PhantomData<Bytes>);
27
28impl Decoder for TransparentDecoder {
29 type Error = Status;
30 type Item = Bytes;
31
32 fn decode(&mut self, buf: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
33 let len = buf.remaining();
34 Ok(Some(buf.copy_to_bytes(len)))
35 }
36}
37
38#[derive(Debug, Clone)]
39pub struct TransparentCodec(PhantomData<(Bytes, Bytes)>);
40
41impl Default for TransparentCodec {
42 fn default() -> Self {
43 Self(PhantomData)
44 }
45}
46
47impl Codec for TransparentCodec {
48 type Decode = Bytes;
49 type Decoder = TransparentDecoder;
50 type Encode = Bytes;
51 type Encoder = TransparentEncoder;
52
53 fn encoder(&mut self) -> Self::Encoder {
54 TransparentEncoder(PhantomData)
55 }
56
57 fn decoder(&mut self) -> Self::Decoder {
58 TransparentDecoder(PhantomData)
59 }
60}