walker_common/compression/
detecting.rs1use 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 pub limit: usize,
32}
33
34impl DecompressionOptions {
35 pub fn new() -> Self {
36 Self::default()
37 }
38
39 pub fn limit(mut self, limit: usize) -> Self {
41 self.limit = limit;
42 self
43 }
44}
45
46impl Compression {
47 pub fn decompress(&self, data: Bytes) -> Result<Bytes, std::io::Error> {
51 Ok(self.decompress_opt(&data)?.unwrap_or(data))
52 }
53
54 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 pub fn decompress_opt(&self, data: &[u8]) -> Result<Option<Bytes>, std::io::Error> {
69 self.decompress_opt_with(data, &Default::default())
70 }
71
72 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 pub file_name: Option<&'a str>,
108
109 pub disable_magic: bool,
111
112 pub ignore_file_extensions: HashSet<&'a str>,
114 pub fail_unknown_file_extension: bool,
116}
117
118impl<'a> Detector<'a> {
119 pub fn decompress(&self, data: Bytes) -> Result<Bytes, Error<'a>> {
121 self.decompress_with(data, &Default::default())
122 }
123
124 pub fn decompress_with(
126 &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(&self, #[allow(unused)] data: &[u8]) -> Result<Compression, Error<'a>> {
135 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 && let Some((_, ext)) = file_name.rsplit_once('.')
152 && !self.ignore_file_extensions.contains(ext)
153 {
154 return Err(Error::Unsupported(ext));
155 }
156 }
157
158 if !self.disable_magic {
161 #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
162 if data.starts_with(b"BZh") {
163 return Ok(Compression::Bzip2);
164 }
165 #[cfg(feature = "liblzma")]
166 if data.starts_with(&[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]) {
167 return Ok(Compression::Xz);
168 }
169 #[cfg(feature = "flate2")]
170 if data.starts_with(&[0x1F, 0x8B, 0x08]) {
171 return Ok(Compression::Gzip);
175 }
176 }
177
178 Ok(Compression::None)
181 }
182}
183
184#[cfg(test)]
185mod test {
186 use super::*;
187
188 fn detect(name: &str) -> Compression {
189 Detector {
190 file_name: Some(name),
191 disable_magic: true,
192 ..Default::default()
193 }
194 .detect(&[])
195 .unwrap()
196 }
197
198 #[test]
199 fn by_name_none() {
200 assert_eq!(detect("foo.bar.json"), Compression::None);
201 }
202
203 #[cfg(any(feature = "bzip2", feature = "bzip2-rs"))]
204 #[test]
205 fn by_name_bzip2() {
206 assert_eq!(detect("foo.bar.bz2"), Compression::Bzip2);
207 }
208
209 #[cfg(feature = "liblzma")]
210 #[test]
211 fn by_name_xz() {
212 assert_eq!(detect("foo.bar.xz"), Compression::Xz);
213 }
214
215 #[cfg(feature = "flate2")]
216 #[test]
217 fn by_name_gzip() {
218 assert_eq!(detect("foo.bar.gz"), Compression::Gzip);
219 }
220
221 #[test]
222 fn default() {
223 let _result = Detector::default().decompress(Bytes::from_static(b"foo"));
225
226 let detector = Detector::default();
227 let _result = detector.decompress(Bytes::from_static(b"foo"));
228 }
229}