apache_dubbo/triple/codec/
serde_codec.rs1use std::marker::PhantomData;
19
20use bytes::{Buf, BufMut};
21use serde::{Deserialize, Serialize};
22
23use super::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
24
25#[derive(Debug)]
26pub struct SerdeCodec<T, U> {
27 _pd: PhantomData<(T, U)>,
28}
29
30impl<T, U> Default for SerdeCodec<T, U> {
31 fn default() -> Self {
32 Self { _pd: PhantomData }
33 }
34}
35
36impl<'a, T, U> Codec for SerdeCodec<T, U>
37where
38 T: Serialize + Send + 'static,
39 U: Deserialize<'a> + Send + 'static,
40{
41 type Encode = T;
42
43 type Decode = U;
44
45 type Encoder = SerdeEncoder<T>;
46
47 type Decoder = SerdeDecoder<U>;
48
49 fn encoder(&mut self) -> Self::Encoder {
50 SerdeEncoder(PhantomData)
51 }
52
53 fn decoder(&mut self) -> Self::Decoder {
54 SerdeDecoder(PhantomData)
55 }
56}
57
58#[derive(Debug, Clone)]
59pub struct SerdeEncoder<T>(PhantomData<T>);
60
61impl<T: Serialize> Encoder for SerdeEncoder<T> {
62 type Item = T;
63
64 type Error = crate::status::Status;
65
66 fn encode(&mut self, item: Self::Item, dst: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
67 item.serialize(&mut serde_json::Serializer::new(dst.writer()))
68 .expect("failed to searialize");
69
70 Ok(())
71 }
72}
73
74pub struct SerdeDecoder<U>(PhantomData<U>);
75
76impl<'a, U: Deserialize<'a>> Decoder for SerdeDecoder<U> {
77 type Item = U;
78
79 type Error = crate::status::Status;
80
81 fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
82 let value = src.chunk().to_owned();
83 let mut msg = vec![0u8; value.len()];
84 src.copy_to_slice(&mut msg);
85
86 let mut de = serde_json::Deserializer::from_reader(msg.reader());
87 Ok(Some(U::deserialize(&mut de).unwrap()))
88 }
89}