1use std::borrow::Borrow;
16use std::marker::PhantomData;
17
18use api::v1::region::{RegionRequest, RegionResponse};
19use prost::Message;
20use tonic::Status;
21use tonic::codec::{Codec, EncodeBuf, Encoder};
22use tonic_prost::ProstDecoder;
23
24pub(crate) struct RegionCodec<R>(PhantomData<R>);
26
27impl<R> Default for RegionCodec<R> {
28 fn default() -> Self {
29 Self(PhantomData)
30 }
31}
32
33impl<R> Codec for RegionCodec<R>
34where
35 R: Borrow<RegionRequest> + Send + 'static,
36{
37 type Encode = R;
38 type Decode = RegionResponse;
39 type Encoder = RegionEncoder<R>;
40 type Decoder = ProstDecoder<RegionResponse>;
41
42 fn encoder(&mut self) -> Self::Encoder {
43 RegionEncoder(PhantomData)
44 }
45
46 fn decoder(&mut self) -> Self::Decoder {
47 ProstDecoder::default()
48 }
49}
50
51pub(crate) struct RegionEncoder<R>(PhantomData<R>);
53
54impl<R: Borrow<RegionRequest>> Encoder for RegionEncoder<R> {
55 type Item = R;
56 type Error = Status;
57
58 fn encode(&mut self, item: R, buf: &mut EncodeBuf<'_>) -> Result<(), Status> {
59 item.borrow()
60 .encode(buf)
61 .map_err(|error| Status::internal(error.to_string()))
62 }
63}