Skip to main content

zip/
compression.rs

1//! Possible ZIP compression methods.
2
3use core::fmt;
4use std::{fmt::Debug, io};
5
6#[allow(deprecated)]
7/// Identifies the storage format used to compress a file within a ZIP archive.
8///
9/// Each file's compression method is stored alongside it, allowing the
10/// contents to be read without context.
11///
12/// When creating ZIP files, you may choose the method to use with
13/// [`crate::write::FileOptions::compression_method`]
14#[derive(Copy, Clone, PartialEq, Eq, Debug)]
15#[cfg_attr(feature = "_arbitrary", derive(arbitrary::Arbitrary))]
16#[non_exhaustive]
17pub enum CompressionMethod {
18    /// Store the file as is
19    Stored,
20    /// Compress the file using Deflate
21    #[cfg(feature = "_deflate-any")]
22    Deflated,
23    /// Compress the file using Deflate64.
24    /// Decoding deflate64 is supported but encoding deflate64 is not supported.
25    #[cfg(feature = "deflate64")]
26    Deflate64,
27    /// Compress the file using BZIP2
28    #[cfg(feature = "_bzip2_any")]
29    Bzip2,
30    /// Encrypted using AES.
31    ///
32    /// The actual compression method has to be taken from the AES extra data field
33    /// or from `ZipFileData`.
34    #[cfg(feature = "aes-crypto")]
35    Aes,
36    /// Compress the file using `ZStandard`
37    #[cfg(feature = "zstd")]
38    Zstd,
39    /// Compress the file using LZMA
40    #[cfg(feature = "lzma")]
41    Lzma,
42    #[cfg(feature = "legacy-zip")]
43    /// Method 1 Shrink
44    Shrink,
45    #[cfg(feature = "legacy-zip")]
46    /// Reduce (Method 2-5)
47    Reduce(u8),
48    #[cfg(feature = "legacy-zip")]
49    /// Method 6 Implode/explode
50    Implode,
51    /// Compress the file using XZ
52    #[cfg(feature = "xz")]
53    Xz,
54    /// Compress the file using `PPMd`
55    #[cfg(feature = "ppmd")]
56    Ppmd,
57    /// Unsupported compression method
58    #[cfg_attr(
59        not(any(fuzzing, feature = "_arbitrary")),
60        deprecated(since = "0.5.7", note = "use the constants instead")
61    )]
62    Unsupported(u16),
63}
64#[allow(deprecated, missing_docs)]
65/// All compression methods defined for the ZIP format
66impl CompressionMethod {
67    pub const STORE: Self = CompressionMethod::Stored;
68    #[cfg(feature = "legacy-zip")]
69    pub const SHRINK: Self = CompressionMethod::Shrink;
70    #[cfg(not(feature = "legacy-zip"))]
71    /// Legacy compression method (enable feature `legacy-zip` to get support)
72    pub const SHRINK: Self = CompressionMethod::Unsupported(1);
73    #[cfg(feature = "legacy-zip")]
74    /// Legacy compression method
75    pub const REDUCE_1: Self = CompressionMethod::Reduce(1);
76    #[cfg(not(feature = "legacy-zip"))]
77    /// Legacy compression method (enable feature `legacy-zip` to get support)
78    pub const REDUCE_1: Self = CompressionMethod::Unsupported(2);
79    #[cfg(feature = "legacy-zip")]
80    /// Legacy compression method
81    pub const REDUCE_2: Self = CompressionMethod::Reduce(2);
82    #[cfg(not(feature = "legacy-zip"))]
83    /// Legacy compression method (enable feature `legacy-zip` to get support)
84    pub const REDUCE_2: Self = CompressionMethod::Unsupported(3);
85    #[cfg(feature = "legacy-zip")]
86    /// Legacy compression method
87    pub const REDUCE_3: Self = CompressionMethod::Reduce(3);
88    #[cfg(not(feature = "legacy-zip"))]
89    /// Legacy compression method (enable feature `legacy-zip` to get support)
90    pub const REDUCE_3: Self = CompressionMethod::Unsupported(4);
91    #[cfg(feature = "legacy-zip")]
92    /// Legacy compression method
93    pub const REDUCE_4: Self = CompressionMethod::Reduce(4);
94    #[cfg(not(feature = "legacy-zip"))]
95    /// Legacy compression method (enable feature `legacy-zip` to get support)
96    pub const REDUCE_4: Self = CompressionMethod::Unsupported(5);
97    #[cfg(feature = "legacy-zip")]
98    /// Legacy compression method
99    pub const IMPLODE: Self = CompressionMethod::Implode;
100    #[cfg(not(feature = "legacy-zip"))]
101    /// Legacy compression method (enable feature `legacy-zip` to get support)
102    pub const IMPLODE: Self = CompressionMethod::Unsupported(6);
103    #[cfg(feature = "_deflate-any")]
104    pub const DEFLATE: Self = CompressionMethod::Deflated;
105    #[cfg(not(feature = "_deflate-any"))]
106    pub const DEFLATE: Self = CompressionMethod::Unsupported(8);
107    #[cfg(feature = "deflate64")]
108    pub const DEFLATE64: Self = CompressionMethod::Deflate64;
109    #[cfg(not(feature = "deflate64"))]
110    pub const DEFLATE64: Self = CompressionMethod::Unsupported(9);
111    pub const PKWARE_IMPLODE: Self = CompressionMethod::Unsupported(10);
112    #[cfg(feature = "_bzip2_any")]
113    pub const BZIP2: Self = CompressionMethod::Bzip2;
114    #[cfg(not(feature = "_bzip2_any"))]
115    pub const BZIP2: Self = CompressionMethod::Unsupported(12);
116    #[cfg(not(feature = "lzma"))]
117    pub const LZMA: Self = CompressionMethod::Unsupported(14);
118    #[cfg(feature = "lzma")]
119    pub const LZMA: Self = CompressionMethod::Lzma;
120    pub const IBM_ZOS_CMPSC: Self = CompressionMethod::Unsupported(16);
121    pub const IBM_TERSE: Self = CompressionMethod::Unsupported(18);
122    pub const ZSTD_DEPRECATED: Self = CompressionMethod::Unsupported(20);
123    #[cfg(feature = "zstd")]
124    pub const ZSTD: Self = CompressionMethod::Zstd;
125    #[cfg(not(feature = "zstd"))]
126    pub const ZSTD: Self = CompressionMethod::Unsupported(93);
127    pub const MP3: Self = CompressionMethod::Unsupported(94);
128    #[cfg(feature = "xz")]
129    pub const XZ: Self = CompressionMethod::Xz;
130    #[cfg(not(feature = "xz"))]
131    pub const XZ: Self = CompressionMethod::Unsupported(95);
132    pub const JPEG: Self = CompressionMethod::Unsupported(96);
133    pub const WAVPACK: Self = CompressionMethod::Unsupported(97);
134    #[cfg(feature = "ppmd")]
135    pub const PPMD: Self = CompressionMethod::Ppmd;
136    #[cfg(not(feature = "ppmd"))]
137    pub const PPMD: Self = CompressionMethod::Unsupported(98);
138    #[cfg(feature = "aes-crypto")]
139    pub const AES: Self = CompressionMethod::Aes;
140
141    // E.4 The compression method field (section 4.4.5) is set to 99
142    // to indicate a file has been encrypted using this method.
143    #[cfg(not(feature = "aes-crypto"))]
144    pub const AES: Self = CompressionMethod::Unsupported(99);
145
146    #[cfg(feature = "_deflate-any")]
147    pub const DEFAULT: Self = CompressionMethod::Deflated;
148
149    #[cfg(all(not(feature = "_deflate-any"), feature = "_bzip2_any"))]
150    pub const DEFAULT: Self = CompressionMethod::Bzip2;
151
152    #[cfg(all(not(feature = "_deflate-any"), not(feature = "_bzip2_any")))]
153    pub const DEFAULT: Self = CompressionMethod::Stored;
154}
155impl CompressionMethod {
156    /// Convert the compression method (as `u16`) to a name
157    #[must_use]
158    pub const fn name_from_u16(val: u16) -> &'static str {
159        match val {
160            0 => "Stored",
161            1 => "Shrink",
162            2 => "Reduce(1)",
163            3 => "Reduce(2)",
164            4 => "Reduce(3)",
165            5 => "Reduce(4)",
166            6 => "Implode",
167            8 => "Deflated",
168            9 => "Deflate64",
169            12 => "Bzip2",
170            14 => "Lzma",
171            95 => "Xz",
172            93 => "Zstd",
173            98 => "Ppmd",
174            99 => "Aes",
175            _ => "Unknown",
176        }
177    }
178
179    pub(crate) const fn parse_from_u16(val: u16) -> Self {
180        match val {
181            0 => CompressionMethod::Stored,
182            #[cfg(feature = "legacy-zip")]
183            1 => CompressionMethod::Shrink,
184            #[cfg(feature = "legacy-zip")]
185            2 => CompressionMethod::Reduce(1),
186            #[cfg(feature = "legacy-zip")]
187            3 => CompressionMethod::Reduce(2),
188            #[cfg(feature = "legacy-zip")]
189            4 => CompressionMethod::Reduce(3),
190            #[cfg(feature = "legacy-zip")]
191            5 => CompressionMethod::Reduce(4),
192            #[cfg(feature = "legacy-zip")]
193            6 => CompressionMethod::Implode,
194            #[cfg(feature = "_deflate-any")]
195            8 => CompressionMethod::Deflated,
196            #[cfg(feature = "deflate64")]
197            9 => CompressionMethod::Deflate64,
198            #[cfg(feature = "_bzip2_any")]
199            12 => CompressionMethod::Bzip2,
200            #[cfg(feature = "lzma")]
201            14 => CompressionMethod::Lzma,
202            #[cfg(feature = "xz")]
203            95 => CompressionMethod::Xz,
204            #[cfg(feature = "zstd")]
205            93 => CompressionMethod::Zstd,
206            #[cfg(feature = "ppmd")]
207            98 => CompressionMethod::Ppmd,
208            #[cfg(feature = "aes-crypto")]
209            99 => CompressionMethod::Aes,
210            #[allow(deprecated)]
211            v => CompressionMethod::Unsupported(v),
212        }
213    }
214
215    /// Converts a u16 to its corresponding `CompressionMethod`
216    #[deprecated(
217        since = "0.5.7",
218        note = "use a constant to construct a compression method"
219    )]
220    #[must_use]
221    pub const fn from_u16(val: u16) -> CompressionMethod {
222        Self::parse_from_u16(val)
223    }
224
225    pub(crate) const fn serialize_to_u16(self) -> u16 {
226        match self {
227            CompressionMethod::Stored => 0,
228            #[cfg(feature = "legacy-zip")]
229            CompressionMethod::Shrink => 1,
230            #[cfg(feature = "legacy-zip")]
231            CompressionMethod::Reduce(n) => 1 + n as u16,
232            #[cfg(feature = "legacy-zip")]
233            CompressionMethod::Implode => 6,
234
235            #[cfg(feature = "_deflate-any")]
236            CompressionMethod::Deflated => 8,
237            #[cfg(feature = "deflate64")]
238            CompressionMethod::Deflate64 => 9,
239            #[cfg(feature = "_bzip2_any")]
240            CompressionMethod::Bzip2 => 12,
241            #[cfg(feature = "zstd")]
242            CompressionMethod::Zstd => 93,
243            #[cfg(feature = "lzma")]
244            CompressionMethod::Lzma => 14,
245            #[cfg(feature = "xz")]
246            CompressionMethod::Xz => 95,
247            #[cfg(feature = "ppmd")]
248            CompressionMethod::Ppmd => 98,
249            // E.4 The compression method field (section 4.4.5) is set to 99
250            // to indicate a file has been encrypted using this method.
251            #[cfg(feature = "aes-crypto")]
252            CompressionMethod::Aes => 99,
253            #[allow(deprecated)]
254            CompressionMethod::Unsupported(v) => v,
255        }
256    }
257
258    /// Converts a `CompressionMethod` to a u16
259    #[deprecated(
260        since = "0.5.7",
261        note = "to match on other compression methods, use a constant"
262    )]
263    #[must_use]
264    pub const fn to_u16(self) -> u16 {
265        self.serialize_to_u16()
266    }
267}
268
269impl Default for CompressionMethod {
270    #[cfg(feature = "_deflate-any")]
271    fn default() -> Self {
272        CompressionMethod::Deflated
273    }
274
275    #[cfg(not(feature = "_deflate-any"))]
276    fn default() -> Self {
277        CompressionMethod::Stored
278    }
279}
280
281impl fmt::Display for CompressionMethod {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        // Just duplicate what the Debug format looks like, i.e, the enum key:
284        let method_u16 = self.serialize_to_u16();
285        let name = Self::name_from_u16(method_u16);
286        write!(f, "{name}")
287    }
288}
289
290/// The compression methods which have been implemented.
291pub const SUPPORTED_COMPRESSION_METHODS: &[CompressionMethod] = &[
292    CompressionMethod::Stored,
293    #[cfg(feature = "_deflate-any")]
294    CompressionMethod::Deflated,
295    #[cfg(feature = "deflate64")]
296    CompressionMethod::Deflate64,
297    #[cfg(feature = "_bzip2_any")]
298    CompressionMethod::Bzip2,
299    #[cfg(feature = "zstd")]
300    CompressionMethod::Zstd,
301    #[cfg(feature = "xz")]
302    CompressionMethod::Xz,
303    #[cfg(feature = "ppmd")]
304    CompressionMethod::Ppmd,
305];
306
307pub(crate) enum Decompressor<R: io::BufRead> {
308    Stored(R),
309    #[cfg(feature = "deflate-flate2")]
310    Deflated(flate2::bufread::DeflateDecoder<R>),
311    #[cfg(feature = "deflate64")]
312    Deflate64(deflate64::Deflate64Decoder<R>),
313    #[cfg(feature = "_bzip2_any")]
314    Bzip2(bzip2::bufread::BzDecoder<R>),
315    #[cfg(feature = "zstd")]
316    Zstd(zstd::Decoder<'static, R>),
317    #[cfg(feature = "lzma")]
318    Lzma(Lzma<R>),
319    #[cfg(feature = "legacy-zip")]
320    Shrink(crate::legacy::shrink::ShrinkDecoder<R>),
321    #[cfg(feature = "legacy-zip")]
322    Reduce(crate::legacy::reduce::ReduceDecoder<R>),
323    #[cfg(feature = "legacy-zip")]
324    Implode(crate::legacy::implode::ImplodeDecoder<R>),
325    #[cfg(feature = "xz")]
326    Xz(Box<lzma_rust2::XzReader<R>>),
327    #[cfg(feature = "ppmd")]
328    Ppmd(Ppmd<R>),
329}
330
331impl<R: io::BufRead> Debug for Decompressor<R> {
332    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
333        match self {
334            Self::Stored(_) => write!(f, "StoredDecompressor"),
335            #[cfg(feature = "deflate-flate2")]
336            Self::Deflated(_) => write!(f, "DeflatedDecompressor"),
337            #[cfg(feature = "deflate64")]
338            Self::Deflate64(_) => write!(f, "Deflate64Decompressor"),
339            #[cfg(feature = "_bzip2_any")]
340            Self::Bzip2(_) => write!(f, "Bzip2Decompressor"),
341            #[cfg(feature = "zstd")]
342            Self::Zstd(_) => write!(f, "ZstdDecompressor"),
343            #[cfg(feature = "lzma")]
344            Self::Lzma(_) => write!(f, "LzmaDecompressor"),
345            #[cfg(feature = "legacy-zip")]
346            Self::Shrink(_) => write!(f, "ShrinkDecompressor"),
347            #[cfg(feature = "legacy-zip")]
348            Self::Reduce(_) => write!(f, "ReduceDecompressor"),
349            #[cfg(feature = "legacy-zip")]
350            Self::Implode(_) => write!(f, "ImplodeDecompressor"),
351            #[cfg(feature = "xz")]
352            Self::Xz(_) => write!(f, "XzDecompressor"),
353            #[cfg(feature = "ppmd")]
354            Self::Ppmd(_) => write!(f, "PpmdDecompressor"),
355        }
356    }
357}
358
359#[cfg(feature = "lzma")]
360pub(crate) enum Lzma<R: io::BufRead> {
361    Uninitialized {
362        reader: Option<R>,
363        uncompressed_size: u64,
364    },
365    Initialized(Box<lzma_rust2::LzmaReader<R>>),
366}
367
368#[cfg(feature = "ppmd")]
369pub(crate) enum Ppmd<R: io::BufRead> {
370    Uninitialized(Option<R>),
371    Initialized(Box<ppmd_rust::Ppmd8Decoder<R>>),
372}
373
374impl<R: io::BufRead> io::Read for Decompressor<R> {
375    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
376        match self {
377            Decompressor::Stored(r) => r.read(buf),
378            #[cfg(feature = "deflate-flate2")]
379            Decompressor::Deflated(r) => r.read(buf),
380            #[cfg(feature = "deflate64")]
381            Decompressor::Deflate64(r) => r.read(buf),
382            #[cfg(feature = "_bzip2_any")]
383            Decompressor::Bzip2(r) => r.read(buf),
384            #[cfg(feature = "zstd")]
385            Decompressor::Zstd(r) => r.read(buf),
386            #[cfg(feature = "lzma")]
387            Decompressor::Lzma(r) => match r {
388                Lzma::Uninitialized {
389                    reader,
390                    uncompressed_size,
391                } => {
392                    let mut reader = reader.take().ok_or_else(|| {
393                        io::Error::other("Reader was not set while reading LZMA data")
394                    })?;
395
396                    // 5.8.8.1 LZMA Version Information & 5.8.8.2 LZMA Properties Size
397                    let mut header = [0; 4];
398                    reader.read_exact(&mut header)?;
399                    let _version_information =
400                        u16::from_le_bytes(header[0..2].try_into().map_err(|e| {
401                            std::io::Error::other(format!("Cannot transform header to u16: {e}"))
402                        })?);
403                    let properties_size =
404                        u16::from_le_bytes(header[2..4].try_into().map_err(|e| {
405                            std::io::Error::other(format!("Cannot transform header to u16: {e}"))
406                        })?);
407                    if properties_size != 5 {
408                        return Err(io::Error::new(
409                            io::ErrorKind::InvalidInput,
410                            format!("unexpected LZMA properties size of {properties_size}"),
411                        ));
412                    }
413
414                    let mut props_data = [0; 5];
415                    reader.read_exact(&mut props_data)?;
416                    let props = props_data[0];
417                    let dict_size =
418                        u32::from_le_bytes(props_data[1..5].try_into().map_err(|e| {
419                            std::io::Error::other(format!("Cannot transform header to u32: {e}"))
420                        })?);
421
422                    // We don't need to handle the end-of-stream marker here, since the LZMA reader
423                    // stops at the end-of-stream marker OR when it has decoded uncompressed_size bytes, whichever comes first.
424                    let mut decompressor = lzma_rust2::LzmaReader::new_with_props(
425                        reader,
426                        *uncompressed_size,
427                        props,
428                        dict_size,
429                        None,
430                    )?;
431
432                    let read = decompressor.read(buf)?;
433
434                    *r = Lzma::Initialized(Box::new(decompressor));
435
436                    Ok(read)
437                }
438                Lzma::Initialized(decompressor) => decompressor.read(buf),
439            },
440            #[cfg(feature = "xz")]
441            Decompressor::Xz(r) => r.read(buf),
442            #[cfg(feature = "ppmd")]
443            Decompressor::Ppmd(r) => match r {
444                Ppmd::Uninitialized(reader) => {
445                    let mut reader = reader.take().ok_or_else(|| {
446                        io::Error::other("Reader was not set while reading PPMd data")
447                    })?;
448
449                    let mut buffer = [0; 2];
450                    reader.read_exact(&mut buffer)?;
451                    let parameters = u16::from_le_bytes(buffer);
452
453                    let order = u32::from((parameters & 0x0F) + 1);
454                    let memory_size = 1024 * 1024 * u32::from(((parameters >> 4) & 0xFF) + 1);
455                    let restoration_method = (parameters >> 12) & 0x0F;
456
457                    let mut decompressor = ppmd_rust::Ppmd8Decoder::new(
458                        reader,
459                        order,
460                        memory_size,
461                        restoration_method.into(),
462                    )
463                    .map_err(|error| match error {
464                        ppmd_rust::Error::RangeDecoderInitialization => io::Error::new(
465                            io::ErrorKind::InvalidData,
466                            "PPMd range coder initialization failed",
467                        ),
468                        ppmd_rust::Error::InvalidParameter => {
469                            io::Error::new(io::ErrorKind::InvalidInput, "Invalid PPMd parameter")
470                        }
471                        ppmd_rust::Error::IoError(io_error) => io_error,
472                        ppmd_rust::Error::MemoryAllocation => {
473                            io::Error::new(io::ErrorKind::OutOfMemory, "Memory allocation failed")
474                        }
475                    })?;
476
477                    let read = decompressor.read(buf)?;
478
479                    *r = Ppmd::Initialized(Box::new(decompressor));
480
481                    Ok(read)
482                }
483                Ppmd::Initialized(decompressor) => decompressor.read(buf),
484            },
485            #[cfg(feature = "legacy-zip")]
486            Decompressor::Shrink(r) => r.read(buf),
487            #[cfg(feature = "legacy-zip")]
488            Decompressor::Reduce(r) => r.read(buf),
489            #[cfg(feature = "legacy-zip")]
490            Decompressor::Implode(r) => r.read(buf),
491        }
492    }
493}
494
495impl<R: io::BufRead> Decompressor<R> {
496    pub fn new(
497        reader: R,
498        compression_method: CompressionMethod,
499        #[cfg_attr(not(any(feature = "lzma", feature = "legacy-zip")), allow(unused))]
500        uncompressed_size: u64,
501        #[cfg_attr(not(feature = "legacy-zip"), allow(unused))] flags: u16,
502    ) -> crate::result::ZipResult<Self> {
503        Ok(match compression_method {
504            CompressionMethod::Stored => Decompressor::Stored(reader),
505            #[cfg(feature = "deflate-flate2")]
506            CompressionMethod::Deflated => {
507                Decompressor::Deflated(flate2::bufread::DeflateDecoder::new(reader))
508            }
509            #[cfg(feature = "deflate64")]
510            CompressionMethod::Deflate64 => {
511                Decompressor::Deflate64(deflate64::Deflate64Decoder::with_buffer(reader))
512            }
513            #[cfg(feature = "_bzip2_any")]
514            CompressionMethod::Bzip2 => Decompressor::Bzip2(bzip2::bufread::BzDecoder::new(reader)),
515            #[cfg(feature = "zstd")]
516            CompressionMethod::Zstd => Decompressor::Zstd(zstd::Decoder::with_buffer(reader)?),
517            #[cfg(feature = "lzma")]
518            CompressionMethod::Lzma => Decompressor::Lzma(Lzma::Uninitialized {
519                reader: Some(reader),
520                uncompressed_size,
521            }),
522            #[cfg(feature = "xz")]
523            CompressionMethod::Xz => {
524                Decompressor::Xz(Box::new(lzma_rust2::XzReader::new(reader, false)))
525            }
526            #[cfg(feature = "ppmd")]
527            CompressionMethod::Ppmd => Decompressor::Ppmd(Ppmd::Uninitialized(Some(reader))),
528            #[cfg(feature = "legacy-zip")]
529            CompressionMethod::Shrink => Decompressor::Shrink(
530                crate::legacy::shrink::ShrinkDecoder::new(reader, uncompressed_size),
531            ),
532            #[cfg(feature = "legacy-zip")]
533            CompressionMethod::Reduce(n) => Decompressor::Reduce(
534                crate::legacy::reduce::ReduceDecoder::new(reader, uncompressed_size, n),
535            ),
536            #[cfg(feature = "legacy-zip")]
537            CompressionMethod::Implode => Decompressor::Implode(
538                crate::legacy::implode::ImplodeDecoder::new(reader, uncompressed_size, flags),
539            ),
540            method => {
541                let method = method.serialize_to_u16();
542                return Err(crate::result::ZipError::CompressionMethodNotSupported(
543                    method,
544                ));
545            }
546        })
547    }
548
549    /// Consumes this decoder, returning the underlying reader.
550    #[allow(clippy::infallible_destructuring_match)]
551    pub fn into_inner(self) -> io::Result<R> {
552        let inner = match self {
553            Decompressor::Stored(r) => r,
554            #[cfg(feature = "deflate-flate2")]
555            Decompressor::Deflated(r) => r.into_inner(),
556            #[cfg(feature = "deflate64")]
557            Decompressor::Deflate64(r) => r.into_inner(),
558            #[cfg(feature = "_bzip2_any")]
559            Decompressor::Bzip2(r) => r.into_inner(),
560            #[cfg(feature = "zstd")]
561            Decompressor::Zstd(r) => r.finish(),
562            #[cfg(feature = "lzma")]
563            Decompressor::Lzma(r) => match r {
564                Lzma::Uninitialized { mut reader, .. } => reader
565                    .take()
566                    .ok_or_else(|| io::Error::other("Reader was not set"))?,
567                Lzma::Initialized(decoder) => decoder.into_inner(),
568            },
569            #[cfg(feature = "legacy-zip")]
570            Decompressor::Shrink(r) => r.into_inner(),
571            #[cfg(feature = "legacy-zip")]
572            Decompressor::Reduce(r) => r.into_inner(),
573            #[cfg(feature = "legacy-zip")]
574            Decompressor::Implode(r) => r.into_inner(),
575            #[cfg(feature = "xz")]
576            Decompressor::Xz(r) => r.into_inner(),
577            #[cfg(feature = "ppmd")]
578            Decompressor::Ppmd(r) => match r {
579                Ppmd::Uninitialized(mut reader) => reader
580                    .take()
581                    .ok_or_else(|| io::Error::other("Reader was not set"))?,
582                Ppmd::Initialized(decoder) => decoder.into_inner(),
583            },
584        };
585        Ok(inner)
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use super::{CompressionMethod, SUPPORTED_COMPRESSION_METHODS};
592
593    #[test]
594    fn from_eq_to() {
595        for v in 0..(u32::from(u16::MAX) + 1) {
596            let from = CompressionMethod::parse_from_u16(v as u16);
597            let to = u32::from(from.serialize_to_u16());
598            assert_eq!(v, to);
599        }
600    }
601
602    #[test]
603    fn to_eq_from() {
604        fn check_match(method: CompressionMethod) {
605            let to = method.serialize_to_u16();
606            let from = CompressionMethod::parse_from_u16(to);
607            let back = from.serialize_to_u16();
608            assert_eq!(to, back);
609        }
610
611        for &method in SUPPORTED_COMPRESSION_METHODS {
612            check_match(method);
613        }
614    }
615
616    #[test]
617    fn to_display_fmt() {
618        fn check_match(method: CompressionMethod) {
619            let debug_str = format!("{method:?}");
620            let display_str = format!("{method}");
621            assert_eq!(debug_str, display_str);
622        }
623
624        for &method in SUPPORTED_COMPRESSION_METHODS {
625            check_match(method);
626        }
627    }
628}