1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Simple [DEFLATE][def]-based compression. This is a wrapper around the
12 //! [`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
14 //! [def]: https://en.wikipedia.org/wiki/DEFLATE
15 //! [mz]: https://code.google.com/p/miniz/
17 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
18 #![cfg_attr(stage0, feature(custom_attribute))]
19 #![crate_name = "flate"]
20 #![unstable(feature = "rustc_private", issue = "27812")]
22 #![crate_type = "rlib"]
23 #![crate_type = "dylib"]
24 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
25 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
26 html_root_url = "https://doc.rust-lang.org/nightly/",
27 test(attr(deny(warnings))))]
30 #![feature(staged_api)]
32 #![cfg_attr(test, feature(rustc_private, rand, vec_push_all))]
33 #![cfg_attr(stage0, allow(improper_ctypes))]
41 use libc::{c_void, size_t, c_int};
47 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
58 impl fmt::Debug for Error {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 "decompression error".fmt(f)
69 impl Deref for Bytes {
71 fn deref(&self) -> &[u8] {
72 unsafe { slice::from_raw_parts(*self.ptr, self.len) }
79 libc::free(*self.ptr as *mut _);
84 #[link(name = "miniz", kind = "static")]
86 /// Raw miniz compression function.
87 fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
89 pout_len: *mut size_t,
93 /// Raw miniz decompression function.
94 fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
96 pout_len: *mut size_t,
101 const LZ_NORM: c_int = 0x80; // LZ with 128 probes, "normal"
102 const TINFL_FLAG_PARSE_ZLIB_HEADER: c_int = 0x1; // parse zlib header and adler32 checksum
103 const TDEFL_WRITE_ZLIB_HEADER: c_int = 0x01000; // write zlib header and adler32 checksum
105 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Bytes {
107 let mut outsz: size_t = 0;
108 let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
109 bytes.len() as size_t,
112 assert!(!res.is_null());
114 ptr: Unique::new(res as *mut u8),
120 /// Compress a buffer, without writing any sort of header on the output.
121 pub fn deflate_bytes(bytes: &[u8]) -> Bytes {
122 deflate_bytes_internal(bytes, LZ_NORM)
125 /// Compress a buffer, using a header that zlib can understand.
126 pub fn deflate_bytes_zlib(bytes: &[u8]) -> Bytes {
127 deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
130 fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Result<Bytes, Error> {
132 let mut outsz: size_t = 0;
133 let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
134 bytes.len() as size_t,
139 ptr: Unique::new(res as *mut u8),
148 /// Decompress a buffer, without parsing any sort of header on the input.
149 pub fn inflate_bytes(bytes: &[u8]) -> Result<Bytes, Error> {
150 inflate_bytes_internal(bytes, 0)
153 /// Decompress a buffer that starts with a zlib header.
154 pub fn inflate_bytes_zlib(bytes: &[u8]) -> Result<Bytes, Error> {
155 inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
160 #![allow(deprecated)]
161 use super::{inflate_bytes, deflate_bytes};
162 use std::__rand::{thread_rng, Rng};
165 fn test_flate_round_trip() {
166 let mut r = thread_rng();
167 let mut words = vec![];
169 let range = r.gen_range(1, 10);
170 let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
174 let mut input = vec![];
176 input.push_all(r.choose(&words).unwrap());
178 debug!("de/inflate of {} bytes of random word-sequences",
180 let cmp = deflate_bytes(&input);
181 let out = inflate_bytes(&cmp).unwrap();
182 debug!("{} bytes deflated to {} ({:.1}% size)",
185 100.0 * ((cmp.len() as f64) / (input.len() as f64)));
186 assert_eq!(&*input, &*out);
191 fn test_zlib_flate() {
192 let bytes = vec![1, 2, 3, 4, 5];
193 let deflated = deflate_bytes(&bytes);
194 let inflated = inflate_bytes(&deflated).unwrap();
195 assert_eq!(&*inflated, &*bytes);