nui 0.0.1

Experimental neovim RPC for UI clients
Documentation
use bytes::{Buf, BufMut, BytesMut};
use serde::Serialize;
use std::io::Cursor;
use tokio_util::codec;

use super::Message;

#[derive(Debug)]
pub struct MessagePackCodec {
    // pub cursor: Cursor<&'a BytesMut>,
}

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> {
        // TODO: optimize this with raw cursor
        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)),
        }
    }
}