-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompression.rs
34 lines (28 loc) · 1.2 KB
/
compression.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::{fs::File, io::{Read, Write}, str};
use flate2::{read::ZlibDecoder, write::ZlibEncoder, Compression, GzBuilder};
fn main() {
let input_string = "blahblahblahblahblah";
println!("{}", input_string);
let input_bytes = input_string.as_bytes();
println!("Uncompressed length: {}", input_bytes.len());
// Compress the bytes directly into a .gz file
let f = File::create("compressed.gz").unwrap();
let mut gz = GzBuilder::new().write(f, Compression::best());
gz.write_all(input_bytes).unwrap();
gz.finish().unwrap();
// Compress the bytes
let mut compressor = ZlibEncoder::new(Vec::new(), Compression::best());
compressor.write_all(input_bytes).unwrap();
let output_bytes = compressor.finish().unwrap();
println!("Compressed length: {}", output_bytes.len());
// for byte in output_bytes.iter() {
// print!("{:02x?}", byte);
// }
// println!();
// Decompress the bytes
let mut decompressor = ZlibDecoder::new(&output_bytes[..]);
let mut result = [0u8; 100];
decompressor.read(&mut result[..]).unwrap(); // also decompressor.read_to_string()
// Decode the bytes to a str
println!("{}", str::from_utf8(&result).unwrap());
}