]> git.lizzy.rs Git - rust.git/blob - src/libflate/lib.rs
Unignore u128 test for stage 0,1
[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 #![deny(warnings)]
26
27 #![feature(libc)]
28 #![feature(staged_api)]
29 #![feature(unique)]
30 #![cfg_attr(test, feature(rand))]
31
32 extern crate libc;
33
34 use libc::{c_int, c_void, size_t};
35 use std::fmt;
36 use std::ops::Deref;
37 use std::ptr::Unique;
38 use std::slice;
39
40 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
41 pub struct Error {
42     _unused: (),
43 }
44
45 impl Error {
46     fn new() -> Error {
47         Error { _unused: () }
48     }
49 }
50
51 impl fmt::Debug for Error {
52     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53         "decompression error".fmt(f)
54     }
55 }
56
57 pub struct Bytes {
58     ptr: Unique<u8>,
59     len: usize,
60 }
61
62 impl Deref for Bytes {
63     type Target = [u8];
64     fn deref(&self) -> &[u8] {
65         unsafe { slice::from_raw_parts(*self.ptr, self.len) }
66     }
67 }
68
69 impl Drop for Bytes {
70     fn drop(&mut self) {
71         unsafe {
72             libc::free(*self.ptr as *mut _);
73         }
74     }
75 }
76
77 #[link(name = "miniz", kind = "static")]
78 #[cfg(not(cargobuild))]
79 extern "C" {}
80
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_FAST: c_int = 0x01;  // LZ with 1 probe, "fast"
98 const TDEFL_GREEDY_PARSING_FLAG: c_int = 0x04000; // fast greedy parsing instead of lazy parsing
99
100 /// Compress a buffer without writing any sort of header on the output. Fast
101 /// compression is used because it is almost twice as fast as default
102 /// compression and the compression ratio is only marginally worse.
103 pub fn deflate_bytes(bytes: &[u8]) -> Bytes {
104     let flags = LZ_FAST | TDEFL_GREEDY_PARSING_FLAG;
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 /// Decompress a buffer without parsing any sort of header on the input.
120 pub fn inflate_bytes(bytes: &[u8]) -> Result<Bytes, Error> {
121     let flags = 0;
122     unsafe {
123         let mut outsz: size_t = 0;
124         let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
125                                                bytes.len() as size_t,
126                                                &mut outsz,
127                                                flags);
128         if !res.is_null() {
129             Ok(Bytes {
130                 ptr: Unique::new(res as *mut u8),
131                 len: outsz as usize,
132             })
133         } else {
134             Err(Error::new())
135         }
136     }
137 }
138
139 #[cfg(test)]
140 mod tests {
141     #![allow(deprecated)]
142     use super::{deflate_bytes, inflate_bytes};
143     use std::__rand::{Rng, thread_rng};
144
145     #[test]
146     fn test_flate_round_trip() {
147         let mut r = thread_rng();
148         let mut words = vec![];
149         for _ in 0..20 {
150             let range = r.gen_range(1, 10);
151             let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
152             words.push(v);
153         }
154         for _ in 0..20 {
155             let mut input = vec![];
156             for _ in 0..2000 {
157                 input.extend_from_slice(r.choose(&words).unwrap());
158             }
159             let cmp = deflate_bytes(&input);
160             let out = inflate_bytes(&cmp).unwrap();
161             assert_eq!(&*input, &*out);
162         }
163     }
164
165     #[test]
166     fn test_zlib_flate() {
167         let bytes = vec![1, 2, 3, 4, 5];
168         let deflated = deflate_bytes(&bytes);
169         let inflated = inflate_bytes(&deflated).unwrap();
170         assert_eq!(&*inflated, &*bytes);
171     }
172 }