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