1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use core::{
    pin::Pin,
    task::{Context, Poll},
};
use std::io::Result;

use flate2::{Compress, Compression, FlushCompress};
use futures::{
    io::{AsyncBufRead, AsyncRead},
    ready,
};
use pin_project::unsafe_project;

/// A zlib encoder, or compressor.
///
/// This structure implements an [`AsyncRead`] interface and will read uncompressed data from an
/// underlying stream and emit a stream of compressed data.
#[unsafe_project(Unpin)]
#[derive(Debug)]
pub struct ZlibEncoder<R: AsyncBufRead> {
    #[pin]
    inner: R,
    flushing: bool,
    compress: Compress,
}

impl<R: AsyncBufRead> ZlibEncoder<R> {
    /// Creates a new encoder which will read uncompressed data from the given stream and emit a
    /// compressed stream.
    pub fn new(read: R, level: Compression) -> ZlibEncoder<R> {
        ZlibEncoder {
            inner: read,
            flushing: false,
            compress: Compress::new(level, true),
        }
    }

    /// Acquires a reference to the underlying reader that this encoder is wrapping.
    pub fn get_ref(&self) -> &R {
        &self.inner
    }

    /// Acquires a mutable reference to the underlying reader that this encoder is wrapping.
    ///
    /// Note that care must be taken to avoid tampering with the state of the reader which may
    /// otherwise confuse this encoder.
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    /// Acquires a pinned mutable reference to the underlying reader that this encoder is wrapping.
    ///
    /// Note that care must be taken to avoid tampering with the state of the reader which may
    /// otherwise confuse this encoder.
    pub fn get_pin_mut<'a>(self: Pin<&'a mut Self>) -> Pin<&'a mut R> {
        self.project().inner
    }

    /// Consumes this encoder returning the underlying reader.
    ///
    /// Note that this may discard internal state of this encoder, so care should be taken
    /// to avoid losing resources when this is called.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: AsyncBufRead> AsyncRead for ZlibEncoder<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<Result<usize>> {
        let mut this = self.project();

        loop {
            let input_buffer = ready!(this.inner.as_mut().poll_fill_buf(cx))?;
            *this.flushing = input_buffer.is_empty();

            let flush = if *this.flushing {
                FlushCompress::Finish
            } else {
                FlushCompress::None
            };

            let (prior_in, prior_out) = (this.compress.total_in(), this.compress.total_out());
            this.compress.compress(input_buffer, buf, flush)?;
            let input = this.compress.total_in() - prior_in;
            let output = this.compress.total_out() - prior_out;

            this.inner.as_mut().consume(input as usize);
            if *this.flushing || output > 0 {
                return Poll::Ready(Ok(output as usize));
            }
        }
    }
}