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