73 lines
1.6 KiB
Rust
73 lines
1.6 KiB
Rust
|
|
use std::marker::PhantomData;
|
||
|
|
use tonic::codec::{Codec, Decoder, Encoder, DecodeBuf, EncodeBuf};
|
||
|
|
use bytes::{Buf, BufMut};
|
||
|
|
use roto_runtime::RotoMessage;
|
||
|
|
|
||
|
|
pub struct RotoCodec<T, U> {
|
||
|
|
_phantom: PhantomData<(T, U)>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl<T, U> Default for RotoCodec<T, U> {
|
||
|
|
fn default() -> Self {
|
||
|
|
Self {
|
||
|
|
_phantom: PhantomData,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl<T, U> Codec for RotoCodec<T, U>
|
||
|
|
where
|
||
|
|
T: RotoMessage + Send + 'static,
|
||
|
|
U: RotoMessage + Send + 'static,
|
||
|
|
{
|
||
|
|
type Encode = U;
|
||
|
|
type Decode = T;
|
||
|
|
type Encoder = RotoEncoder<U>;
|
||
|
|
type Decoder = RotoDecoder<T>;
|
||
|
|
|
||
|
|
fn encoder(&mut self) -> Self::Encoder {
|
||
|
|
RotoEncoder(PhantomData)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn decoder(&mut self) -> Self::Decoder {
|
||
|
|
RotoDecoder(PhantomData)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct RotoEncoder<U>(PhantomData<U>);
|
||
|
|
|
||
|
|
impl<U> Encoder for RotoEncoder<U>
|
||
|
|
where
|
||
|
|
U: RotoMessage,
|
||
|
|
{
|
||
|
|
type Item = U;
|
||
|
|
type Error = tonic::Status;
|
||
|
|
|
||
|
|
fn encode(&mut self, message: Self::Item, buf: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {
|
||
|
|
buf.put_slice(&message.bytes());
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
pub struct RotoDecoder<T>(PhantomData<T>);
|
||
|
|
|
||
|
|
impl<T> Decoder for RotoDecoder<T>
|
||
|
|
where
|
||
|
|
T: RotoMessage,
|
||
|
|
{
|
||
|
|
type Item = T;
|
||
|
|
type Error = tonic::Status;
|
||
|
|
|
||
|
|
fn decode(&mut self, buf: &mut DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
|
||
|
|
if buf.remaining() == 0 {
|
||
|
|
return Ok(None);
|
||
|
|
}
|
||
|
|
|
||
|
|
let bytes = buf.copy_to_bytes(buf.remaining());
|
||
|
|
match T::decode(bytes) {
|
||
|
|
Ok(msg) => Ok(Some(msg)),
|
||
|
|
Err(e) => Err(tonic::Status::internal(format!("Roto decode error: {}", e))),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|