use bytes::{Bytes, BytesMut};
pub struct LengthDecoder {
remaining: u64,
}
pub struct Error;
impl LengthDecoder {
pub fn new(length: u64) -> Self {
LengthDecoder { remaining: length }
}
}
impl super::Decoder for LengthDecoder {
type Item = Bytes; type Error = Error;
fn decode(&mut self, bytes: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
debug_assert!(!bytes.is_empty(), "decode should always be called with bytes");
if self.remaining == 0 {
Ok(Some(Bytes::new()))
} else {
let to_read = bytes.len().min(self.remaining as usize);
self.remaining -= to_read as u64;
Ok(Some(bytes.split_to(to_read).freeze()))
}
}
}