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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
use std::io;
use std::fmt;

use flate2::read::DeflateDecoder;
use flate2::read::ZlibDecoder;

use super::*;

/// Decompresses the underlying `BufferedReader` using the deflate
/// algorithm.
#[derive(Debug)]
pub struct Deflate<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> {
    reader: Generic<DeflateDecoder<R>, C>,
}

assert_send_and_sync!(Deflate<R, C>
                      where R: BufferedReader<C>,
                            C: fmt::Debug);

impl <R: BufferedReader<()>> Deflate<R, ()> {
    /// Instantiates a new deflate decompression reader.
    ///
    /// `reader` is the source to wrap.
    pub fn new(reader: R) -> Self {
        Self::with_cookie(reader, ())
    }
}

impl <R: BufferedReader<C>, C: fmt::Debug + Sync + Send> Deflate<R, C> {
    /// Like [`Self::new`], but uses a cookie.
    ///
    /// The cookie can be retrieved using the [`BufferedReader::cookie_ref`] and
    /// [`BufferedReader::cookie_mut`] methods, and set using the [`BufferedReader::cookie_set`] method.
    pub fn with_cookie(reader: R, cookie: C) -> Self {
        Deflate {
            reader: Generic::with_cookie(
                DeflateDecoder::new(reader), None, cookie),
        }
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> io::Read for Deflate<R, C> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
        self.reader.read(buf)
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> fmt::Display for Deflate<R, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Deflate").finish()
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Send + Sync> BufferedReader<C>
        for Deflate<R, C> {
    fn buffer(&self) -> &[u8] {
        self.reader.buffer()
    }

    fn data(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data(amount)
    }

    fn data_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data_hard(amount)
    }

    fn data_eof(&mut self) -> Result<&[u8], io::Error> {
        self.reader.data_eof()
    }

    fn consume(&mut self, amount: usize) -> &[u8] {
        self.reader.consume(amount)
    }

    fn data_consume(&mut self, amount: usize)
                    -> Result<&[u8], io::Error> {
        self.reader.data_consume(amount)
    }

    fn data_consume_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data_consume_hard(amount)
    }

    fn read_be_u16(&mut self) -> Result<u16, io::Error> {
        self.reader.read_be_u16()
    }

    fn read_be_u32(&mut self) -> Result<u32, io::Error> {
        self.reader.read_be_u32()
    }

    fn steal(&mut self, amount: usize) -> Result<Vec<u8>, io::Error> {
        self.reader.steal(amount)
    }

    fn steal_eof(&mut self) -> Result<Vec<u8>, io::Error> {
        self.reader.steal_eof()
    }

    fn get_mut(&mut self) -> Option<&mut dyn BufferedReader<C>> {
        Some(self.reader.reader_mut().get_mut())
    }

    fn get_ref(&self) -> Option<&dyn BufferedReader<C>> {
        Some(self.reader.reader_ref().get_ref())
    }

    fn into_inner<'b>(self: Box<Self>)
            -> Option<Box<dyn BufferedReader<C> + 'b>> where Self: 'b {
        // Strip the outer box.
        Some(self.reader.into_reader().into_inner().into_boxed())
    }

    fn cookie_set(&mut self, cookie: C) -> C {
        self.reader.cookie_set(cookie)
    }

    fn cookie_ref(&self) -> &C {
        self.reader.cookie_ref()
    }

    fn cookie_mut(&mut self) -> &mut C {
        self.reader.cookie_mut()
    }
}

/// Decompresses the underlying `BufferedReader` using the zlib
/// algorithm.
pub struct Zlib<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> {
    reader: Generic<ZlibDecoder<R>, C>,
}

assert_send_and_sync!(Zlib<R, C>
                      where R: BufferedReader<C>,
                            C: fmt::Debug);

impl <R: BufferedReader<()>> Zlib<R, ()> {
    /// Instantiates a new zlib decompression reader.
    ///
    /// `reader` is the source to wrap.
    pub fn new(reader: R) -> Self {
        Self::with_cookie(reader, ())
    }
}

