Skip to content

Rust Platform

JSON Packer's Rust core library provides lightweight, reversible JSON binary compression functionality.

Installation

bash
cargo add json-packer

Or add the dependency in Cargo.toml:

toml
[dependencies]
json-packer = "0.1.0"

API

Core Functions

rust
// Compress / Decompress (bytes)
pub fn compress_to_bytes(value: &serde_json::Value, opts: &CompressOptions) -> Result<Vec<u8>, Error>;
pub fn decompress_from_bytes(bytes: &[u8]) -> Result<serde_json::Value, Error>;

// Compress / Decompress (Base64)
pub fn compress_to_base64(value: &serde_json::Value, opts: &CompressOptions) -> Result<String, Error>;
pub fn decompress_from_base64(s: &str) -> Result<serde_json::Value, Error>;

Configuration Options

rust
#[derive(Clone, Debug)]
pub struct CompressOptions {
    pub enable_value_pool: bool,     // Enable string value pool (default false)
    pub pool_min_repeats: u32,       // Minimum repetitions for value pool (default 3)
    pub pool_min_string_len: usize,  // Minimum string length for value pool (default 8)
}

Examples

Basic Compression

rust
use json_packer::{compress_to_base64, decompress_from_base64, CompressOptions};
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let data = json!({
        "ok": true,
        "count": 42,
        "name": "Alice"
    });

    // Compress
    let compressed = compress_to_base64(&data, &CompressOptions::default())?;
    println!("Compressed result: {}", compressed);

    // Decompress
    let decompressed = decompress_from_base64(&compressed)?;
    assert_eq!(data, decompressed);
    
    println!("Data integrity verification passed!");
    Ok(())
}

Enable String Value Pool

rust
use json_packer::{compress_to_bytes, decompress_from_bytes, CompressOptions};
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let options = CompressOptions {
        enable_value_pool: true,    // Enable string value pool
        pool_min_repeats: 3,        // Minimum repetitions
        pool_min_string_len: 8,     // Minimum string length
    };

    let data = json!({
        "items": [
            {"status": "connected", "message": "connected to server"},
            {"status": "connected", "message": "connected to server"},
            {"status": "connected", "message": "connected to server"}
        ]
    });

    // Compress (enabling value pool automatically uses v2 format)
    let compressed = compress_to_bytes(&data, &options)?;
    
    // Decompress
    let decompressed = decompress_from_bytes(&compressed)?;
    assert_eq!(data, decompressed);

    println!("Original size: {} bytes", serde_json::to_string(&data)?.len());
    println!("Compressed size: {} bytes", compressed.len());
    println!("Compression ratio: {:.1}%", 
        (1.0 - compressed.len() as f64 / serde_json::to_string(&data)?.len() as f64) * 100.0);

    Ok(())
}

Released under the MIT License