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