use std::io::{self, Write};
use compio_buf::{IoBuf, IoBufMut, Slice, bytes::Bytes};
use crate::framed::codec::{Decoder, Encoder};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BytesCodec;
impl BytesCodec {
pub fn new() -> Self {
Self {}
}
}
impl Default for BytesCodec {
fn default() -> Self {
Self::new()
}
}
impl<B: IoBufMut> Encoder<Bytes, B> for BytesCodec {
type Error = io::Error;
fn encode(&mut self, item: Bytes, buf: &mut B) -> Result<(), Self::Error> {
let mut writer = buf.as_writer();
writer.write_all(&item)?;
Ok(())
}
}
impl<B: IoBuf> Decoder<Bytes, B> for BytesCodec {
type Error = io::Error;
fn decode(&mut self, buf: &Slice<B>) -> Result<Bytes, Self::Error> {
let inner = buf.as_ref().to_vec();
Ok(Bytes::from(inner))
}
}