]> git.lizzy.rs Git - rust.git/blob - src/libflate/lib.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libflate / lib.rs
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.
4 //
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.
10
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.
13 //!
14 //! [def]: https://en.wikipedia.org/wiki/DEFLATE
15 //! [mz]: https://code.google.com/p/miniz/
16
17 #![crate_name = "flate"]
18 #![unstable(feature = "rustc_private")]
19 #![staged_api]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24        html_root_url = "http://doc.rust-lang.org/nightly/")]
25
26 #![feature(core)]
27 #![feature(int_uint)]
28 #![feature(libc)]
29 #![feature(staged_api)]
30
31 #[cfg(test)] #[macro_use] extern crate log;
32
33 extern crate libc;
34
35 use libc::{c_void, size_t, c_int};
36 use std::ops::Deref;
37 use std::ptr::Unique;
38 use std::slice;
39
40 pub struct Bytes {
41     ptr: Unique<u8>,
42     len: uint,
43 }
44
45 impl Deref for Bytes {
46     type Target = [u8];
47     fn deref(&self) -> &[u8] {
48         unsafe { slice::from_raw_parts(*self.ptr, self.len) }
49     }
50 }
51
52 impl Drop for Bytes {
53     fn drop(&mut self) {
54         unsafe { libc::free(*self.ptr as *mut _); }
55     }
56 }
57
58 #[link(name = "miniz", kind = "static")]
59 extern {
60     /// Raw miniz compression function.
61     fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
62                                   src_buf_len: size_t,
63                                   pout_len: *mut size_t,
64                                   flags: c_int)
65                                   -> *mut c_void;
66
67     /// Raw miniz decompression function.
68     fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
69                                     src_buf_len: size_t,
70                                     pout_len: *mut size_t,
71                                     flags: c_int)
72                                     -> *mut c_void;
73 }
74
75 static LZ_NORM : c_int = 0x80;  // LZ with 128 probes, "normal"
76 static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
77 static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
78
79 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
80     unsafe {
81         let mut outsz : size_t = 0;
82         let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
83                                              bytes.len() as size_t,
84                                              &mut outsz,
85                                              flags);
86         if !res.is_null() {
87             let res = Unique::new(res as *mut u8);
88             Some(Bytes { ptr: res, len: outsz as uint })
89         } else {
90             None
91         }
92     }
93 }
94
95 /// Compress a buffer, without writing any sort of header on the output.
96 pub fn deflate_bytes(bytes: &[u8]) -> Option<Bytes> {
97     deflate_bytes_internal(bytes, LZ_NORM)
98 }
99
100 /// Compress a buffer, using a header that zlib can understand.
101 pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
102     deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
103 }
104
105 fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
106     unsafe {
107         let mut outsz : size_t = 0;
108         let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
109                                                bytes.len() as size_t,
110                                                &mut outsz,
111                                                flags);
112         if !res.is_null() {
113             let res = Unique::new(res as *mut u8);
114             Some(Bytes { ptr: res, len: outsz as uint })
115         } else {
116             None
117         }
118     }
119 }
120
121 /// Decompress a buffer, without parsing any sort of header on the input.
122 pub fn inflate_bytes(bytes: &[u8]) -> Option<Bytes> {
123     inflate_bytes_internal(bytes, 0)
124 }
125
126 /// Decompress a buffer that starts with a zlib header.
127 pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
128     inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
129 }
130
131 #[cfg(test)]
132 mod tests {
133     #![allow(deprecated)]
134     use super::{inflate_bytes, deflate_bytes};
135     use std::rand;
136     use std::rand::Rng;
137
138     #[test]
139     fn test_flate_round_trip() {
140         let mut r = rand::thread_rng();
141         let mut words = vec!();
142         for _ in 0..20 {
143             let range = r.gen_range(1, 10);
144             let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
145             words.push(v);
146         }
147         for _ in 0..20 {
148             let mut input = vec![];
149             for _ in 0..2000 {
150                 input.push_all(r.choose(&words).unwrap());
151             }
152             debug!("de/inflate of {} bytes of random word-sequences",
153                    input.len());
154             let cmp = deflate_bytes(&input).expect("deflation failed");
155             let out = inflate_bytes(&cmp).expect("inflation failed");
156             debug!("{} bytes deflated to {} ({:.1}% size)",
157                    input.len(), cmp.len(),
158                    100.0 * ((cmp.len() as f64) / (input.len() as f64)));
159             assert_eq!(&*input, &*out);
160         }
161     }
162
163     #[test]
164     fn test_zlib_flate() {
165         let bytes = vec!(1, 2, 3, 4, 5);
166         let deflated = deflate_bytes(&bytes).expect("deflation failed");
167         let inflated = inflate_bytes(&deflated).expect("inflation failed");
168         assert_eq!(&*inflated, &*bytes);
169     }
170 }