1use InflateStream;
14
15fn inflate(inflater: &mut InflateStream, data: &[u8]) -> Result<Vec<u8>, String> {
16 let mut decoded = Vec::<u8>::new();
17
18 let mut n = 0;
19 loop {
20 let (num_bytes_read, bytes) = try!(inflater.update(&data[n..]));
21 if bytes.len() == 0 {
22 break;
23 }
24 n += num_bytes_read;
25 decoded.extend(bytes.iter().map(|v| *v));
26 }
27
28 Ok(decoded)
29}
30
31pub fn inflate_bytes(data: &[u8]) -> Result<Vec<u8>, String> {
35 inflate(&mut InflateStream::new(), data)
36}
37
38pub fn inflate_bytes_zlib(data: &[u8]) -> Result<Vec<u8>, String> {
42 inflate(&mut InflateStream::from_zlib(), data)
43}
44
45pub fn inflate_bytes_zlib_no_checksum(data: &[u8]) -> Result<Vec<u8>, String> {
50 inflate(&mut InflateStream::from_zlib_no_checksum(), data)
51}
52
53#[cfg(test)]
54mod test {
55 #[test]
56 fn inflate_bytes_with_zlib() {
57 use super::inflate_bytes_zlib;
58 use std::str::from_utf8;
59
60 let encoded = [120, 156, 243, 72, 205, 201, 201, 215, 81, 168, 202, 201,
61 76, 82, 4, 0, 27, 101, 4, 19];
62 let decoded = inflate_bytes_zlib(&encoded).unwrap();
63 assert!(from_utf8(&decoded).unwrap() == "Hello, zlib!");
64 }
65
66 #[test]
67 fn inflate_bytes_with_zlib_checksum_fail() {
68 use super::inflate_bytes_zlib;
69
70 let encoded = [120, 156, 243, 72, 205, 201, 201, 215, 81, 168, 202, 201,
73 76, 82, 4, 0, 0, 0, 0, 0];
74 inflate_bytes_zlib(&encoded).unwrap_err();
75 }
76
77 #[test]
78 fn inflate_bytes_with_zlib_trailing() {
79 use super::inflate_bytes_zlib;
80 use std::str::from_utf8;
81
82 let encoded = [120, 156, 243, 72, 205, 201, 201, 215, 81, 168, 202, 201,
84 76, 82, 4, 0, 27, 101, 4, 19, 0, 0, 0, 0];
85 let decoded = inflate_bytes_zlib(&encoded).unwrap();
86 assert!(from_utf8(&decoded).unwrap() == "Hello, zlib!");
87 }
88
89}