use std::io::{self, Read, Write};
use crate::{
DecoderDictionary, DecoderOptions, EncoderDictionary, EncoderOptions, Error, StreamingDecoder,
StreamingEncoder,
};
const READ_CHUNK: usize = StreamingDecoder::RECOMMENDED_INPUT_SIZE;
const READ_CHUNK_INITIAL: usize = 32768;
impl From<Error> for io::Error {
fn from(error: Error) -> Self {
io::Error::new(io::ErrorKind::InvalidData, error)
}
}
pub struct Writer<'a, W: Write> {
inner: Option<W>,
encoder: StreamingEncoder<'a>,
}
impl<W: Write> Writer<'static, W> {
pub fn new(inner: W) -> io::Result<Self> {
Self::with_options(inner, EncoderOptions::default())
}
pub fn with_options(inner: W, options: EncoderOptions) -> io::Result<Self> {
Ok(Self {
inner: Some(inner),
encoder: StreamingEncoder::new(options)?,
})
}
}
impl<'a, W: Write> Writer<'a, W> {
pub fn with_prepared_dict(
inner: W,
dictionary: &EncoderDictionary<'a>,
options: EncoderOptions,
) -> io::Result<Self> {
Ok(Self {
inner: Some(inner),
encoder: StreamingEncoder::with_prepared_dict(dictionary, options)?,
})
}
pub fn get_ref(&self) -> &W {
self.inner.as_ref().expect("inner writer taken by finish")
}
pub fn finish(mut self) -> io::Result<W> {
self.encoder.finish()?;
self.drain()?;
let mut inner = self.inner.take().expect("inner writer taken by finish");
inner.flush()?;
Ok(inner)
}
fn drain(&mut self) -> io::Result<()> {
let pending = self.encoder.pending_output_len();
if pending == 0 {
return Ok(());
}
let inner = self.inner.as_mut().expect("inner writer taken by finish");
let result = inner.write_all(self.encoder.pending_output());
self.encoder.consume_output(pending);
result
}
}
impl<W: Write> Write for Writer<'_, W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.encoder.push(buf)?;
self.drain()?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.encoder.flush()?;
self.drain()?;
self.inner
.as_mut()
.expect("inner writer taken by finish")
.flush()
}
}
impl<W: Write> Drop for Writer<'_, W> {
fn drop(&mut self) {
if self.inner.is_some() {
let _ = self.drain();
}
}
}
impl<W: Write> std::fmt::Debug for Writer<'_, W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Writer")
.field("finished", &self.inner.is_none())
.field("pending_output_len", &self.encoder.pending_output_len())
.finish_non_exhaustive()
}
}
pub struct Reader<'a, R: Read> {
inner: R,
decoder: StreamingDecoder<'a>,
chunk: Vec<u8>,
input_done: bool,
finished: bool,
}
impl<R: Read> Reader<'static, R> {
pub fn new(inner: R) -> Self {
Self::with_options(inner, DecoderOptions::default())
}
pub fn with_options(inner: R, options: DecoderOptions) -> Self {
Self {
inner,
decoder: StreamingDecoder::new(options),
chunk: Vec::new(),
input_done: false,
finished: false,
}
}
}
impl<'a, R: Read> Reader<'a, R> {
pub fn with_prepared_dict(
inner: R,
dictionary: &DecoderDictionary<'a>,
options: DecoderOptions,
) -> Self {
Self {
inner,
decoder: StreamingDecoder::with_prepared_dict(dictionary, options),
chunk: Vec::new(),
input_done: false,
finished: false,
}
}
pub fn get_ref(&self) -> &R {
&self.inner
}
pub fn into_inner(self) -> R {
self.inner
}
pub fn into_inner_with_remainder(self) -> (R, Vec<u8>) {
let remainder = self.decoder.unconsumed_input().to_vec();
(self.inner, remainder)
}
}
impl<R: Read> Read for Reader<'_, R> {
fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
if dst.is_empty() {
return Ok(0);
}
loop {
let produced = self.decoder.read(dst);
if produced != 0 {
return Ok(produced);
}
if self.finished {
return Ok(0);
}
if self.input_done {
self.decoder.finish()?;
self.finished = true;
continue;
}
if self.refill()? == 0 {
self.input_done = true;
}
}
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
let start = buf.len();
loop {
let pending = self.decoder.pending_output_len();
if pending != 0 {
buf.extend_from_slice(self.decoder.pending_output());
self.decoder.consume_output(pending);
continue;
}
if self.finished {
return Ok(buf.len() - start);
}
if self.input_done {
self.decoder.finish()?;
self.finished = true;
continue;
}
match self.refill() {
Ok(0) => self.input_done = true,
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
Err(err) => return Err(err),
}
}
}
}
impl<R: Read> Reader<'_, R> {
fn refill(&mut self) -> io::Result<usize> {
if self.chunk.is_empty() {
self.chunk = vec![0u8; READ_CHUNK_INITIAL];
}
let read = self.inner.read(&mut self.chunk)?;
if read != 0 {
self.decoder.push(&self.chunk[..read])?;
}
if read == self.chunk.len() && read < READ_CHUNK {
self.chunk = vec![0u8; READ_CHUNK];
}
Ok(read)
}
}
impl<R: Read> std::fmt::Debug for Reader<'_, R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Reader")
.field("input_done", &self.input_done)
.field("finished", &self.finished)
.field("pending_output_len", &self.decoder.pending_output_len())
.finish_non_exhaustive()
}
}