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