File: zlib_tokio_write.rs

package info (click to toggle)
rust-async-compression 0.4.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 928 kB
  • sloc: makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,090 bytes parent folder | download
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
35
//! Run this example with the following command in a terminal:
//!
//! ```console
//! $ cargo run --example zlib_tokio_write --features="tokio,zlib"
//! "example"
//! ```

use std::io::Result;

use async_compression::tokio::write::{ZlibDecoder, ZlibEncoder};
use tokio::io::AsyncWriteExt as _; // for `write_all` and `shutdown`

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    let data = b"example";
    let compressed_data = compress(data).await?;
    let de_compressed_data = decompress(&compressed_data).await?;
    assert_eq!(de_compressed_data, data);
    println!("{:?}", String::from_utf8(de_compressed_data).unwrap());
    Ok(())
}

async fn compress(in_data: &[u8]) -> Result<Vec<u8>> {
    let mut encoder = ZlibEncoder::new(Vec::new());
    encoder.write_all(in_data).await?;
    encoder.shutdown().await?;
    Ok(encoder.into_inner())
}

async fn decompress(in_data: &[u8]) -> Result<Vec<u8>> {
    let mut decoder = ZlibDecoder::new(Vec::new());
    decoder.write_all(in_data).await?;
    decoder.shutdown().await?;
    Ok(decoder.into_inner())
}