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