use bytes::Bytes;
use buffa::{Message, MessageView, OwnedView};
use super::{Codec, CodecError, CodecFor};
const NAME: &str = "proto";
#[derive(Debug, Clone, Copy, Default)]
pub struct ProtoCodec;
impl Codec for ProtoCodec {
fn name(&self) -> &str {
NAME
}
fn is_binary(&self) -> bool {
true
}
}
impl<M: Message> CodecFor<M> for ProtoCodec {
fn marshal(&self, message: &M) -> Result<Bytes, CodecError> {
Ok(message.encode_to_bytes())
}
fn unmarshal(&self, data: Bytes) -> Result<M, CodecError> {
M::decode_from_slice(&data).map_err(|e| CodecError::decode(NAME, e.to_string()))
}
fn marshal_stable(&self, message: &M) -> Result<Bytes, CodecError> {
Ok(message.encode_to_bytes())
}
fn marshal_append(&self, buf: &mut Vec<u8>, message: &M) -> Result<(), CodecError> {
message.encode(buf);
Ok(())
}
}
impl ProtoCodec {
pub fn unmarshal_owned_view<V>(&self, bytes: Bytes) -> Result<OwnedView<V>, CodecError>
where
V: MessageView<'static>,
{
OwnedView::<V>::decode(bytes).map_err(|e| CodecError::decode(NAME, e.to_string()))
}
}