impl <R: BufferedReader<C>, C: fmt::Debug + Sync + Send> Zlib<R, C> {
    /// Like [`Self::new`], but uses a cookie.
    ///
    /// The cookie can be retrieved using the [`BufferedReader::cookie_ref`] and
    /// [`BufferedReader::cookie_mut`] methods, and set using the [`BufferedReader::cookie_set`] method.
    pub fn with_cookie(reader: R, cookie: C) -> Self {
        Zlib {
            reader: Generic::with_cookie(
                ZlibDecoder::new(reader), None, cookie),
        }
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> io::Read for Zlib<R, C> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
        self.reader.read(buf)
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> fmt::Display for Zlib<R, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Zlib")
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Sync + Send> fmt::Debug for Zlib<R, C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Zlib")
            .field("reader", &self.get_ref().unwrap())
            .finish()
    }
}

impl<R: BufferedReader<C>, C: fmt::Debug + Send + Sync> BufferedReader<C>
        for Zlib<R, C> {
    fn buffer(&self) -> &[u8] {
        self.reader.buffer()
    }

    fn data(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data(amount)
    }

    fn data_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data_hard(amount)
    }

    fn data_eof(&mut self) -> Result<&[u8], io::Error> {
        self.reader.data_eof()
    }

    fn consume(&mut self, amount: usize) -> &[u8] {
        self.reader.consume(amount)
    }

    fn data_consume(&mut self, amount: usize)
                    -> Result<&[u8], io::Error> {
        self.reader.data_consume(amount)
    }

    fn data_consume_hard(&mut self, amount: usize) -> Result<&[u8], io::Error> {
        self.reader.data_consume_hard(amount)
    }

    fn read_be_u16(&mut self) -> Result<u16, io::Error> {
        self.reader.read_be_u16()
    }

    fn read_be_u32(&mut self) -> Result<u32, io::Error> {
        self.reader.read_be_u32()
    }

    fn steal(&mut self, amount: usize) -> Result<Vec<u8>, io::Error> {
        self.reader.steal(amount)
    }

    fn steal_eof(&mut self) -> Result<Vec<u8>, io::Error> {
        self.reader.steal_eof()
    }

    fn get_mut(&mut self) -> Option<&mut dyn BufferedReader<C>> {
        Some(self.reader.reader_mut().get_mut())
    }

    fn get_ref(&self) -> Option<&dyn BufferedReader<C>> {
        Some(self.reader.reader_ref().get_ref())
    }

    fn into_inner<'b>(self: Box<Self>)
            -> Option<Box<dyn BufferedReader<C> + 'b>> where Self: 'b {
        // Strip the outer box.
        Some(self.reader.into_reader().into_inner().into_boxed())
    }

    fn cookie_set(&mut self, cookie: C) -> C {
        self.reader.cookie_set(cookie)
    }

    fn cookie_ref(&self) -> &C {
        self.reader.cookie_ref()
    }

    fn cookie_mut(&mut self) -> &mut C {
        self.reader.cookie_mut()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    // Test that buffer() returns the same data as data().
    #[test]
    fn buffer_test() {
        use flate2::write::DeflateEncoder;
        use flate2::Compression;
        use std::io::prelude::*;

        // Test vector.
        let size = 10 * default_buf_size();
        let mut input_raw = Vec::with_capacity(size);
        let mut v = 0u8;
        for _ in 0..size {
            input_raw.push(v);
            if v == std::u8::MAX {
                v = 0;
            } else {
                v += 1;
            }
        }

        // Compress the raw input.
        let mut input = Vec::new();
        {
            let mut encoder =
                DeflateEncoder::new(&mut input, Compression::default());
            encoder.write(&input_raw[..]).unwrap();
            encoder.try_finish().unwrap();
        }

        let mut reader = Deflate::new(
            Generic::new(&input[..], None));

        // Gather some stats to make it easier to figure out whether
        // this test is working.
        let stats_count =  2 * default_buf_size();
        let mut stats = vec![0usize; stats_count];

        for i in 0..input_raw.len() {
            let data = reader.data(default_buf_size() + 1).unwrap().to_vec();
            assert!(!data.is_empty());
            assert_eq!(data, reader.buffer());
            // And, we may as well check to make sure we read the
            // right data.
            assert_eq!(data, &input_raw[i..i+data.len()]);

            stats[cmp::min(data.len(), stats_count - 1)] += 1;

            // Consume one byte and see what happens.
            reader.consume(1);
        }

        if false {
            for i in 0..stats.len() {
                if stats[i] > 0 {
                    if i == stats.len() - 1 {
                        eprint!(">=");
                    }
                    eprintln!("{}: {}", i, stats[i]);
                }
            }
        }
    }
}