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
#![warn(missing_docs)]

//! `BufRead` and `Write`r detects compression algorithms from file extension.
//!
//! Supported formats:
//! * Gzip (`.gz`) by [`flate2`](https://crates.io/crates/flate2) crate
//! * LZ4 (`.lz4`) by [`lz4`](https://crates.io/crates/lz4) crate

use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Read, Result, Write};
use std::path::Path;

use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use lz4::liblz4::ContentChecksum;
use lz4::{Decoder as Lz4Decoder, Encoder as Lz4Encoder, EncoderBuilder as Lz4EncoderBuilder};

/// The [`BufRead`](https://doc.rust-lang.org/std/io/trait.BufRead.html) type reads from compressed or uncompressed file.
///
/// This reader detects compression algorithms from file name extension.
pub struct DetectReader {
    inner: Box<dyn BufRead>,
}

impl DetectReader {
    /// Open compressed or uncompressed file.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<DetectReader> {
        DetectReader::open_with_wrapper::<P, Id>(path, Id)
    }

    /// Open compressed or uncompressed file using wrapper type.
    ///
    /// [`InnerReadWrapper`](trait.InnerReadWrapper.html) is the wrapepr type's trait handles compressed byte stream.
    /// For example, the progress-counting wrapper enables you to calculate progress of loading.
    pub fn open_with_wrapper<P: AsRef<Path>, B: ReadWrapperBuilder>(
        path: P,
        builder: B,
    ) -> Result<DetectReader> {
        let path = path.as_ref();

        let f = File::open(path)?;
        let wf = builder.new_wrapped_reader(f);

        let inner: Box<dyn BufRead> = match path.extension() {
            Some(e) if e == "gz" => {
                let d = GzDecoder::new(wf);
                let br = BufReader::new(d);
                Box::new(br)
            }
            Some(e) if e == "lz4" => {
                let d = Lz4Decoder::new(wf)?;
                let br = BufReader::new(d);
                Box::new(br)
            }
            _ => {
                let br = BufReader::new(wf);
                Box::new(br)
            }
        };

        Ok(DetectReader { inner })
    }
}

impl Read for DetectReader {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        self.inner.read(buf)
    }
}

impl BufRead for DetectReader {
    fn fill_buf(&mut self) -> Result<&[u8]> {
        self.inner.fill_buf()
    }

    fn consume(&mut self, amt: usize) {
        self.inner.consume(amt)
    }
}

/// The [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) type writes to compressed or uncompressed file.
///
/// This writer detects compression algorithms from file name extension.
///
/// You must [`finalize`](struct.DetectWriter.html#method.finalize) this writer.
pub struct DetectWriter {
    inner: Box<dyn Finalize>,
    not_closed: bool,
}

impl DetectWriter {
    /// Create compressed or uncompressed file.
    pub fn create<P: AsRef<Path>>(path: P, level: Level) -> Result<DetectWriter> {
        DetectWriter::create_with_wrapper::<P, Id>(path, level, Id)
    }

    /// Create compressed or uncompressed file using wrapper type.
    ///
    /// [`InnerWriteWrapper`](trait.InnerWriteWrapper.html) is the wrapepr type's trait handles compressed byte stream.
    /// For example, the size-accumulating wrapper enables you to calculate size of compressed output.
    pub fn create_with_wrapper<P: AsRef<Path>, B: WriteWrapperBuilder>(
        path: P,
        level: Level,
        builder: B,
    ) -> Result<DetectWriter> {
        let path = path.as_ref();

        let f = File::create(path)?;
        let wf = builder.new_wrapped_writer(f);
        let w = BufWriter::new(wf);

        let inner: Box<dyn Finalize> = match path.extension() {
            Some(e) if e == "gz" => {
                let e = GzEncoder::new(w, level.into_flate2_compression());
                Box::new(e)
            }
            Some(e) if e == "lz4" => {
                let mut builder = Lz4EncoderBuilder::new();
                builder
                    .level(level.into_lz4_level()?)
                    .checksum(ContentChecksum::ChecksumEnabled);

                let e = builder.build(w)?;
                Box::new(FinalizeLz4Encoder::new(e))
            }
            _ => Box::new(w),
        };

        Ok(DetectWriter {
            inner,
            not_closed: true,
        })
    }

