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
use std::io::Write;
use std::io;

use byteorder::{WriteBytesExt, BigEndian};

use checksum::{Adler32Checksum, RollingChecksum};
use compress::compress_data_dynamic_n;
use compress::Flush;
use deflate_state::DeflateState;
use compression_options::CompressionOptions;
use zlib::{write_zlib_header, CompressionLevel};
use std::thread;

/// A DEFLATE encoder/compressor.
///
/// A struct implementing a `Write` interface that takes unencoded data and compresses it to
/// the provided writer using DEFLATE compression.
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// use deflate::Compression;
/// use deflate::write::DeflateEncoder;
///
/// let data = b"This is some test data";
/// let mut encoder = DeflateEncoder::new(Vec::new(), Compression::Default);
/// encoder.write_all(data).unwrap();
/// let compressed_data = encoder.finish().unwrap();
/// ```
pub struct DeflateEncoder<W: Write> {
    // We use a box here to avoid putting the buffers on the stack
    // It's done here rather than in the structs themselves for now to
    // keep the data close in memory.
    // Option is used to allow us to implement `Drop` and `finish()` at the same time.
    deflate_state: Option<Box<DeflateState<W>>>,
}

impl<W: Write> DeflateEncoder<W> {
    /// Creates a new encoder using the provided compression options.
    pub fn new<O: Into<CompressionOptions>>(writer: W, options: O) -> DeflateEncoder<W> {
        DeflateEncoder { deflate_state: Some(Box::new(DeflateState::new(options.into(), writer))) }
    }

    /// Encode all pending data to the contained writer, consume this `ZlibEncoder`,
    /// and return the contained writer if writing succeeds.
    pub fn finish(mut self) -> io::Result<W> {
        self.output_all().map(|_| ())?;
        // We have to move the inner state out of the encoder, and replace it with `None`
        // to let the `DeflateEncoder` drop safely.
        let state = self.deflate_state.take();
        Ok(state.unwrap().encoder_state.writer.w)
    }

    /// Resets the encoder (except the compression options), replacing the current writer
    /// with a new one, returning the old one.
    pub fn reset(&mut self, w: W) -> io::Result<W> {
        self.output_all().map(|_| ())?;
        self.deflate_state.as_mut().unwrap().reset(w)
    }

    /// Output all pending data as if encoding is done, but without resetting anything
    fn output_all(&mut self) -> io::Result<usize> {
        compress_data_dynamic_n(&[],
                                &mut self.deflate_state.as_mut().unwrap(),
                                Flush::Finish)
    }
}

impl<W: Write> io::Write for DeflateEncoder<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        compress_data_dynamic_n(buf, &mut self.deflate_state.as_mut().unwrap(), Flush::None)
    }

    fn flush(&mut self) -> io::Result<()> {
        compress_data_dynamic_n(&[], &mut self.deflate_state.as_mut().unwrap(), Flush::Sync)
            .map(|_| ())
    }
}

impl<W: Write> Drop for DeflateEncoder<W> {
    /// When the encoder is dropped, output the rest of the data.
    ///
    /// WARNING: This may silently fail if writing fails, so using this to finish encoding
    /// for writers where writing might fail is not recommended, for that call finish() instead.
    fn drop(&mut self) {
        // Not sure if implementing drop is a good idea or not, but we follow flate2 for now.
        // We only do this if we are not panicking, to avoid a double panic.
        if self.deflate_state.is_some() && !thread::panicking() {
            let _ = self.output_all();
        }
    }
}


/// A Zlib encoder/compressor.
///
/// A struct implementing a `Write` interface that takes unencoded data and compresses it to
/// the provided writer using DEFLATE compression with Zlib headers and trailers.
///
/// # Examples
///
/// ```
/// use std::io::Write;
///
/// use deflate::Compression;
/// use deflate::write::ZlibEncoder;
///
/// let data = b"This is some test data";
/// let mut encoder = ZlibEncoder::new(Vec::new(), Compression::Default);
/// encoder.write_all(data).unwrap();
/// let compressed_data = encoder.finish().unwrap();
/// ```
pub struct ZlibEncoder<W: Write> {
    // We use a box here to avoid putting the buffers on the stack
    // It's done here rather than in the structs themselves for now to
    // keep the data close in memory.
    // Option is used to allow us to implement `Drop` and `finish()` at the same time.
    deflate_state: Option<Box<DeflateState<W>>>,
    checksum: Adler32Checksum,
    header_written: bool,
}

impl<W: Write> ZlibEncoder<W> {
    /// Create a new `ZlibEncoder` using the provided compression options.
    pub fn new<O: Into<CompressionOptions>>(writer: W, options: O) -> ZlibEncoder<W> {
        ZlibEncoder {
            deflate_state: Some(Box::new(DeflateState::new(options.into(), writer))),
            checksum: Adler32Checksum::new(),
            header_written: false,
        }
    }

    /// Output all pending data ,including the trailer(checksum) as if encoding is done,
    /// but without resetting anything.
    fn output_all(&mut self) -> io::Result<usize> {
        self.check_write_header()?;
        let n = compress_data_dynamic_n(&[],
                                        &mut self.deflate_state.as_mut().unwrap(),
                                        Flush::Finish)?;
        self.write_trailer()?;
        Ok(n)
    }

