zigzag-rs
A dependency-free (including no std) ZigZag encoding/decoding Rust library. ZigZag encoding is a method for mapping signed integers to unsigned integers, commonly used in variable-length encoding and data compression.
Features
- Completely dependency-free, usable in
#![no_std]environments - Supports all Rust native signed integer types (i8, i16, i32, i64, i128)
- Simple and easy-to-use API with both single value and batch processing
- Iterator-based API for memory-constrained environments
- Efficient implementation optimized for embedded systems
- Error handling with Result types for robust application development
Usage
Add the dependency to your Cargo.toml:
[]
= "0.2.1"
Single value encoding/decoding
use ZigZag;
// Encoding
let encoded = i32zigzag_encode;
assert_eq!;
// Decoding
let decoded = i32zigzag_decode;
assert_eq!;
Batch processing
use ZigZag;
// Prepare data
let values = ;
let mut encoded = ;
let mut decoded = ;
// Encode a slice of values
i32zigzag_encode_slice;
// Decode a slice of values
i32zigzag_decode_slice;
// Verify round-trip conversion
assert_eq!;
Iterator-based API
The library provides an iterator-based API that encodes or decodes values on-the-fly as the iterator is consumed, without requiring an intermediate buffer:
use ;
// Source data
let values = ;
// Create an iterator that encodes values on-demand
let encoded_iter = ;
// Process encoded values without allocating a buffer
for in values.iter.zip
// For decoding
let encoded_values = ;
let decoded_iter = ;
// Process decoded values one at a time
for decoded in decoded_iter
This approach is particularly useful in memory-constrained environments like embedded systems.
Error handling
The library provides error handling variants of the batch processing functions:
use ZigZag;
let values = ;
let mut encoded = ;
// Try to encode, but return a Result instead of panicking if the buffer is too small
let result = i32try_zigzag_encode_slice;
if let Err = result
ZigZag Encoding Principle
ZigZag encoding maps signed integers to unsigned integers as follows:
- 0 -> 0
- -1 -> 1
- 1 -> 2
- -2 -> 3
- 2 -> 4 ...
This encoding method ensures that small absolute values (whether positive or negative) are mapped to small unsigned integers, which is ideal for subsequent variable-length encoding.
Performance
The implementation is optimized for both single value processing and batch operations, making it suitable for resource-constrained environments like embedded systems.
License
MIT or Apache-2.0 (dual licensed)