    /// Finalize this writer.
    ///
    /// Some encodings requires finalization.
    ///
    pub fn finalize(mut self) -> Result<()> {
        if self.not_closed {
            self.inner.finalize()?;
            self.not_closed = false;
        }
        Ok(())
    }
}

impl Write for DetectWriter {
    fn write(&mut self, bytes: &[u8]) -> Result<usize> {
        self.inner.write(bytes)
    }

    fn flush(&mut self) -> Result<()> {
        self.inner.flush()
    }
}

impl Drop for DetectWriter {
    fn drop(&mut self) {
        if self.not_closed {
            panic!("DetectWriter must be finalized. But dropped before finalization.");
        }
    }
}

/// Compression level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    /// Uncompressed
    None,
    /// Minimum compression (fastest and large)
    Minimum,
    /// Maximum compression (smallest and slow)
    Maximum,
}

impl Level {
    fn into_flate2_compression(self) -> Compression {
        match self {
            Level::None => Compression::none(),
            Level::Minimum => Compression::fast(),
            Level::Maximum => Compression::best(),
        }
    }

    fn into_lz4_level(self) -> Result<u32> {
        match self {
            Level::None => Err(Error::new(
                ErrorKind::InvalidInput,
                "LZ4 don't support non-compression mode",
            )),
            Level::Minimum => Ok(1),
            Level::Maximum => Ok(3),
        }
    }
}

/// The [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) wrapper builder.
///
/// For more information, see [`DetectReader::open_with_wrapper()`](struct.DetectReader.html#method.open_with_wrapper).
pub trait ReadWrapperBuilder {
    /// Read wrapper of `File`
    type Wrapper: 'static + Read;
    /// Create new wrapper.
    fn new_wrapped_reader(self, f: File) -> Self::Wrapper;
}

/// The [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) wrapper builder.
///
/// For more information, see [`DetectWriter::create_with_wrapper()`](struct.DetectWriter.html#method.create_with_wrapper).
pub trait WriteWrapperBuilder {
    /// Write wrapper of `File`
    type Wrapper: 'static + Write;
    /// Create new wrapper.
    fn new_wrapped_writer(self, f: File) -> Self::Wrapper;
}

#[derive(Debug, Clone, Copy)]
struct Id;

impl ReadWrapperBuilder for Id {
    type Wrapper = File;
    fn new_wrapped_reader(self, f: File) -> Self::Wrapper {
        f
    }
}

impl WriteWrapperBuilder for Id {
    type Wrapper = File;
    fn new_wrapped_writer(self, f: File) -> Self::Wrapper {
        f
    }
}

trait Finalize: Write {
    fn finalize(&mut self) -> Result<()> {
        self.flush()
    }
}

impl Finalize for File {}
impl<W: Write> Finalize for GzEncoder<W> {}
impl<W: Write> Finalize for BufWriter<W> {}

struct FinalizeLz4Encoder<W: Write>(Option<Lz4Encoder<W>>);

impl<W: Write> FinalizeLz4Encoder<W> {
    fn new(inner: Lz4Encoder<W>) -> FinalizeLz4Encoder<W> {
        FinalizeLz4Encoder(Some(inner))
    }
}

impl<W: Write> Write for FinalizeLz4Encoder<W> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        self.0
            .as_mut()
            .expect("writer already finalized")
            .write(buf)
    }

    fn flush(&mut self) -> Result<()> {
        self.0.as_mut().expect("writer already finalized").flush()
    }
}

impl<W: Write> Finalize for FinalizeLz4Encoder<W> {
    fn finalize(&mut self) -> Result<()> {
        self.flush()?;
        let enc = self.0.take().expect("writer already finalized");
        enc.finish().1
    }
}