Last active
November 28, 2023 21:24
-
-
Save Jerboa-app/43ce8818d476d73350a7dc4e7fc717af to your computer and use it in GitHub Desktop.
Rust (libflate) compress and decompress string data in memory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::io::{Write, Read}; | |
| use libflate::deflate::{Encoder, Decoder}; | |
| const A_STRING: &str = "This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed."; | |
| fn main() { | |
| println!("The original data: {}\n", A_STRING); | |
| let mut encoder = Encoder::new(Vec::new()); | |
| encoder.write_all(A_STRING.as_bytes()).unwrap(); | |
| let encoded_data = encoder.finish().into_result().unwrap(); | |
| println!("Compressed/raw sizes: {}/{}\n Compressed data: {:?}\n", encoded_data.len(), A_STRING.as_bytes().len(), encoded_data); | |
| let mut decoder = Decoder::new(&encoded_data[..]); | |
| let mut decoded_data = Vec::new(); | |
| decoder.read_to_end(&mut decoded_data).unwrap(); | |
| let s = std::str::from_utf8(&decoded_data).unwrap(); | |
| println!("uncompressed: {:?}, data: {}", decoded_data, s); | |
| } | |
| /* | |
| The original data: This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed. | |
| Compressed/raw sizes: 49/163 | |
| Compressed data: [197, 202, 65, 13, 0, 32, 8, 5, 208, 42, 63, 129, 105, 44, 128, 202, 132, 131, 232, 128, 254, 211, 22, 110, 239, 248, 170, 104, 224, 33, 68, 186, 218, 68, 10, 37, 58, 25, 26, 163, 239, 117, 156, 35, 120, 20, 252, 139, 23] | |
| uncompressed: [84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 116, 114, 105, 110, 103, 32, 116, 104, 97, 116, 32, 99, 97, 110, 32, 98, 101, 32, 99, 111, 109, 112, 114, 101, 115, 115, 101, 100, 46, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 116, 114, 105, 110, 103, 32, 116, 104, 97, 116, 32, 99, 97, 110, 32, 98, 101, 32, 99, 111, 109, 112, 114, 101, 115, 115, 101, 100, 46, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 116, 114, 105, 110, 103, 32, 116, 104, 97, 116, 32, 99, 97, 110, 32, 98, 101, 32, 99, 111, 109, 112, 114, 101, 115, 115, 101, 100, 46, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 116, 114, 105, 110, 103, 32, 116, 104, 97, 116, 32, 99, 97, 110, 32, 98, 101, 32, 99, 111, 109, 112, 114, 101, 115, 115, 101, 100, 46], data: This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed. This is a string that can be compressed. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment