walker_common/compression/
detecting.rs

1use bytes::Bytes;
2use std::collections::HashSet;
3
4#[derive(Debug, thiserror::Error)]
5pub enum Error<'a> {
6    #[error("unsupported compression: {0}")]
7    Unsupported(&'a str),
8    #[error(transparent)]
9    Io(#[from] std::io::Error),
10}
11
12#[derive(Copy, Clone, Eq, PartialEq, Debug)]
13#[non_exhaustive]
14pub enum Compression {
15    None,
16    #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
17    Bzip2,
18    #[cfg(feature = "liblzma")]
19    Xz,
20    #[cfg(feature = "flate2")]
21    Gzip,
22}
23
24#[non_exhaustive]
25#[derive(Clone, Debug, PartialEq, Eq, Default)]
26pub struct DecompressionOptions {
27    /// The maximum decompressed payload size.
28    ///
29    /// If the size of the uncompressed payload exceeds this limit, and error would be returned
30    /// instead. Zero means, unlimited.
31    pub limit: usize,
32}
33
34impl DecompressionOptions {
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Set the limit of the maximum uncompressed payload size.
40    pub fn limit(mut self, limit: usize) -> Self {
41        self.limit = limit;
42        self
43    }
44}
45
46impl Compression {
47    /// Perform decompression.
48    ///
49    /// Returns the original data for [`Compression::None`].
50    pub fn decompress(&self, data: Bytes) -> Result<Bytes, std::io::Error> {
51        Ok(self.decompress_opt(&data)?.unwrap_or(data))
52    }
53
54    /// Perform decompression.
55    ///
56    /// Returns the original data for [`Compression::None`].
57    pub fn decompress_with(
58        &self,
59        data: Bytes,
60        opts: &DecompressionOptions,
61    ) -> Result<Bytes, std::io::Error> {
62        Ok(self.decompress_opt_with(&data, opts)?.unwrap_or(data))
63    }
64
65    /// Perform decompression.
66    ///
67    /// Returns `None` for [`Compression::None`]
68    pub fn decompress_opt(&self, data: &[u8]) -> Result<Option<Bytes>, std::io::Error> {
69        self.decompress_opt_with(data, &Default::default())
70    }
71
72    /// Perform decompression.
73    ///
74    /// Returns `None` for [`Compression::None`]
75    pub fn decompress_opt_with(
76        &self,
77        #[allow(unused_variables)] data: &[u8],
78        #[allow(unused_variables)] opts: &DecompressionOptions,
79    ) -> Result<Option<Bytes>, std::io::Error> {
80        match self {
81            #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
82            Compression::Bzip2 =>
83            {
84                #[allow(deprecated)]
85                super::decompress_bzip2_with(data, opts).map(Some)
86            }
87            #[cfg(feature = "liblzma")]
88            Compression::Xz =>
89            {
90                #[allow(deprecated)]
91                super::decompress_xz_with(data, opts).map(Some)
92            }
93            #[cfg(feature = "flate2")]
94            Compression::Gzip =>
95            {
96                #[allow(deprecated)]
97                super::decompress_gzip_with(data, opts).map(Some)
98            }
99            Compression::None => Ok(None),
100        }
101    }
102}
103
104#[derive(Clone, Debug, Default)]
105pub struct Detector<'a> {
106    /// File name
107    pub file_name: Option<&'a str>,
108
109    /// Disable detection by magic bytes
110    pub disable_magic: bool,
111
112    /// File name extensions to ignore.
113    pub ignore_file_extensions: HashSet<&'a str>,
114    /// If a file name is present, but the extension is unknown, report as an error
115    pub fail_unknown_file_extension: bool,
116}
117
118impl<'a> Detector<'a> {
119    /// Detect and decompress in a single step.
120    pub fn decompress(&'a self, data: Bytes) -> Result<Bytes, Error<'a>> {
121        self.decompress_with(data, &Default::default())
122    }
123
124    /// Detect and decompress in a single step.
125    pub fn decompress_with(
126        &'a self,
127        data: Bytes,
128        opts: &DecompressionOptions,
129    ) -> Result<Bytes, Error<'a>> {
130        let compression = self.detect(&data)?;
131        Ok(compression.decompress_with(data, opts)?)
132    }
133
134    pub fn detect(&'a self, #[allow(unused)] data: &[u8]) -> Result<Compression, Error<'a>> {
135        // detect by file name extension
136
137        if let Some(file_name) = self.file_name {
138            #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
139            if file_name.ends_with(".bz2") {
140                return Ok(Compression::Bzip2);
141            }
142            #[cfg(feature = "liblzma")]
143            if file_name.ends_with(".xz") {
144                return Ok(Compression::Xz);
145            }
146            #[cfg(feature = "flate2")]
147            if file_name.ends_with(".gz") {
148                return Ok(Compression::Gzip);
149            }
150            if self.fail_unknown_file_extension {
151                if let Some((_, ext)) = file_name.rsplit_once('.') {
152                    if !self.ignore_file_extensions.contains(ext) {
153                        return Err(Error::Unsupported(ext));
154                    }
155                }
156            }
157        }
158
159        // magic bytes
160
161        if !self.disable_magic {
162            #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
163            if data.starts_with(b"BZh") {
164                return Ok(Compression::Bzip2);
165            }
166            #[cfg(feature = "liblzma")]
167            if data.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
168                return Ok(Compression::Xz);
169            }
170            #[cfg(feature = "flate2")]
171            if data.starts_with(&[0x1F, 0x8B, 0x08]) {
172                // NOTE: Byte #3 (0x08) is the compression format, which means "deflate" and is the
173                // only one supported right now. Having additional compression formats, we'd need
174                // to extend this check, or drop the 3rd byte.
175                return Ok(Compression::Gzip);
176            }
177        }
178
179        // done
180
181        Ok(Compression::None)
182    }
183}
184
185#[cfg(test)]
186mod test {
187    use super::*;
188
189    fn detect(name: &str) -> Compression {
190        Detector {
191            file_name: Some(name),
192            disable_magic: true,
193            ..Default::default()
194        }
195        .detect(&[])
196        .unwrap()
197    }
198
199    #[test]
200    fn by_name_none() {
201        assert_eq!(detect("foo.bar.json"), Compression::None);
202    }
203
204    #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
205    #[test]
206    fn by_name_bzip2() {
207        assert_eq!(detect("foo.bar.bz2"), Compression::Bzip2);
208    }
209
210    #[cfg(feature = "liblzma")]
211    #[test]
212    fn by_name_xz() {
213        assert_eq!(detect("foo.bar.xz"), Compression::Xz);
214    }
215
216    #[cfg(feature = "flate2")]
217    #[test]
218    fn by_name_gzip() {
219        assert_eq!(detect("foo.bar.gz"), Compression::Gzip);
220    }
221}