]> git.lizzy.rs Git - rust.git/blob - src/libflate/lib.rs
Register new snapshots
[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 /*!
12
13 Simple [DEFLATE][def]-based compression. This is a wrapper around the
14 [`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
15
16 [def]: https://en.wikipedia.org/wiki/DEFLATE
17 [mz]: https://code.google.com/p/miniz/
18
19 */
20
21 #![crate_id = "flate#0.11.0-pre"]
22 #![crate_type = "rlib"]
23 #![crate_type = "dylib"]
24 #![license = "MIT/ASL2"]
25 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
26        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
27        html_root_url = "http://doc.rust-lang.org/")]
28 #![feature(phase)]
29
30 #[cfg(test)] #[phase(plugin, link)] extern crate log;
31
32 extern crate libc;
33
34 use std::c_vec::CVec;
35 use libc::{c_void, size_t, c_int};
36
37 #[link(name = "miniz", kind = "static")]
38 extern {
39     /// Raw miniz compression function.
40     fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
41                                       src_buf_len: size_t,
42                                       pout_len: *mut size_t,
43                                       flags: c_int)
44                                       -> *mut c_void;
45
46     /// Raw miniz decompression function.
47     fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
48                                         src_buf_len: size_t,
49                                         pout_len: *mut size_t,
50                                         flags: c_int)
51                                         -> *mut c_void;
52 }
53
54 static LZ_NORM : c_int = 0x80;  // LZ with 128 probes, "normal"
55 static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
56 static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
57
58 fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
59     unsafe {
60         let mut outsz : size_t = 0;
61         let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
62                                                      bytes.len() as size_t,
63                                                      &mut outsz,
64                                                      flags);
65         if !res.is_null() {
66             Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
67         } else {
68             None
69         }
70     }
71 }
72
73 /// Compress a buffer, without writing any sort of header on the output.
74 pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
75     deflate_bytes_internal(bytes, LZ_NORM)
76 }
77
78 /// Compress a buffer, using a header that zlib can understand.
79 pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
80     deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
81 }
82
83 fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
84     unsafe {
85         let mut outsz : size_t = 0;
86         let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
87                                                        bytes.len() as size_t,
88                                                        &mut outsz,
89                                                        flags);
90         if !res.is_null() {
91             Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
92         } else {
93             None
94         }
95     }
96 }
97
98 /// Decompress a buffer, without parsing any sort of header on the input.
99 pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
100     inflate_bytes_internal(bytes, 0)
101 }
102
103 /// Decompress a buffer that starts with a zlib header.
104 pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
105     inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
106 }
107
108 #[cfg(test)]
109 mod tests {
110     use super::{inflate_bytes, deflate_bytes};
111     use std::rand;
112     use std::rand::Rng;
113
114     #[test]
115     fn test_flate_round_trip() {
116         let mut r = rand::task_rng();
117         let mut words = vec!();
118         for _ in range(0, 20) {
119             let range = r.gen_range(1u, 10);
120             let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
121             words.push(v);
122         }
123         for _ in range(0, 20) {
124             let mut input = vec![];
125             for _ in range(0, 2000) {
126                 input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
127             }
128             debug!("de/inflate of {} bytes of random word-sequences",
129                    input.len());
130             let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
131             let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
132             debug!("{} bytes deflated to {} ({:.1f}% size)",
133                    input.len(), cmp.len(),
134                    100.0 * ((cmp.len() as f64) / (input.len() as f64)));
135             assert_eq!(input.as_slice(), out.as_slice());
136         }
137     }
138
139     #[test]
140     fn test_zlib_flate() {
141         let bytes = vec!(1, 2, 3, 4, 5);
142         let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
143         let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
144         assert_eq!(inflated.as_slice(), bytes.as_slice());
145     }
146 }