Okay, the go-to crate for using Zstandard compression in Rust without relying on the C libzstd library is rs-zstd. It's a pure Rust implementation.
Here's how you can use it:
1. Add rs-zstd to your Cargo.toml:
[dependencies]
rs-zstd = "0.7" # Check crates.io for the latest version
2. Basic Usage (In-Memory Compression/Decompression):
This is suitable for smaller amounts of data that can fit entirely in memory.
use rs_zstd;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let original_data = b"This is a test string. It will be compressed using pure Rust Zstandard!";
println!("Original size: {}", original_data.len());
// --- Compression ---
// compress_to_vec compresses data using default settings (or specify level)
// let compressed_data = rs_zstd::zstd_compress(original_data)?; // Default level
let compressed_data = rs_zstd::zstd_compress_e(original_data, 3)?; // Level 3 compression
println!("Compressed size: {}", compressed_data.len());
// println!("Compressed data: {:?}", compressed_data); // Uncomment to see bytes
// --- Decompression ---
// decompress_from_vec decompresses data
let decompressed_data = rs_zstd::zstd_decompress(&compressed_data)?;
println!("Decompressed size: {}", decompressed_data.len());
// --- Verification ---
assert_eq!(original_data, decompressed_data.as_slice());
println!("Successfully compressed and decompressed!");
Ok(())
}
Explanation:
rs_zstd::zstd_compress_e(data, level): Compresses the input byte slice (data) using the specified compression level. Levels typically range from 1 (fastest) to 22 (best compression). You can also use constants like rs_zstd::zstd_level_fast() or rs_zstd::zstd_level_best(). It returns a Vec<u8> containing the compressed data.
rs_zstd::zstd_decompress(compressed_data): Takes a byte slice containing zstd-compressed data and returns a Vec<u8> with the decompressed output.
- Error Handling: Both functions return
Result types, so you need to handle potential errors (e.g., invalid compressed data).
3. Streaming Usage (For Larger Data / IO):
For larger data or when working with files or network streams, using the streaming API is more efficient as it avoids loading everything into memory at once.
use rs_zstd::stream::{copy_encode, copy_decode};
use std::io::{Cursor, Read, Write}; // Using Cursor for in-memory example
fn main() -> Result<(), Box<dyn std::error::Error>> {
let original_data = b"This is a larger test string designed for streaming compression and decompression using rs-zstd.";
println!("Original size: {}", original_data.len());
// --- Compression ---
let mut compressed_output = Vec::new();
// Use Cursor as a Read/Write target for in-memory operations
let mut reader = Cursor::new(original_data);
let mut writer = Cursor::new(&mut compressed_output);
// copy_encode takes a reader, a writer, and a compression level
let compressed_size = copy_encode(&mut reader, &mut writer, 3)?; // Level 3
println!("Compressed size (streaming): {}", compressed_size);
// compressed_output now holds the compressed data
// --- Decompression ---
let mut decompressed_output = Vec::new();
let mut compressed_reader = Cursor::new(&compressed_output); // Read from compressed data
let mut decompressed_writer = Cursor::new(&mut decompressed_output); // Write decompressed data
// copy_decode takes a reader (compressed) and a writer (decompressed)
let decompressed_size = copy_decode(&mut compressed_reader, &mut decompressed_writer)?;
println!("Decompressed size (streaming): {}", decompressed_size);
// --- Verification ---
assert_eq!(original_data, decompressed_output.as_slice());
println!("Successfully streamed compression and decompression!");
Ok(())
}
Explanation:
rs_zstd::stream::copy_encode: Takes a Read source, a Write destination, and a compression level. It reads from the source, compresses, and writes to the destination, handling the Zstandard framing internally.
rs_zstd::stream::copy_decode: Takes a Read source (compressed data), a Write destination (decompressed data), and handles the decompression process.
std::io::Cursor: Used here to treat a Vec<u8> (like original_data or compressed_output) as if it were a file or stream, satisfying the Read and Write traits needed by the copy_encode/copy_decode functions.
Key Advantages of rs-zstd:
- Pure Rust: No need to install C compilers, development headers, or link against
libzstd. This simplifies cross-compilation and deployment.
- Modern Rust: Integrates well with Rust's ecosystem (e.g.,
async/await support is available via features or other related crates if needed, though the core rs-zstd is synchronous).
- Good Performance: While potentially not quite as fast as the highly optimized C implementation in all scenarios,
rs-zstd offers very competitive performance for a pure Rust solution.
Alternative (with C dependency):
The flate2 crate is the standard for gzip/deflate in Rust and also supports Zstandard via its "zstd" feature. However, this feature typically requires linking against the C libzstd library, so it does not meet your requirement of avoiding C dependencies.
# Cargo.toml - THIS HAS C DEPENDENCIES FOR ZSTD
# [dependencies]
# flate2 = { version = "1.0", features = ["zstd"] }
Therefore, stick with rs-zstd for a pure Rust solution.