    /// Encode all pending data to the contained writer, consume this `ZlibEncoder`,
    /// and return the contained writer if writing succeeds.
    pub fn finish(mut self) -> io::Result<W> {
        self.output_all()?;
        // We have to move the inner state out of the encoder, and replace it with `None`
        // to let the `DeflateEncoder` drop safely.
        let inner = self.deflate_state.take();
        Ok(inner.unwrap().encoder_state.writer.w)
    }

    /// Resets the encoder (except the compression options), replacing the current writer
    /// with a new one, returning the old one.
    pub fn reset(&mut self, writer: W) -> io::Result<W> {
        self.check_write_header()?;
        compress_data_dynamic_n(&[],
                                &mut self.deflate_state.as_mut().unwrap(),
                                Flush::Finish)?;
        self.write_trailer()?;
        self.header_written = false;
        self.checksum = Adler32Checksum::new();
        self.deflate_state.as_mut().unwrap().reset(writer)
    }

    /// Check if a zlib header should be written.
    fn check_write_header(&mut self) -> io::Result<()> {
        if !self.header_written {
            write_zlib_header(&mut self.deflate_state.as_mut().unwrap().encoder_state.writer,
                              CompressionLevel::Default)?;
            self.header_written = true;
        }
        Ok(())
    }

    /// Write the trailer, which for zlib is the Adler32 checksum.
    fn write_trailer(&mut self) -> io::Result<()> {

        let hash = self.checksum.current_hash();

        self.deflate_state
            .as_mut()
            .unwrap()
            .encoder_state
            .writer
            .write_u32::<BigEndian>(hash)
    }
}

impl<W: Write> io::Write for ZlibEncoder<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.check_write_header()?;
        self.checksum.update_from_slice(buf);
        compress_data_dynamic_n(buf, &mut self.deflate_state.as_mut().unwrap(), Flush::None)
    }

    /// Flush the encoder.
    ///
    /// This will flush the encoder, emulating the Sync flush method from Zlib.
    /// This essentially finishes the current block, and sends an additional empty stored block to
    /// the writer.
    fn flush(&mut self) -> io::Result<()> {
        compress_data_dynamic_n(&[], &mut self.deflate_state.as_mut().unwrap(), Flush::Sync)
            .map(|_| ())
    }
}

impl<W: Write> Drop for ZlibEncoder<W> {
    /// When the encoder is dropped, output the rest of the data.
    ///
    /// WARNING: This may silently fail if writing fails, so using this to finish encoding
    /// for writers where writing might fail is not recommended, for that call finish() instead.
    fn drop(&mut self) {
        if self.deflate_state.is_some() && !thread::panicking() {
            let _ = self.output_all();
        }
    }
}


#[cfg(test)]
mod test {
    use super::*;
    use test_utils::{get_test_data, decompress_to_end, decompress_zlib};
    use compression_options::CompressionOptions;
    use std::io::Write;

    #[test]
    fn deflate_writer() {
        let data = get_test_data();
        let compressed = {
            let mut compressor = DeflateEncoder::new(Vec::with_capacity(data.len() / 3),
                                                     CompressionOptions::high());
            // Write in multiple steps to see if this works as it's supposed to.
            compressor.write(&data[0..data.len() / 2]).unwrap();
            compressor.write(&data[data.len() / 2..]).unwrap();
            compressor.finish().unwrap()
        };
        println!("writer compressed len:{}", compressed.len());
        let res = decompress_to_end(&compressed);
        assert!(res == data);
    }

    #[test]
    fn zlib_writer() {
        let data = get_test_data();
        let compressed = {
            let mut compressor = ZlibEncoder::new(Vec::with_capacity(data.len() / 3),
                                                  CompressionOptions::high());
            compressor.write(&data[0..data.len() / 2]).unwrap();
            compressor.write(&data[data.len() / 2..]).unwrap();
            compressor.finish().unwrap()
        };
        println!("writer compressed len:{}", compressed.len());
        let res = decompress_zlib(&compressed);
        assert!(res == data);
    }



    #[test]
    /// Check if the the result of compressing after resetting is the same as before.
    fn writer_reset() {
        let data = get_test_data();
        let mut compressor = DeflateEncoder::new(Vec::with_capacity(data.len() / 3),
                                                 CompressionOptions::default());
        compressor.write(&data).unwrap();
        let res1 = compressor.reset(Vec::with_capacity(data.len() / 3)).unwrap();
        compressor.write(&data).unwrap();
        let res2 = compressor.finish().unwrap();
        assert!(res1 == res2);
    }

    #[test]
    fn writer_reset_zlib() {
        let data = get_test_data();
        let mut compressor = ZlibEncoder::new(Vec::with_capacity(data.len() / 3),
                                              CompressionOptions::default());
        compressor.write(&data).unwrap();
        let res1 = compressor.reset(Vec::with_capacity(data.len() / 3)).unwrap();
        compressor.write(&data).unwrap();
        let res2 = compressor.finish().unwrap();
        assert!(res1 == res2);
    }

    #[test]
    fn writer_sync() {
        let data = get_test_data();
        let compressed = {
            let mut compressor = DeflateEncoder::new(Vec::with_capacity(data.len() / 3),
                                                     CompressionOptions::default());
            let split = data.len() / 2;
            compressor.write(&data[..split]).unwrap();
            compressor.flush().unwrap();
            compressor.write(&data[split..]).unwrap();
            compressor.finish().unwrap()
        };


        let res = decompress_to_end(&compressed);
        assert!(res == data);
    }
}