]> git.lizzy.rs Git - rust.git/blob - src/libflate/lib.rs
51f387523294f43832cd263e485e6ae017d26ec3
[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 // 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")]
21 #![staged_api]
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
28 #![feature(libc)]
29 #![feature(staged_api)]
30 #![feature(unique)]
31 #![cfg_attr(test, feature(rustc_private, rand, vec_push_all))]
32 #![cfg_attr(stage0, allow(improper_ctypes))]
33
34 #[cfg(test)]
35 #[macro_use]
36 extern crate log;
37
38 extern crate libc;
39
40 use libc::{c_void, size_t, c_int};
41 use std::fmt;
42 use std::ops::Deref;
43 use std::ptr::Unique;
44 use std::slice;
45
46 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
47 pub struct Error {
48     _unused: (),
49 }
50
51 impl Error {
52     fn new() -> Error {
53         Error { _unused: () }
54     }
55 }
56
57 impl fmt::Debug for Error {
58     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59         "decompression error".fmt(f)
60     }
61 }
62
63 pub struct Bytes {
64     ptr: Unique<u8>,
65     len: usize,
66 }
67
68 impl Deref for Bytes {
69     type Target = [u8];
70     fn deref(&self) -> &[u8] {
71         unsafe { slice::from_raw_parts(*self.ptr, self.len) }
72     }
73 }
74
75 impl Drop for Bytes {
76     fn drop(&mut self) {
77         unsafe {
78             libc::free(*self.ptr as *mut _);
79         }
80     }
81 }
82
83 #[link(name = "miniz", kind = "static")]
84 extern {
85     /// Raw miniz compression function.
86     fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
87                                   src_buf_len: size_t,
88                                   pout_len: *mut size_t,
89                                   flags: c_int)
90                                   -> *mut c_void;
91
92     /// Raw miniz decompression function.
93     fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
94                                     src_buf_len: size_t,
95                                     pout_len: *mut size_t,
96                                     flags: c_int)
97                                     -> *mut c_void;
98 }
99
100 const LZ_NORM: c_int = 0x80;  // LZ with 128 probes, "normal"
101 const TINFL_FLAG_PARSE_ZLIB_HEADER: c_int = 0x1; // parse zlib header and adler32 checksum
102 const TDEFL_WRITE_ZLIB_HEADER: c_int = 0x01000; // write zlib header and adler32 checksum
103
104 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Bytes {
105     unsafe {
106         let mut outsz: size_t = 0;
107         let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
108                                              bytes.len() as size_t,
109                                              &mut outsz,
110                                              flags);
111         assert!(!res.is_null());
112         Bytes {
113             ptr: Unique::new(res as *mut u8),
114             len: outsz as usize,
115         }
116     }
117 }
118
119 /// Compress a buffer, without writing any sort of header on the output.
120 pub fn deflate_bytes(bytes: &[u8]) -> Bytes {
121     deflate_bytes_internal(bytes, LZ_NORM)
122 }
123
124 /// Compress a buffer, using a header that zlib can understand.
125 pub fn deflate_bytes_zlib(bytes: &[u8]) -> Bytes {
126     deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
127 }
128
129 fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Result<Bytes, Error> {
130     unsafe {
131         let mut outsz: size_t = 0;
132         let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
133                                                bytes.len() as size_t,
134                                                &mut outsz,
135                                                flags);
136         if !res.is_null() {
137             Ok(Bytes {
138                 ptr: Unique::new(res as *mut u8),
139                 len: outsz as usize,
140             })
141         } else {
142             Err(Error::new())
143         }
144     }
145 }
146
147 /// Decompress a buffer, without parsing any sort of header on the input.
148 pub fn inflate_bytes(bytes: &[u8]) -> Result<Bytes, Error> {
149     inflate_bytes_internal(bytes, 0)
150 }
151
152 /// Decompress a buffer that starts with a zlib header.
153 pub fn inflate_bytes_zlib(bytes: &[u8]) -> Result<Bytes, Error> {
154     inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
155 }
156
157 #[cfg(test)]
158 mod tests {
159     #![allow(deprecated)]
160     use super::{inflate_bytes, deflate_bytes};
161     use std::__rand::{thread_rng, Rng};
162
163     #[test]
164     fn test_flate_round_trip() {
165         let mut r = thread_rng();
166         let mut words = vec![];
167         for _ in 0..20 {
168             let range = r.gen_range(1, 10);
169             let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
170             words.push(v);
171         }
172         for _ in 0..20 {
173             let mut input = vec![];
174             for _ in 0..2000 {
175                 input.push_all(r.choose(&words).unwrap());
176             }
177             debug!("de/inflate of {} bytes of random word-sequences",
178                    input.len());
179             let cmp = deflate_bytes(&input);
180             let out = inflate_bytes(&cmp).unwrap();
181             debug!("{} bytes deflated to {} ({:.1}% size)",
182                    input.len(),
183                    cmp.len(),
184                    100.0 * ((cmp.len() as f64) / (input.len() as f64)));
185             assert_eq!(&*input, &*out);
186         }
187     }
188
189     #[test]
190     fn test_zlib_flate() {
191         let bytes = vec![1, 2, 3, 4, 5];
192         let deflated = deflate_bytes(&bytes);
193         let inflated = inflate_bytes(&deflated).unwrap();
194         assert_eq!(&*inflated, &*bytes);
195     }
196 }