use bytes::{Buf, BufMut, BytesMut};
use serde::Serialize;
use std::io::Cursor;
use tokio_util::codec;
use super::Message;
#[derive(Debug)]
pub struct MessagePackCodec {
}
impl MessagePackCodec {
pub fn new() -> Self {
Self {}
}
}
impl codec::Decoder for MessagePackCodec {
type Item = Message;
type Error = std::io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let mut buf = Cursor::new(&src);
match rmp_serde::from_read(&mut buf) {
Ok(value) => {
src.advance(buf.position() as usize);
Ok(Some(value))
}
Err(_) => Ok(None),
}
}
}
impl codec::Encoder<Message> for MessagePackCodec {
type Error = std::io::Error;
fn encode(&mut self, message: Message, dst: &mut BytesMut) -> Result<(), Self::Error> {
match message.serialize(&mut rmp_serde::Serializer::new(&mut dst.writer())) {
Ok(_) => Ok(()),
Err(err) => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, err)),
}
}
}