use crate::{Decoder, Encoder};
use bytes::{Bytes, BytesMut, Buf, BufMut};
use std::io::Error;
const U64_LENGTH: usize = std::mem::size_of::<u64>();
pub struct LengthCodec;
impl Encoder for LengthCodec {
type Item = Bytes;
type Error = Error;
fn encode(&mut self, src: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
dst.reserve(U64_LENGTH + src.len());
dst.put_u64(src.len() as u64);
dst.extend_from_slice(&src);
Ok(())
}
}
impl Decoder for LengthCodec {
type Item = Bytes;
type Error = Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if src.len() < U64_LENGTH {
return Ok(None);
}
let len = src.get_u64() as usize;
if src.len() - U64_LENGTH >= len {
Ok(Some(src.split_to(len).freeze()))
} else {
Ok(None)
}
}
}