apache_dubbo/triple/codec/
serde_codec.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use 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}