1use crate::{Algorithm, Compression, Error, Sink};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub struct Deflate;
31
32impl Deflate {
33 pub const fn new() -> Self {
37 Deflate
38 }
39
40 pub const fn is_supported() -> bool {
44 cfg!(feature = "zlib")
45 }
46
47 pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
49 imp::encode(data, 6, imp::RAW, "gzdeflate", out)
50 }
51
52 pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
54 imp::decode(data, imp::RAW, "gzinflate", out)
55 }
56}
57
58impl Algorithm for Deflate {
59 fn name(&self) -> &str {
60 Compression::DEFLATE
61 }
62
63 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
64 let mut out = Vec::new();
65 self.compress_into(data, &mut out)?;
66 Ok(out)
67 }
68
69 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
70 let mut out = Vec::new();
71 self.decompress_into(data, &mut out)?;
72 Ok(out)
73 }
74
75 fn supported(&self) -> bool {
76 Self::is_supported()
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
107pub struct Gzip;
108
109impl Gzip {
110 pub const fn new() -> Self {
114 Gzip
115 }
116
117 pub const fn is_supported() -> bool {
121 cfg!(feature = "zlib")
122 }
123
124 pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
126 imp::encode(data, -1, imp::GZIP, "gzencode", out)
127 }
128
129 pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
131 imp::decode(data, imp::GZIP, "gzdecode", out)
132 }
133}
134
135impl Algorithm for Gzip {
136 fn name(&self) -> &str {
137 Compression::GZIP
138 }
139
140 fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
141 let mut out = Vec::new();
142 self.compress_into(data, &mut out)?;
143 Ok(out)
144 }
145
146 fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
147 let mut out = Vec::new();
148 self.decompress_into(data, &mut out)?;
149 Ok(out)
150 }
151
152 fn supported(&self) -> bool {
153 Self::is_supported()
154 }
155}
156
157#[cfg(feature = "zlib")]
158mod imp {
159 use std::cell::Cell;
174 use std::mem::MaybeUninit;
175 use std::os::raw::c_int;
176 use std::thread::LocalKey;
177
178 use libz_sys as z;
179
180 use crate::sink::spare;
181 use crate::{Error, Sink};
182
183 pub(super) const RAW: c_int = -15;
185 pub(super) const GZIP: c_int = 31;
187
188 static NUL: [u8; 1] = [0];
190
191 const MEM_LEVEL: c_int = 9;
193
194 const MAX_RATIO: usize = 1032;
197
198 fn message(status: c_int) -> &'static str {
200 match status {
201 z::Z_NEED_DICT => "need dictionary",
202 z::Z_STREAM_END => "stream end",
203 z::Z_ERRNO => "file error",
204 z::Z_STREAM_ERROR => "stream error",
205 z::Z_DATA_ERROR => "data error",
206 z::Z_MEM_ERROR => "insufficient memory",
207 z::Z_BUF_ERROR => "buffer error",
208 z::Z_VERSION_ERROR => "incompatible version",
209 _ => "",
210 }
211 }
212
213 fn codec(function: &str, status: c_int) -> Error {
215 Error::Codec(format!("{function}(): {}", message(status)))
216 }
217
218 struct Stream {
220 raw: Box<MaybeUninit<z::z_stream>>,
221 inflate: bool,
222 }
223
224 impl Stream {
225 fn ptr(&mut self) -> *mut z::z_stream {
226 self.raw.as_mut_ptr()
227 }
228 }
229
230 impl Drop for Stream {
231 fn drop(&mut self) {
232 let s = self.ptr();
233 unsafe {
236 if self.inflate {
237 z::inflateEnd(s);
238 } else {
239 z::deflateEnd(s);
240 }
241 }
242 }
243 }
244
245 thread_local! {
246 static DEFLATE_RAW: Cell<Option<Stream>> = const { Cell::new(None) };
247 static DEFLATE_GZIP: Cell<Option<Stream>> = const { Cell::new(None) };
248 static INFLATE_RAW: Cell<Option<Stream>> = const { Cell::new(None) };
249 static INFLATE_GZIP: Cell<Option<Stream>> = const { Cell::new(None) };
250 }
251
252 fn slot(inflate: bool, encoding: c_int) -> &'static LocalKey<Cell<Option<Stream>>> {
256 match (inflate, encoding == GZIP) {
257 (false, false) => &DEFLATE_RAW,
258 (false, true) => &DEFLATE_GZIP,
259 (true, false) => &INFLATE_RAW,
260 (true, true) => &INFLATE_GZIP,
261 }
262 }
263
264 fn deflater(level: c_int, encoding: c_int) -> Result<Stream, c_int> {
267 if let Some(mut stream) = slot(false, encoding).with(Cell::take) {
268 if unsafe { z::deflateReset(stream.ptr()) } == z::Z_OK {
270 return Ok(stream);
271 }
272 }
273 let mut raw = Box::new(MaybeUninit::<z::z_stream>::zeroed());
274 let status = unsafe {
277 z::deflateInit2_(
278 raw.as_mut_ptr(),
279 level,
280 z::Z_DEFLATED,
281 encoding,
282 MEM_LEVEL,
283 z::Z_DEFAULT_STRATEGY,
284 z::zlibVersion(),
285 std::mem::size_of::<z::z_stream>() as c_int,
286 )
287 };
288 if status != z::Z_OK {
289 return Err(status);
290 }
291 Ok(Stream { raw, inflate: false })
292 }
293
294 fn inflater(encoding: c_int) -> Result<Stream, c_int> {
296 if let Some(mut stream) = slot(true, encoding).with(Cell::take) {
297 if unsafe { z::inflateReset(stream.ptr()) } == z::Z_OK {
299 return Ok(stream);
300 }
301 }
302 let mut raw = Box::new(MaybeUninit::<z::z_stream>::zeroed());
303 let status = unsafe {
305 z::inflateInit2_(raw.as_mut_ptr(), encoding, z::zlibVersion(), std::mem::size_of::<z::z_stream>() as c_int)
306 };
307 if status != z::Z_OK {
308 return Err(status);
309 }
310 Ok(Stream { raw, inflate: true })
311 }
312
313 fn keep(stream: Stream, encoding: c_int) {
315 slot(stream.inflate, encoding).with(|slot| slot.set(Some(stream)));
316 }
317
318 pub(super) fn encode<S: Sink + ?Sized>(
321 data: &[u8],
322 level: c_int,
323 encoding: c_int,
324 function: &str,
325 out: &mut S,
326 ) -> Result<(), Error> {
327 let start = out.len();
328 let guess = (data.len() as f64 * 1.015) as usize + 10 + 8 + 4 + 1;
329 if !out.grow(start + guess) {
331 return Err(codec(function, z::Z_MEM_ERROR));
332 }
333 let mut stream = deflater(level, encoding).map_err(|status| codec(function, status))?;
334 let (at, _) = spare(out);
335 let s = stream.ptr();
336 let (status, written) = unsafe {
340 (&raw mut (*s).next_in).write(data.as_ptr().cast_mut());
341 (&raw mut (*s).avail_in).write(data.len() as z::uInt);
342 (&raw mut (*s).next_out).write(at);
343 (&raw mut (*s).avail_out).write(guess as z::uInt);
344 let status = z::deflate(s, z::Z_FINISH);
345 (status, (&raw const (*s).total_out).read() as usize)
346 };
347 keep(stream, encoding);
348 if status != z::Z_STREAM_END {
349 return Err(codec(function, status));
350 }
351 unsafe { out.set_len(start + written.min(guess)) };
353 if encoding == GZIP && written > 9 {
356 unsafe { *out.as_mut_ptr().add(start + 9) = 3 };
358 }
359 Ok(())
360 }
361
362 pub(super) fn decode<S: Sink + ?Sized>(
375 data: &[u8],
376 encoding: c_int,
377 function: &str,
378 out: &mut S,
379 ) -> Result<(), Error> {
380 if data.is_empty() {
381 return Err(codec(function, z::Z_DATA_ERROR));
382 }
383 let start = out.len();
384 let mut hinted = false;
387 if encoding == GZIP
388 && data.len() >= 18
389 && let Some(trailer) = data.last_chunk::<4>()
390 {
391 let size = u32::from_le_bytes(*trailer) as usize;
392 if size <= data.len().saturating_mul(MAX_RATIO) {
393 hinted = out.reserve(start + size.max(data.len() + 1));
394 }
395 }
396 let mut stream = inflater(encoding).map_err(|status| codec(function, status))?;
397 let s = stream.ptr();
398 let status = unsafe {
402 (&raw mut (*s).next_in).write(data.as_ptr().cast_mut());
403 (&raw mut (*s).avail_in).write(data.len() as z::uInt);
404 let mut nul = true;
405 let feed_nul = |s: *mut z::z_stream| {
406 (&raw mut (*s).next_in).write(NUL.as_ptr().cast_mut());
407 (&raw mut (*s).avail_in).write(1);
408 };
409
410 let mut size = data.len() + 1;
411 let mut used = 0;
412 let mut round = 0;
413 loop {
414 let capacity = out.capacity();
419 let mut free = (size - used) as z::uInt;
420 let mut capped = false;
421 if start + size > capacity {
422 if hinted && capacity > start + used {
423 free = (capacity - start - used) as z::uInt;
424 capped = true;
425 } else if !out.grow((start + size).max(capacity + capacity / 2)) {
426 break z::Z_MEM_ERROR;
427 }
428 }
429 let (at, _) = spare(out);
430 (&raw mut (*s).next_out).write(at);
431 (&raw mut (*s).avail_out).write(free);
432 if nul && (&raw const (*s).avail_in).read() == 0 {
433 feed_nul(s);
434 nul = false;
435 }
436 let mut status = z::inflate(s, z::Z_NO_FLUSH);
437 if nul
438 && status == z::Z_OK
439 && (&raw const (*s).avail_in).read() == 0
440 && (&raw const (*s).avail_out).read() != 0
441 {
442 feed_nul(s);
443 nul = false;
444 status = z::inflate(s, z::Z_NO_FLUSH);
445 }
446 used += (free - (&raw const (*s).avail_out).read()) as usize;
447 out.set_len(start + used);
448 if capped && (&raw const (*s).avail_out).read() == 0 && matches!(status, z::Z_OK | z::Z_BUF_ERROR) {
449 hinted = false;
450 continue;
451 }
452 size += (size >> 3) + 1;
453 round += 1;
454 let more =
455 status == z::Z_BUF_ERROR || (status == z::Z_OK && ((&raw const (*s).avail_in).read() != 0 || nul));
456 if !(more && round < 100) {
457 break status;
458 }
459 }
460 };
461 keep(stream, encoding);
462 match status {
463 z::Z_STREAM_END => Ok(()),
464 z::Z_OK => Err(codec(function, z::Z_DATA_ERROR)),
466 status => Err(codec(function, status)),
467 }
468 }
469}
470
471#[cfg(not(feature = "zlib"))]
472mod imp {
473 use crate::{Error, Sink};
474
475 pub(super) const RAW: i32 = -15;
476 pub(super) const GZIP: i32 = 31;
477
478 pub(super) fn encode<S: Sink + ?Sized>(_: &[u8], _: i32, _: i32, function: &str, _: &mut S) -> Result<(), Error> {
479 Err(Error::undefined(function))
480 }
481
482 pub(super) fn decode<S: Sink + ?Sized>(_: &[u8], _: i32, function: &str, _: &mut S) -> Result<(), Error> {
483 Err(Error::undefined(function))
484 }
485}
486
487#[cfg(all(test, feature = "zlib"))]
488mod tests {
489 use super::*;
490
491 #[test]
492 fn round_trips() {
493 let data = b"hello hello hello hello".repeat(100);
494 for algorithm in [&Deflate as &dyn Algorithm, &Gzip] {
495 let compressed = algorithm.compress(&data).unwrap();
496 assert!(compressed.len() < data.len());
497 assert_eq!(algorithm.decompress(&compressed).unwrap(), data);
498 assert_eq!(algorithm.compress(&data).unwrap(), compressed);
500 assert_eq!(algorithm.decompress(&compressed).unwrap(), data);
501 }
502 }
503
504 #[test]
505 fn appends() {
506 let mut out = b"prefix".to_vec();
507 Gzip.compress_into(b"abc", &mut out).unwrap();
508 assert_eq!(&out[..6], b"prefix");
509 assert_eq!(out[6 + 9], 3);
510 let mut plain = b"x".to_vec();
511 Gzip.decompress_into(&out[6..], &mut plain).unwrap();
512 assert_eq!(plain, b"xabc");
513 }
514
515 #[test]
516 fn invalid_data() {
517 assert_eq!(Deflate.decompress(b""), Err(Error::Codec("gzinflate(): data error".into())));
518 assert_eq!(Gzip.decompress(b"garbage"), Err(Error::Codec("gzdecode(): data error".into())));
519 let data = b"abc".repeat(1000);
522 let mut body = Gzip.compress(&data).unwrap();
523 assert_eq!(Gzip.decompress(&body).unwrap(), data);
524 let len = body.len();
525 body[len - 4..].copy_from_slice(&7u32.to_le_bytes());
526 assert_eq!(Gzip.decompress(&body), Err(Error::Codec("gzdecode(): data error".into())));
527 }
528}