use std::io::{self, Error, ErrorKind, Read};
use crate::{copier::Copier, ring::RingBuf};
#[derive(Debug)]
pub struct DecodeReader<R: Read> {
nth_chunk: usize,
reader: R,
copier: Copier,
ring: RingBuf<1024>,
}
impl<R: Read> DecodeReader<R> {
pub const fn new(reader: R) -> Self {
Self {
nth_chunk: 0,
reader,
copier: Copier::new_decode(),
ring: RingBuf::new(),
}
}
}
impl<R: Read> Read for DecodeReader<R> {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
while self.ring.is_empty() {
if !self.copier.write() && self.copier.copy_encoded(&mut self.reader, self.nth_chunk)? {
if self.copier.is_empty() {
break;
}
self.copier.decode().map_err(|err| {
Error::new(ErrorKind::InvalidData, err.nth_chunk(self.nth_chunk))
})?;
self.nth_chunk += 1;
}
if self.copier.write() && self.copier.copy_to(&mut self.ring)? {
self.copier = Copier::new_decode();
}
}
self.ring.copy_to_writer(&mut buf)
}
}