Skip to main content

grpc_core/
codec.rs

1//! Serialization contracts for individual gRPC message payloads.
2
3/// Encodes and decodes message payloads independently of gRPC wire framing.
4///
5/// A codec may retain reusable serialization state. Implementations do not need
6/// to be thread safe. Payloads exclude the five-byte gRPC frame prefix, and the
7/// transport is responsible for compression and message size limits.
8pub trait Codec {
9    /// Message type accepted by the encoder.
10    type EncodeItem: ?Sized;
11    /// Owned message type returned by the decoder.
12    type DecodeItem;
13    /// Serialization or deserialization failure.
14    type Error: std::error::Error;
15
16    /// HTTP content type identifying this serialization format.
17    const CONTENT_TYPE: &'static str;
18
19    /// Appends one serialized message to `destination`.
20    ///
21    /// The caller may reuse the buffer between messages. An implementation may
22    /// leave partially appended bytes on failure; callers must discard them.
23    ///
24    /// # Errors
25    ///
26    /// Returns an implementation-defined error when the message cannot be encoded.
27    fn encode(
28        &mut self,
29        item: &Self::EncodeItem,
30        destination: &mut Vec<u8>,
31    ) -> Result<(), Self::Error>;
32
33    /// Decodes exactly one message payload.
34    ///
35    /// # Errors
36    ///
37    /// Returns an implementation-defined error when the payload is invalid for
38    /// this codec, including unsupported trailing bytes where applicable.
39    fn decode(&mut self, payload: &[u8]) -> Result<Self::DecodeItem, Self::Error>;
40}