Skip to main content

use_zip/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4//! ZIP compression method labels for `RustUse`.
5
6use core::fmt;
7
8/// Common ZIP file extension.
9pub const ZIP_EXTENSION: &str = "zip";
10
11/// ZIP compression methods.
12#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
13pub enum ZipCompressionMethod {
14    /// Stored without compression.
15    #[default]
16    Stored,
17    /// Deflate compression.
18    Deflated,
19    /// Bzip2 compression.
20    Bzip2,
21    /// Zstandard compression.
22    Zstd,
23    /// LZMA compression.
24    Lzma,
25    /// Unknown method code.
26    Unknown(u16),
27}
28
29impl ZipCompressionMethod {
30    /// Returns the ZIP method code.
31    #[must_use]
32    pub const fn code(self) -> u16 {
33        match self {
34            Self::Stored => 0,
35            Self::Deflated => 8,
36            Self::Bzip2 => 12,
37            Self::Lzma => 14,
38            Self::Zstd => 93,
39            Self::Unknown(code) => code,
40        }
41    }
42
43    /// Returns a stable lowercase label.
44    #[must_use]
45    pub const fn as_str(self) -> &'static str {
46        match self {
47            Self::Stored => "stored",
48            Self::Deflated => "deflated",
49            Self::Bzip2 => "bzip2",
50            Self::Zstd => "zstd",
51            Self::Lzma => "lzma",
52            Self::Unknown(_) => "unknown",
53        }
54    }
55
56    /// Maps a ZIP method code to a known label or preserves the unknown code.
57    #[must_use]
58    pub const fn from_code(code: u16) -> Self {
59        match code {
60            0 => Self::Stored,
61            8 => Self::Deflated,
62            12 => Self::Bzip2,
63            14 => Self::Lzma,
64            93 => Self::Zstd,
65            other => Self::Unknown(other),
66        }
67    }
68}
69
70impl fmt::Display for ZipCompressionMethod {
71    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
72        formatter.write_str(self.as_str())
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::{ZIP_EXTENSION, ZipCompressionMethod};
79
80    #[test]
81    fn maps_zip_method_codes() {
82        assert_eq!(
83            ZipCompressionMethod::from_code(0),
84            ZipCompressionMethod::Stored
85        );
86        assert_eq!(
87            ZipCompressionMethod::from_code(8),
88            ZipCompressionMethod::Deflated
89        );
90        assert_eq!(
91            ZipCompressionMethod::from_code(93),
92            ZipCompressionMethod::Zstd
93        );
94        assert_eq!(
95            ZipCompressionMethod::from_code(65000),
96            ZipCompressionMethod::Unknown(65000)
97        );
98    }
99
100    #[test]
101    fn exposes_zip_extension_label() {
102        assert_eq!(ZIP_EXTENSION, "zip");
103    }
104}