use std::io;
use crate::{
buf::{IoBuf, IoBufMut, IoBufMutExt, Slice},
io::framed::buffer::append,
};
pub trait Encoder<Item, B: IoBufMut> {
type Error: From<io::Error>;
fn encode(&mut self, item: Item, buf: &mut B) -> Result<(), Self::Error>;
}
pub trait Decoder<B: IoBuf> {
type Item;
type Error: From<io::Error>;
fn decode(&mut self, buf: &Slice<B>) -> Result<Self::Item, Self::Error>;
fn decode_eof(&mut self, buf: &Slice<B>) -> Result<Option<Self::Item>, Self::Error> {
if buf.is_empty() {
Ok(None)
} else {
self.decode(buf).map(Some)
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct BytesCodec;
impl BytesCodec {
#[inline]
pub fn new() -> Self {
Self
}
}
impl<B: IoBufMut + IoBufMutExt> Encoder<Vec<u8>, B> for BytesCodec {
type Error = io::Error;
fn encode(&mut self, item: Vec<u8>, buf: &mut B) -> Result<(), Self::Error> {
append(buf, &item)?;
Ok(())
}
}
impl<B: IoBuf> Decoder<B> for BytesCodec {
type Item = Vec<u8>;
type Error = io::Error;
fn decode(&mut self, buf: &Slice<B>) -> Result<Self::Item, Self::Error> {
Ok(buf.to_vec())
}
}