mysten_network/
codec.rs

1// Copyright (c) 2022, Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use bytes::{Buf, BufMut};
5use std::marker::PhantomData;
6use tonic::{
7    codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder},
8    Status,
9};
10
11#[derive(Debug)]
12pub struct BincodeEncoder<T>(PhantomData<T>);
13
14impl<T: serde::Serialize> Encoder for BincodeEncoder<T> {
15    type Item = T;
16    type Error = Status;
17
18    fn encode(&mut self, item: Self::Item, buf: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
19        bincode::serialize_into(buf.writer(), &item).map_err(|e| Status::internal(e.to_string()))
20    }
21}
22
23#[derive(Debug)]
24pub struct BincodeDecoder<U>(PhantomData<U>);
25
26impl<U: serde::de::DeserializeOwned> Decoder for BincodeDecoder<U> {
27    type Item = U;
28    type Error = Status;
29
30    fn decode(&mut self, buf: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
31        if !buf.has_remaining() {
32            return Ok(None);
33        }
34
35        let item: Self::Item =
36            bincode::deserialize_from(buf.reader()).map_err(|e| Status::internal(e.to_string()))?;
37        Ok(Some(item))
38    }
39}
40
41/// A [`Codec`] that implements `application/grpc+bincode` via the serde library.
42#[derive(Debug, Clone)]
43pub struct BincodeCodec<T, U>(PhantomData<(T, U)>);
44
45impl<T, U> Default for BincodeCodec<T, U> {
46    fn default() -> Self {
47        Self(PhantomData)
48    }
49}
50
51impl<T, U> Codec for BincodeCodec<T, U>
52where
53    T: serde::Serialize + Send + 'static,
54    U: serde::de::DeserializeOwned + Send + 'static,
55{
56    type Encode = T;
57    type Decode = U;
58    type Encoder = BincodeEncoder<T>;
59    type Decoder = BincodeDecoder<U>;
60
61    fn encoder(&mut self) -> Self::Encoder {
62        BincodeEncoder(PhantomData)
63    }
64
65    fn decoder(&mut self) -> Self::Decoder {
66        BincodeDecoder(PhantomData)
67    }
68}