]> git.proxmox.com Git - rustc.git/blob - src/libflate/lib.rs
New upstream version 1.19.0+dfsg3
[rustc.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 #![cfg_attr(stage0, 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 #![cfg_attr(stage0, 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.as_ptr(), self.len) }
66 }
67 }
68
69 impl Drop for Bytes {
70 fn drop(&mut self) {
71 unsafe {
72 libc::free(self.ptr.as_ptr() as *mut _);
73 }
74 }
75 }
76
77 extern "C" {
78 /// Raw miniz compression function.
79 fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
80 src_buf_len: size_t,
81 pout_len: *mut size_t,
82 flags: c_int)
83 -> *mut c_void;
84
85 /// Raw miniz decompression function.
86 fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
87 src_buf_len: size_t,
88 pout_len: *mut size_t,
89 flags: c_int)
90 -> *mut c_void;
91 }
92
93 const LZ_FAST: c_int = 0x01; // LZ with 1 probe, "fast"
94 const TDEFL_GREEDY_PARSING_FLAG: c_int = 0x04000; // fast greedy parsing instead of lazy parsing
95
96 /// Compress a buffer without writing any sort of header on the output. Fast
97 /// compression is used because it is almost twice as fast as default
98 /// compression and the compression ratio is only marginally worse.
99 pub fn deflate_bytes(bytes: &[u8]) -> Bytes {
100 let flags = LZ_FAST | TDEFL_GREEDY_PARSING_FLAG;
101 unsafe {
102 let mut outsz: size_t = 0;
103 let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
104 bytes.len() as size_t,
105 &mut outsz,
106 flags);
107 assert!(!res.is_null());
108 Bytes {
109 ptr: Unique::new(res as *mut u8),
110 len: outsz as usize,
111 }
112 }
113 }
114
115 /// Decompress a buffer without parsing any sort of header on the input.
116 pub fn inflate_bytes(bytes: &[u8]) -> Result<Bytes, Error> {
117 let flags = 0;
118 unsafe {
119 let mut outsz: size_t = 0;
120 let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
121 bytes.len() as size_t,
122 &mut outsz,
123 flags);
124 if !res.is_null() {
125 Ok(Bytes {
126 ptr: Unique::new(res as *mut u8),
127 len: outsz as usize,
128 })
129 } else {
130 Err(Error::new())
131 }
132 }
133 }
134
135 #[cfg(test)]
136 mod tests {
137 #![allow(deprecated)]
138 use super::{deflate_bytes, inflate_bytes};
139 use std::__rand::{Rng, thread_rng};
140
141 #[test]
142 fn test_flate_round_trip() {
143 let mut r = thread_rng();
144 let mut words = vec![];
145 for _ in 0..20 {
146 let range = r.gen_range(1, 10);
147 let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
148 words.push(v);
149 }
150 for _ in 0..20 {
151 let mut input = vec![];
152 for _ in 0..2000 {
153 input.extend_from_slice(r.choose(&words).unwrap());
154 }
155 let cmp = deflate_bytes(&input);
156 let out = inflate_bytes(&cmp).unwrap();
157 assert_eq!(&*input, &*out);
158 }
159 }
160
161 #[test]
162 fn test_zlib_flate() {
163 let bytes = vec![1, 2, 3, 4, 5];
164 let deflated = deflate_bytes(&bytes);
165 let inflated = inflate_bytes(&deflated).unwrap();
166 assert_eq!(&*inflated, &*bytes);
167 }
168 }