apache_dubbo/triple/codec/
prost.rs1use super::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
19use prost::Message;
20use std::marker::PhantomData;
21
22#[derive(Debug, Clone)]
24pub struct ProstCodec<T, U> {
25 _pd: PhantomData<(T, U)>,
26}
27
28impl<T, U> Default for ProstCodec<T, U> {
29 fn default() -> Self {
30 Self { _pd: PhantomData }
31 }
32}
33
34impl<T, U> Codec for ProstCodec<T, U>
35where
36 T: Message + Send + 'static,
37 U: Message + Default + Send + 'static,
38{
39 type Encode = T;
40 type Decode = U;
41
42 type Encoder = ProstEncoder<T>;
43 type Decoder = ProstDecoder<U>;
44
45 fn encoder(&mut self) -> Self::Encoder {
46 ProstEncoder(PhantomData)
47 }
48
49 fn decoder(&mut self) -> Self::Decoder {
50 ProstDecoder(PhantomData)
51 }
52}
53
54#[derive(Debug, Clone, Default)]
56pub struct ProstEncoder<T>(PhantomData<T>);
57
58impl<T: Message> Encoder for ProstEncoder<T> {
59 type Item = T;
60 type Error = crate::status::Status;
61
62 fn encode(&mut self, item: Self::Item, buf: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
63 item.encode(buf)
64 .expect("Message only errors if not enough space");
65
66 Ok(())
67 }
68}
69
70#[derive(Debug, Clone, Default)]
72pub struct ProstDecoder<U>(PhantomData<U>);
73
74impl<U: Message + Default> Decoder for ProstDecoder<U> {
75 type Item = U;
76 type Error = crate::status::Status;
77
78 fn decode(&mut self, buf: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
79 let item = Message::decode(buf)
80 .map(Option::Some)
81 .map_err(from_decode_error)?;
82
83 Ok(item)
84 }
85}
86
87fn from_decode_error(error: prost::DecodeError) -> crate::status::Status {
88 crate::status::Status::new(crate::status::Code::Internal, error.to_string())
91}