Skip to main content

volo_grpc/codec/
mod.rs

1//! Generic encoding and decoding.
2//!
3//! This module contains the generic `Encoder` and `Decoder` traits as well as
4//! the 'DefaultEncoder' and 'DefaultDecoder' implementations based on prost.
5
6pub mod compression;
7pub mod decode;
8pub mod encode;
9
10use std::{io, marker::PhantomData, mem::size_of};
11
12use bytes::Bytes;
13use pilota::{LinkedBytes, pb::Message};
14
15use crate::{Status, status::Code::Internal};
16
17const PREFIX_LEN: usize = size_of::<u32>() + size_of::<u8>();
18const BUFFER_SIZE: usize = 8 * 1024;
19
20/// Encoder for gRPC messages.
21pub trait Encoder {
22    /// The type that is encoded.
23    type Item;
24
25    /// The type of encoding errors.
26    ///
27    /// The type of unrecoverable frame encoding errors.
28    type Error: From<io::Error>;
29
30    /// Encodes a message into the buffer.
31    fn encode(&mut self, item: Self::Item, dst: &mut LinkedBytes) -> Result<(), Self::Error>;
32}
33
34#[derive(Debug, Clone)]
35pub struct DefaultEncoder<T>(PhantomData<T>);
36
37impl<T: Message> Encoder for DefaultEncoder<T> {
38    type Item = T;
39    type Error = Status;
40
41    fn encode(&mut self, item: Self::Item, dst: &mut LinkedBytes) -> Result<(), Self::Error> {
42        let mut ctx = pilota::pb::EncodeLengthContext::default();
43        let required_len = item.encoded_len(&mut ctx) - ctx.zero_copy_len;
44        dst.reserve(required_len);
45        item.encode(dst)
46            .map_err(|e| Status::new(Internal, e.to_string()))
47    }
48}
49
50impl<T> Default for DefaultEncoder<T> {
51    fn default() -> Self {
52        DefaultEncoder(PhantomData)
53    }
54}
55
56/// Decoder for gRPC messages.
57pub trait Decoder {
58    /// The type that is decoded.
59    type Item;
60
61    /// The type of unrecoverable frame decoding errors.
62    type Error: From<io::Error>;
63
64    /// Decode a message from the buffer.
65    fn decode(&mut self, src: Bytes) -> Result<Option<Self::Item>, Self::Error>;
66}
67
68#[derive(Debug, Clone)]
69pub struct DefaultDecoder<T>(PhantomData<fn(T)>);
70
71impl<T: Message + Default> Decoder for DefaultDecoder<T> {
72    type Item = T;
73    type Error = Status;
74
75    fn decode(&mut self, src: Bytes) -> Result<Option<Self::Item>, Self::Error> {
76        Message::decode(src)
77            .map(Some)
78            .map_err(|e| Status::new(Internal, e.to_string()))
79    }
80}
81
82impl<T> Default for DefaultDecoder<T> {
83    fn default() -> Self {
84        DefaultDecoder(PhantomData)
85    }
86}