Skip to main content

eazip/
compression.rs

1use crate::io;
2use alloc::{fmt, string::String, vec::Vec};
3
4/// A compression method used in an archive.
5///
6/// The field is the value as defined by the ZIP standard.
7#[derive(Clone, Copy, PartialEq, Eq)]
8pub struct CompressionMethod(pub u16);
9
10impl fmt::Debug for CompressionMethod {
11    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12        let name = match *self {
13            Self::STORE => "store",
14            Self::DEFLATE => "deflate",
15            Self::DEFLATE64 => "deflate64",
16            Self::BZIP2 => "bzip2",
17            Self::LZMA => "lzma",
18            Self::ZSTD_DEPRECATED => "zstd (deprecated)",
19            Self::ZSTD => "zstd",
20            Self::XZ => "xz",
21            Self::AES => "aes",
22            Self(n) => return write!(f, "unknown ({n})"),
23        };
24
25        f.write_str(name)
26    }
27}
28
29impl Default for CompressionMethod {
30    fn default() -> Self {
31        if cfg!(feature = "zstd") {
32            Self::ZSTD
33        } else if cfg!(feature = "deflate") {
34            Self::DEFLATE
35        } else {
36            Self::STORE
37        }
38    }
39}
40
41impl CompressionMethod {
42    /// The compressions methods natively supported by this crate.
43    ///
44    /// Exact value varies depending the enabled features.
45    pub const SUPPORTED: &[CompressionMethod] = &[
46        Self::STORE,
47        #[cfg(feature = "deflate")]
48        Self::DEFLATE,
49        #[cfg(feature = "zstd")]
50        Self::ZSTD,
51    ];
52}
53
54impl CompressionMethod {
55    /// No compression
56    pub const STORE: Self = Self(0);
57    pub const DEFLATE: Self = Self(8);
58    pub const DEFLATE64: Self = Self(9);
59    pub const BZIP2: Self = Self(12);
60    pub const LZMA: Self = Self(14);
61    pub const ZSTD_DEPRECATED: Self = Self(20);
62    pub const ZSTD: Self = Self(93);
63    pub const XZ: Self = Self(95);
64    pub const AES: Self = Self(99);
65}
66
67#[cold]
68fn unsupported_method(method: CompressionMethod) -> io::Error {
69    io::Error::new(
70        io::ErrorKind::Unsupported,
71        alloc::format!("Unsupported compression method: {method:?}"),
72    )
73}
74
75/// An adapter to decompress a stream.
76pub struct Decompressor<R>(DecompressorImpl<R>);
77
78impl<R: io::BufRead + fmt::Debug> fmt::Debug for Decompressor<R> {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("Decompressor")
81            .field("method", &self.compression_method())
82            .field("reader", &self.get_ref())
83            .finish()
84    }
85}
86
87enum DecompressorImpl<R> {
88    Store(R),
89    #[cfg(feature = "deflate")]
90    Deflate(flate2::bufread::DeflateDecoder<R>),
91    #[cfg(feature = "zstd")]
92    Zstd(zstd::Decoder<'static, R>),
93}
94
95impl<R: io::BufRead> Decompressor<R> {
96    /// Creates a new `Decompressor`.
97    ///
98    /// Compression methods unsupported by this crate will cause an error.
99    pub fn new(reader: R, method: CompressionMethod) -> io::Result<Self> {
100        let inner = match method {
101            CompressionMethod::STORE => DecompressorImpl::Store(reader),
102            #[cfg(feature = "deflate")]
103            CompressionMethod::DEFLATE => {
104                DecompressorImpl::Deflate(flate2::bufread::DeflateDecoder::new(reader))
105            }
106            #[cfg(feature = "zstd")]
107            CompressionMethod::ZSTD => DecompressorImpl::Zstd(zstd::Decoder::with_buffer(reader)?),
108            _ => return Err(unsupported_method(method)),
109        };
110
111        Ok(Self(inner))
112    }
113
114    /// Returns the compression method used by this decompressor
115    pub fn compression_method(&self) -> CompressionMethod {
116        match self.0 {
117            DecompressorImpl::Store(_) => CompressionMethod::STORE,
118            #[cfg(feature = "deflate")]
119            DecompressorImpl::Deflate(_) => CompressionMethod::DEFLATE,
120            #[cfg(feature = "zstd")]
121            DecompressorImpl::Zstd(_) => CompressionMethod::ZSTD,
122        }
123    }
124
125    /// Gets a shared reference to the underlying reader.
126    pub fn get_ref(&self) -> &R {
127        match &self.0 {
128            DecompressorImpl::Store(r) => r,
129            #[cfg(feature = "deflate")]
130            DecompressorImpl::Deflate(r) => r.get_ref(),
131            #[cfg(feature = "zstd")]
132            DecompressorImpl::Zstd(r) => r.get_ref(),
133        }
134    }
135
136    /// Gets a mutable reference to the underlying reader.
137    ///
138    /// It is inadvisable to directly read from the underlying reader.
139    pub fn get_mut(&mut self) -> &mut R {
140        match &mut self.0 {
141            DecompressorImpl::Store(r) => r,
142            #[cfg(feature = "deflate")]
143            DecompressorImpl::Deflate(r) => r.get_mut(),
144            #[cfg(feature = "zstd")]
145            DecompressorImpl::Zstd(r) => r.get_mut(),
146        }
147    }
148}
149
150impl<R: io::BufRead> io::Read for Decompressor<R> {
151    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
152        match &mut self.0 {
153            DecompressorImpl::Store(r) => r.read(buf),
154            #[cfg(feature = "deflate")]
155            DecompressorImpl::Deflate(r) => r.read(buf),
156            #[cfg(feature = "zstd")]
157            DecompressorImpl::Zstd(r) => r.read(buf),
158        }
159    }
160
161    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
162        match &mut self.0 {
163            DecompressorImpl::Store(r) => r.read_to_end(buf),
164            #[cfg(feature = "deflate")]
165            DecompressorImpl::Deflate(r) => r.read_to_end(buf),
166            #[cfg(feature = "zstd")]
167            DecompressorImpl::Zstd(r) => r.read_to_end(buf),
168        }
169    }
170
171    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
172        match &mut self.0 {
173            DecompressorImpl::Store(r) => r.read_to_string(buf),
174            #[cfg(feature = "deflate")]
175            DecompressorImpl::Deflate(r) => r.read_to_string(buf),
176            #[cfg(feature = "zstd")]
177            DecompressorImpl::Zstd(r) => r.read_to_string(buf),
178        }
179    }
180}
181
182/// An adapter to compress a stream.
183pub struct Compressor<W: io::Write>(CompressorImpl<W>);
184
185impl<W: io::Write + fmt::Debug> fmt::Debug for Compressor<W> {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        f.debug_struct("Compressor")
188            .field("method", &self.compression_method())
189            .field("writer", &self.get_ref())
190            .finish()
191    }
192}
193
194enum CompressorImpl<W: io::Write> {
195    Store(W),
196    #[cfg(feature = "deflate")]
197    Deflate(flate2::write::DeflateEncoder<W>),
198    #[cfg(feature = "zstd")]
199    Zstd(zstd::Encoder<'static, W>),
200}
201
202impl<W: io::Write> Compressor<W> {
203    /// Creates a new `Compressor`.
204    ///
205    /// The `level` parameter signification depends on the method used. `None`
206    /// always means "default level" and is always supported.
207    ///
208    /// Compression methods unsupported by this crate will cause an error.
209    pub fn new(writer: W, method: CompressionMethod, level: Option<i32>) -> io::Result<Self> {
210        // Avoid the "unused" warning if not using the default features
211        let _ = level;
212
213        let inner = match method {
214            CompressionMethod::STORE => CompressorImpl::Store(writer),
215            #[cfg(feature = "deflate")]
216            CompressionMethod::DEFLATE => {
217                let level = match level {
218                    Some(level) => flate2::Compression::new(level as _),
219                    None => flate2::Compression::default(),
220                };
221
222                CompressorImpl::Deflate(flate2::write::DeflateEncoder::new(writer, level))
223            }
224            #[cfg(feature = "zstd")]
225            CompressionMethod::ZSTD => {
226                let level = level.unwrap_or(0);
227                CompressorImpl::Zstd(zstd::Encoder::new(writer, level)?)
228            }
229            _ => return Err(unsupported_method(method)),
230        };
231
232        Ok(Self(inner))
233    }
234
235    /// Returns the compression method used by this compressor
236    pub fn compression_method(&self) -> CompressionMethod {
237        match self.0 {
238            CompressorImpl::Store(_) => CompressionMethod::STORE,
239            #[cfg(feature = "deflate")]
240            CompressorImpl::Deflate(_) => CompressionMethod::DEFLATE,
241            #[cfg(feature = "zstd")]
242            CompressorImpl::Zstd(_) => CompressionMethod::ZSTD,
243        }
244    }
245
246    /// Gets a shared reference to the underlying writer.
247    pub fn get_ref(&self) -> &W {
248        match &self.0 {
249            CompressorImpl::Store(w) => w,
250            #[cfg(feature = "deflate")]
251            CompressorImpl::Deflate(w) => w.get_ref(),
252            #[cfg(feature = "zstd")]
253            CompressorImpl::Zstd(w) => w.get_ref(),
254        }
255    }
256
257    /// Gets a mutable reference to the underlying writer.
258    ///
259    /// It is inadvisable to directly write to the underlying writer.
260    pub fn get_mut(&mut self) -> &mut W {
261        match &mut self.0 {
262            CompressorImpl::Store(w) => w,
263            #[cfg(feature = "deflate")]
264            CompressorImpl::Deflate(w) => w.get_mut(),
265            #[cfg(feature = "zstd")]
266            CompressorImpl::Zstd(w) => w.get_mut(),
267        }
268    }
269
270    /// Attempts to finish the stream.
271    ///
272    /// You must finish the stream when you're done writing.
273    pub fn do_finish(&mut self) -> io::Result<()> {
274        match &mut self.0 {
275            CompressorImpl::Store(_) => Ok(()),
276            #[cfg(feature = "deflate")]
277            CompressorImpl::Deflate(w) => w.try_finish(),
278            #[cfg(feature = "zstd")]
279            CompressorImpl::Zstd(w) => w.do_finish(),
280        }
281    }
282
283    /// Finishes the stream and get the writer back.
284    ///
285    /// You must finish the stream when you're done writing.
286    pub fn finish(self) -> io::Result<W> {
287        match self.0 {
288            CompressorImpl::Store(w) => Ok(w),
289            #[cfg(feature = "deflate")]
290            CompressorImpl::Deflate(w) => w.finish(),
291            #[cfg(feature = "zstd")]
292            CompressorImpl::Zstd(w) => w.finish(),
293        }
294    }
295}
296
297impl<W: io::Write> io::Write for Compressor<W> {
298    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
299        match &mut self.0 {
300            CompressorImpl::Store(w) => w.write(buf),
301            #[cfg(feature = "deflate")]
302            CompressorImpl::Deflate(w) => w.write(buf),
303            #[cfg(feature = "zstd")]
304            CompressorImpl::Zstd(w) => w.write(buf),
305        }
306    }
307
308    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
309        match &mut self.0 {
310            CompressorImpl::Store(w) => w.write_all(buf),
311            #[cfg(feature = "deflate")]
312            CompressorImpl::Deflate(w) => w.write_all(buf),
313            #[cfg(feature = "zstd")]
314            CompressorImpl::Zstd(w) => w.write_all(buf),
315        }
316    }
317
318    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
319        match &mut self.0 {
320            CompressorImpl::Store(w) => w.write_vectored(bufs),
321            #[cfg(feature = "deflate")]
322            CompressorImpl::Deflate(w) => w.write_vectored(bufs),
323            #[cfg(feature = "zstd")]
324            CompressorImpl::Zstd(w) => w.write_vectored(bufs),
325        }
326    }
327
328    fn flush(&mut self) -> io::Result<()> {
329        match &mut self.0 {
330            CompressorImpl::Store(w) => w.flush(),
331            #[cfg(feature = "deflate")]
332            CompressorImpl::Deflate(w) => w.flush(),
333            #[cfg(feature = "zstd")]
334            CompressorImpl::Zstd(w) => w.flush(),
335        }
336    }
337}