Debian Codegraph @

src/deflate.rs

raw symbols SCIP
1 //! Binding to DEFLATE library.
2 //!
3 //! [libdeflater](https://crates.io/crates/libdeflater) or [flate2](https://crates.io/crates/flate2) is used to compress/decompress data.
4
5 use std::convert::TryInto;
6 use thiserror::Error;
7
8 #[cfg(not(feature = "libdeflater"))]
9 use flate2::Status;
10
11 #[cfg(not(feature = "libdeflater"))]
12 pub use flate2::Crc;
13
14 #[cfg(feature = "libdeflater")]
15 pub use libdeflater::Crc;
16
17 use crate::BGZFError;
18
19 /// Compression Level
20 #[cfg(not(feature = "libdeflater"))]
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22 pub struct Compression(flate2::Compression);
23
24 /// Compression Level
25 #[cfg(feature = "libdeflater")]
26 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
27 pub struct Compression(libdeflater::CompressionLvl);
28
29 #[cfg(not(feature = "libdeflater"))]
30 impl Compression {
31 pub const fn new(level: u32) -> Result<Self, BGZFError> {
32 Ok(Compression(flate2::Compression::new(level)))
33 }
34
35 pub const fn best() -> Self {
36 Compression(flate2::Compression::best())
37 }
38
39 pub const fn fast() -> Self {
40 Compression(flate2::Compression::fast())
41 }
42 }
43
44 #[cfg(not(feature = "libdeflater"))]
45 impl From<flate2::Compression> for Compression {
46 fn from(value: flate2::Compression) -> Self {
47 Compression(value)
48 }
49 }
50
51 #[cfg(feature = "libdeflater")]
52 impl Compression {
53 pub fn new(level: u32) -> Result<Self, BGZFError> {
54 Ok(Compression(
55 libdeflater::CompressionLvl::new(level.try_into().unwrap()).map_err(|e| match e {
56 libdeflater::CompressionLvlError::InvalidValue => {
57 BGZFError::InvalidCompressionLevel
58 }
59 })?,
60 ))
61 }
62
63 pub fn best() -> Self {
64 Compression(libdeflater::CompressionLvl::best())
65 }
66
67 pub fn fast() -> Self {
68 Compression(libdeflater::CompressionLvl::fastest())
69 }
70 }
71
72 #[cfg(not(feature = "libdeflater"))]
73 impl Default for Compression {
74 fn default() -> Self {
75 Compression(flate2::Compression::default())
76 }
77 }
78
79 #[cfg(feature = "libdeflater")]
80 impl Default for Compression {
81 fn default() -> Self {
82 Compression(libdeflater::CompressionLvl::default())
83 }
84 }
85
86 /// Compression Error
87 #[derive(Debug, Error, Clone, PartialEq)]
88 pub enum CompressError {
89 #[error("Insufficient spcae")]
90 InsufficientSpace,
91 #[error("Other: {0}")]
92 Other(String),
93 }
94
95 /// flate2 based compressor
96 #[cfg(not(feature = "libdeflater"))]
97 #[derive(Debug)]
98 pub struct Compress(flate2::Compress);
99
100 #[cfg(not(feature = "libdeflater"))]
101 impl Compress {
102 pub fn new(level: Compression) -> Self {
103 Compress(flate2::Compress::new(level.0, false))
104 }
105
106 pub fn compress(
107 &mut self,
108 original_data: &[u8],
109 compressed_data: &mut [u8],
110 ) -> Result<usize, CompressError> {
111 self.0.reset();
112 let status = self
113 .0
114 .compress(
115 original_data,
116 compressed_data,
117 flate2::FlushCompress::Finish,
118 )
119 .map_err(|e| CompressError::Other(e.message().unwrap_or("Unkown error").to_string()))?;
120 match status {
121 flate2::Status::BufError => Err(CompressError::InsufficientSpace),
122 flate2::Status::Ok => Err(CompressError::InsufficientSpace),
123 flate2::Status::StreamEnd => Ok(self.0.total_out().try_into().unwrap()),
124 }
125 }
126 }
127
128 /// libdeflater based compressor
129 #[cfg(feature = "libdeflater")]
130 pub struct Compress(libdeflater::Compressor);
131
132 #[cfg(feature = "libdeflater")]
133 impl Compress {
134 pub fn new(level: Compression) -> Self {
135 Compress(libdeflater::Compressor::new(level.0))
136 }
137
138 pub fn compress(
139 &mut self,
140 original_data: &[u8],
141 compressed_data: &mut [u8],
142 ) -> Result<usize, CompressError> {
143 self.0
144 .deflate_compress(original_data, compressed_data)
145 .map_err(|e| match e {
146 libdeflater::CompressionError::InsufficientSpace => {
147 CompressError::InsufficientSpace
148 }
149 })
150 }
151 }
152
153 /// Decompress Error
154 #[derive(Debug, Error, Clone, PartialEq)]
155 pub enum DecompressError {
156 #[error("Decompress Error: Insufficient spcae")]
157 InsufficientSpace,
158 #[error("Decompress Error: Bad data")]
159 BadData,
160 #[error("Decompress Error: {0}")]
161 Other(String),
162 }
163
164 /// flate2 based decompressor
165 #[cfg(not(feature = "libdeflater"))]
166 #[derive(Debug)]
167 pub struct Decompress(flate2::Decompress);
168
169 #[cfg(not(feature = "libdeflater"))]
170 impl Decompress {
171 pub fn new() -> Self {
172 Decompress(flate2::Decompress::new(false))
173 }
174
175 pub fn decompress(
176 &mut self,
177 compressed_data: &[u8],
178 decompressed_data: &mut [u8],
179 ) -> Result<usize, DecompressError> {
180 self.0.reset(false);
181 match self
182 .0
183 .decompress(
184 compressed_data,
185 decompressed_data,
186 flate2::FlushDecompress::Finish,
187 )
188 .map_err(|e| {
189 DecompressError::Other(e.message().unwrap_or("Unknown Error").to_string())
190 })? {
191 Status::StreamEnd => Ok(self.0.total_out().try_into().unwrap()),
192 Status::Ok => Err(DecompressError::InsufficientSpace),
193 Status::BufError => Err(DecompressError::InsufficientSpace),
194 }
195 }
196 }
197
198 /// libdeflater based decompressor
199 #[cfg(feature = "libdeflater")]
200 pub struct Decompress(libdeflater::Decompressor);
201
202 #[cfg(feature = "libdeflater")]
203 impl Decompress {
204 pub fn new() -> Self {
205 Decompress(libdeflater::Decompressor::new())
206 }
207
208 pub fn decompress(
209 &mut self,
210 compressed_data: &[u8],
211 decompressed_data: &mut [u8],
212 ) -> Result<usize, DecompressError> {
213 self.0
214 .deflate_decompress(compressed_data, decompressed_data)
215 .map_err(|e| match e {
216 libdeflater::DecompressionError::BadData => DecompressError::BadData,
217 libdeflater::DecompressionError::InsufficientSpace => {
218 DecompressError::InsufficientSpace
219 }
220 })
221 }
222 }
223
224 #[cfg(test)]
225 mod test {
226 use super::*;
227 use rand::prelude::*;
228
229 const BUF_SIZE: usize = 3000;
230
231 #[test]
232 fn test_deflate_inflate() -> anyhow::Result<()> {
233 let mut rand = rand_pcg::Pcg64Mcg::seed_from_u64(0x3874aef456157523);
234 let mut original_data = vec![0; BUF_SIZE];
235 rand.fill_bytes(&mut original_data);
236
237 let mut compress = Compress::new(Compression::default());
238 let mut small_buf = [0; 100];
239 assert_eq!(
240 compress.compress(&original_data, &mut small_buf),
241 Err(CompressError::InsufficientSpace)
242 );
243
244 let mut decompress = Decompress::new();
245 let mut deflated_data = vec![0; BUF_SIZE + 500];
246 let deflate_size = compress.compress(&original_data, &mut deflated_data)?;
247 let mut inflated_data = vec![0; BUF_SIZE];
248
249 assert_eq!(
250 decompress.decompress(&deflated_data[..deflate_size], &mut small_buf),
251 Err(DecompressError::InsufficientSpace)
252 );
253
254 assert!(decompress
255 .decompress(&deflated_data[..100], &mut inflated_data)
256 .is_err());
257
258 let inflate_size =
259 decompress.decompress(&deflated_data[..deflate_size], &mut inflated_data)?;
260 assert_eq!(inflate_size, original_data.len());
261 assert_eq!(inflated_data, original_data);
262
263 Ok(())
264 }
265 }