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 #![crate_name = "flate"]
19 #![crate_type = "rlib"]
20 #![crate_type = "dylib"]
21 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23 html_root_url = "http://doc.rust-lang.org/nightly/")]
25 #[cfg(test)] #[macro_use] extern crate log;
29 use libc::{c_void, size_t, c_int};
39 impl Deref for Bytes {
41 fn deref(&self) -> &[u8] {
42 unsafe { slice::from_raw_mut_buf(&self.ptr.0, self.len) }
48 unsafe { libc::free(self.ptr.0 as *mut _); }
52 #[link(name = "miniz", kind = "static")]
54 /// Raw miniz compression function.
55 fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
57 pout_len: *mut size_t,
61 /// Raw miniz decompression function.
62 fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
64 pout_len: *mut size_t,
69 static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
70 static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
71 static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
73 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
75 let mut outsz : size_t = 0;
76 let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
77 bytes.len() as size_t,
81 let res = Unique(res as *mut u8);
82 Some(Bytes { ptr: res, len: outsz as uint })
89 /// Compress a buffer, without writing any sort of header on the output.
90 pub fn deflate_bytes(bytes: &[u8]) -> Option<Bytes> {
91 deflate_bytes_internal(bytes, LZ_NORM)
94 /// Compress a buffer, using a header that zlib can understand.
95 pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
96 deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
99 fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
101 let mut outsz : size_t = 0;
102 let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
103 bytes.len() as size_t,
107 let res = Unique(res as *mut u8);
108 Some(Bytes { ptr: res, len: outsz as uint })
115 /// Decompress a buffer, without parsing any sort of header on the input.
116 pub fn inflate_bytes(bytes: &[u8]) -> Option<Bytes> {
117 inflate_bytes_internal(bytes, 0)
120 /// Decompress a buffer that starts with a zlib header.
121 pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
122 inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
127 use super::{inflate_bytes, deflate_bytes};
132 fn test_flate_round_trip() {
133 let mut r = rand::thread_rng();
134 let mut words = vec!();
135 for _ in range(0u, 20) {
136 let range = r.gen_range(1u, 10);
137 let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
140 for _ in range(0u, 20) {
141 let mut input = vec![];
142 for _ in range(0u, 2000) {
143 input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
145 debug!("de/inflate of {} bytes of random word-sequences",
147 let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
148 let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
149 debug!("{} bytes deflated to {} ({:.1}% size)",
150 input.len(), cmp.len(),
151 100.0 * ((cmp.len() as f64) / (input.len() as f64)));
152 assert_eq!(input, out.as_slice());
157 fn test_zlib_flate() {
158 let bytes = vec!(1, 2, 3, 4, 5);
159 let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
160 let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
161 assert_eq!(inflated.as_slice(), bytes);