tonic/codec/
mod.rs

1//! Generic encoding and decoding.
2//!
3//! This module contains the generic `Codec`, `Encoder` and `Decoder` traits
4//! and a protobuf codec based on prost.
5
6mod buffer;
7#[cfg(feature = "compression")]
8pub(crate) mod compression;
9mod decode;
10mod encode;
11#[cfg(feature = "prost")]
12mod prost;
13
14use crate::Status;
15use std::io;
16
17pub(crate) use self::encode::{encode_client, encode_server};
18
19pub use self::buffer::{DecodeBuf, EncodeBuf};
20#[cfg(feature = "compression")]
21#[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
22pub use self::compression::{CompressionEncoding, EnabledCompressionEncodings};
23pub use self::decode::Streaming;
24#[cfg(feature = "prost")]
25#[cfg_attr(docsrs, doc(cfg(feature = "prost")))]
26pub use self::prost::ProstCodec;
27
28// 5 bytes
29const HEADER_SIZE: usize =
30    // compression flag
31    std::mem::size_of::<u8>() +
32    // data length
33    std::mem::size_of::<u32>();
34
35/// Trait that knows how to encode and decode gRPC messages.
36pub trait Codec: Default {
37    /// The encodable message.
38    type Encode: Send + 'static;
39    /// The decodable message.
40    type Decode: Send + 'static;
41
42    /// The encoder that can encode a message.
43    type Encoder: Encoder<Item = Self::Encode, Error = Status> + Send + 'static;
44    /// The encoder that can decode a message.
45    type Decoder: Decoder<Item = Self::Decode, Error = Status> + Send + 'static;
46
47    /// Fetch the encoder.
48    fn encoder(&mut self) -> Self::Encoder;
49    /// Fetch the decoder.
50    fn decoder(&mut self) -> Self::Decoder;
51}
52
53/// Encodes gRPC message types
54pub trait Encoder {
55    /// The type that is encoded.
56    type Item;
57
58    /// The type of encoding errors.
59    ///
60    /// The type of unrecoverable frame encoding errors.
61    type Error: From<io::Error>;
62
63    /// Encodes a message into the provided buffer.
64    fn encode(&mut self, item: Self::Item, dst: &mut EncodeBuf<'_>) -> Result<(), Self::Error>;
65}
66
67/// Decodes gRPC message types
68pub trait Decoder {
69    /// The type that is decoded.
70    type Item;
71
72    /// The type of unrecoverable frame decoding errors.
73    type Error: From<io::Error>;
74
75    /// Decode a message from the buffer.
76    ///
77    /// The buffer will contain exactly the bytes of a full message. There
78    /// is no need to get the length from the bytes, gRPC framing is handled
79    /// for you.
80    fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error>;
81}