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