xref: /tonic/examples/src/codec_buffers/common.rs (revision 18a2b309)
1 //! This module defines a common encoder with small buffers. This is useful
2 //! when you have many concurrent RPC's, and not a huge volume of data per
3 //! rpc normally.
4 //!
5 //! Note that you can customize your codecs per call to the code generator's
6 //! compile function. This lets you group services by their codec needs.
7 //!
8 //! While this codec demonstrates customizing the built-in Prost codec, you
9 //! can use this to implement other codecs as well, as long as they have a
10 //! Default implementation.
11 
12 use std::marker::PhantomData;
13 
14 use prost::Message;
15 use tonic::codec::{BufferSettings, Codec, ProstCodec};
16 
17 #[derive(Debug, Clone, Copy, Default)]
18 pub struct SmallBufferCodec<T, U>(PhantomData<(T, U)>);
19 
20 impl<T, U> Codec for SmallBufferCodec<T, U>
21 where
22     T: Message + Send + 'static,
23     U: Message + Default + Send + 'static,
24 {
25     type Encode = T;
26     type Decode = U;
27 
28     type Encoder = <ProstCodec<T, U> as Codec>::Encoder;
29     type Decoder = <ProstCodec<T, U> as Codec>::Decoder;
30 
encoder(&mut self) -> Self::Encoder31     fn encoder(&mut self) -> Self::Encoder {
32         // Here, we will just customize the prost codec's internal buffer settings.
33         // You can of course implement a complete Codec, Encoder, and Decoder if
34         // you wish!
35         ProstCodec::<T, U>::raw_encoder(BufferSettings::new(512, 4096))
36     }
37 
decoder(&mut self) -> Self::Decoder38     fn decoder(&mut self) -> Self::Decoder {
39         ProstCodec::<T, U>::raw_decoder(BufferSettings::new(512, 4096))
40     }
41 }
42