Expand description
§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:
[dependencies]
zigzag-rs = "0.2.0"Example code:
use zigzag_rs::ZigZag;
fn main() {
// Single value encoding/decoding
let encoded = i32::zigzag_encode(-1);
assert_eq!(encoded, 1u32);
let decoded = i32::zigzag_decode(1u32);
assert_eq!(decoded, -1i32);
// Batch processing
let values = [-10, -1, 0, 1, 10];
let mut encoded = [0u32; 5];
i32::zigzag_encode_slice(&values, &mut encoded);
let mut decoded = [0i32; 5];
i32::zigzag_decode_slice(&encoded, &mut decoded);
assert_eq!(values, decoded);
// Using Result-based error handling
let values = [-10, -1, 0, 1, 10];
let mut encoded = [0u32; 5];
let result = i32::try_zigzag_encode_slice(&values, &mut encoded);
assert!(result.is_ok());
// Using iterator-based API
let values = [-10, -1, 0, 1, 10];
// Encode each value on the fly without allocating a buffer
let encoded_iter = zigzag_rs::zigzag_encode_iter::<i32, _>(values.iter());
// The values are encoded only when the iterator is consumed
for (original, encoded) in values.iter().zip(encoded_iter) {
assert_eq!(encoded, i32::zigzag_encode(*original));
}
}§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.
Enums§
- ZigZag
Error - Error type for ZigZag operations
Traits§
- ZigZag
- Trait for ZigZag encoding, used to convert signed integers to unsigned integers
Functions§
- zigzag_
decode_ iter - Creates an iterator that decodes each unsigned integer from the source iterator.
- zigzag_
encode_ iter - Creates an iterator that encodes each signed integer from the source iterator.