Zeckendorf Compression
A Rust library for compressing and decompressing data using the Zeckendorf representation algorithm.
Overview
The Zeckendorf algorithm represents numbers as a sum of non-consecutive Fibonacci numbers. This library interprets input data as a big integer (either big-endian or little-endian), converts it to its Zeckendorf representation, and sometimes achieves compression. However, compression is not guaranteed; the algorithm may result in a larger representation depending on the input data. The library can automatically try both endian interpretations and select the one that produces the best compression.
⚠️ Warning: Compressing or decompressing files larger than 10KB (10,000 bytes) is unstable due to time and memory pressure. The library may experience performance issues, excessive memory usage, or failures when processing files exceeding this size.
Command-line tools (zeck-compress and zeck-decompress) are available and can be installed via cargo install zeck. See the Binaries section for usage details.
Features
- Compression & Decompression: Convert data to/from Zeckendorf representation
- File Format with Headers:
.zeckfile format that automatically preserves original file size and endianness information - Multiple Endian Interpretations: Support for both big-endian and little-endian input interpretations
- Automatic Best Compression: Try both endian interpretations and automatically select the best result
- Multiple Fibonacci Algorithms:
- Slow recursive (memoized, for small numbers)
- Slow iterative (memoized, for large numbers)
- Fast Doubling (optimized, ~160x faster for large indices)
- Memoized Fast Doubling (with sparse HashMap caching for large, non-contiguous indices)
- BigInt Support: Handle arbitrarily large numbers using
num-bigint - Memoization: Thread-safe caching for improved performance
- Statistics & Visualization: Generate compression statistics and plots
- Benchmarking: Comprehensive performance benchmarks
- WebAssembly Support: Available as a WebAssembly module for use in web browsers
- Error Handling: Comprehensive error types for file format operations
WebAssembly
This library is also available as a WebAssembly module for use in web browsers and JavaScript/TypeScript projects. The WebAssembly module can be installed via npm:
Available functions are marked with the #[wasm_bindgen] attribute. The WebAssembly module can also be built manually using the convenience script at scripts/build_wasm_bundle.sh that builds the WebAssembly module with the wasm-pack tool.
You can see a live demo of the WebAssembly module in action at https://prizz.github.io/zeckendorf-webapp/. The source code for the demo is available at https://github.com/pRizz/zeckendorf-webapp.
Installation
Install from crates.io
Run:
Or add this to your Cargo.toml:
[]
= "2.1.0"
Features:
cli_tools: Enables thezeck-compressandzeck-decompresscommand-line binaries. This feature includes theclapdependency. Not enabled by default - use--features cli_toolswhen installing binaries.
For CLI tools (when installing binaries):
[]
= { = "2.1.0", = ["cli_tools"] }
Install from GitHub (development version)
Run:
Or add this to your Cargo.toml:
[]
= { = "https://github.com/pRizz/zeckendorf" }
For CLI tools:
[]
= { = "https://github.com/pRizz/zeckendorf", = ["cli_tools"] }
Install from npm
Run:
Or add this to your package.json:
Usage
File Format Compression (Recommended)
The .zeck file format automatically handles size preservation and endianness information. This is the recommended approach for most use cases.
Big-Endian File Format
use ;
// Compress data (interpreted as big-endian integer)
let data = vec!;
let zeck_file = compress_zeck_be?;
// Serialize to bytes for storage
let bytes = zeck_file.to_bytes;
// Later, deserialize and decompress
use deserialize_zeck_file;
let zeck_file = deserialize_zeck_file?;
let decompressed = decompress_zeck_file?;
assert_eq!;
Little-Endian File Format
use ;
// Compress data (interpreted as little-endian integer)
let data = vec!;
let zeck_file = compress_zeck_le?;
// Decompress data
let decompressed = decompress_zeck_file?;
assert_eq!;
Automatic Best Compression (File Format)
use ;
// Try both endian interpretations and get the best result
let data = vec!;
match compress_zeck_best?
Padless Compression (Advanced)
The padless compression functions strip leading zero bytes and do not preserve original size information. You must manually track the original size if you need to restore leading zeros. These functions are marked as _dangerous to indicate they require careful handling.
⚠️ Important: The padless functions are lower-level and do not preserve leading zero bytes. Use the file format functions above for most use cases.
Big-Endian Padless
use ;
// Compress data (interpreted as big-endian integer)
let data = vec!;
let compressed = padless_zeckendorf_compress_be_dangerous;
// Decompress data (leading zeros may be lost)
let decompressed = padless_zeckendorf_decompress_be_dangerous;
// Note: decompressed may not equal data if data had leading zeros
Little-Endian Padless
use ;
// Compress data (interpreted as little-endian integer)
let data = vec!;
let compressed = padless_zeckendorf_compress_le_dangerous;
// Decompress data (trailing zeros may be lost)
let decompressed = padless_zeckendorf_decompress_le_dangerous;
Automatic Best Padless Compression
use ;
let data = vec!;
match padless_zeckendorf_compress_best_dangerous
Fibonacci Numbers
use memoized_slow_fibonacci_recursive;
// Calculate Fibonacci numbers (for indices up to 93)
let fib_10 = memoized_slow_fibonacci_recursive; // Returns 55
// For larger numbers, use BigInt versions
use fast_doubling_fibonacci_biguint;
let fib_100 = fast_doubling_fibonacci_biguint;
// For even better performance with caching, use memoized fast doubling
use memoized_fast_doubling_fibonacci_biguint;
let fib_1000 = memoized_fast_doubling_fibonacci_biguint;
Zeckendorf Representation
use memoized_zeckendorf_list_descending_for_integer;
// Get Zeckendorf representation as a list of Fibonacci indices
let zld = memoized_zeckendorf_list_descending_for_integer;
// Returns [6, 4, 2] meaning F(6) + F(4) + F(2) = 8 + 3 + 1 = 12
// For BigInt numbers
use memoized_zeckendorf_list_descending_for_biguint;
use BigUint;
let zld = memoized_zeckendorf_list_descending_for_biguint;
Utility Functions
The library provides various utility functions for working with Fibonacci numbers and Zeckendorf representations:
use ;
Error Handling
The file format functions return Result types with comprehensive error handling:
use ;
match compress_zeck_be
Common error types include:
HeaderTooShort: Input data is too short to contain a valid headerUnsupportedVersion: File format version is not supportedReservedFlagsSet: Reserved flags are set (indicating a newer format)CompressionFailed: Compression did not reduce the data sizeDecompressedTooLarge: Decompressed data is larger than expectedDataSizeTooLarge: Data size exceeds the maximum representable size
Binaries
The project includes several utility binaries. The command-line compression tools (zeck-compress and zeck-decompress) can be installed globally via:
Install from crates.io
Install from GitHub (development version)
After installation, you can use zeck-compress and zeck-decompress directly from your command line.
Compression/Decompression Tools
⚠️ Warning: Compressing or decompressing files larger than 10KB (10,000 bytes) is unstable due to time and memory pressure. The library may experience performance issues, excessive memory usage, or failures when processing files exceeding this size.
zeck-compress
Compresses data using the Zeckendorf representation algorithm. Automatically adds .zeck extension for compressed files.
Options:
INPUT: Input file path (optional, reads from stdin if not specified)- Shows a warning if reading from stdin and no data was piped in
-o, --output FILE: Output file path (optional)- If not specified and input is a file, uses the input filename with the
.zeckextension appended - If not specified and reading from stdin, writes to stdout
- The
.zeckextension is automatically added unless the file already ends with.zeck
- If not specified and input is a file, uses the input filename with the
--endian ENDIAN: Endianness to use (big,little, orbest). Default:bestbig: Use big-endian interpretationlittle: Use little-endian interpretationbest: Try both and use the best result (default)- Note: When using
best, if neither method produces compression (both result in larger or equal output), the tool will exit with an error showing compression statistics
-v, --verbose: Show compression statistics (default: true, use--no-verboseto disable)
Examples:
# Compress a file (output filename automatically created from input with extension)
# Creates input.bin.zeck
# Compress with best endianness (statistics shown by default)
# Compress with specific endianness
# Compress to a specific output file
# Creates output.zeck
# Compress from stdin to stdout
|
Note: When writing to a file, the output filename is printed to stdout (e.g., "Compressed to: input.bin.zeck"). Verbose statistics are shown by default and include descriptive messages about compression ratios (e.g., "File was compressed by X.XX% (Y bytes -> Z bytes)"). A warning is shown when reading from stdin if no data was piped in.
zeck-decompress
Decompresses data that was compressed using the Zeckendorf representation algorithm. Automatically detects endianness from the file header.
Options:
INPUT: Input file path (optional, reads from stdin if not specified)- When reading from a file, endianness is automatically detected from the file header
- When reading from stdin, endianness is automatically detected from the file header
- Shows a warning if reading from stdin and no data was piped in
-o, --output FILE: Output file path (optional)- If not specified and input is a file, uses the input filename with
.zeckextension removed - If not specified and reading from stdin, writes to stdout
- If not specified and input is a file, uses the input filename with
-v, --verbose: Show decompression statistics (default: true, use--no-verboseto disable)
Examples:
# Decompress a file (endianness detected from file header, output filename automatically created)
# Automatically detects endianness from header, creates output file "input"
# Decompress to a specific output file
# Automatically detects endianness from header
# Decompress from stdin to stdout
|
# Automatically detects endianness from header
Note: The endianness used for decompression must match the endianness used during compression. The file header stores which endianness was used, so decompression will automatically use the correct endianness when reading from a file or from stdin.
Additional features:
- When writing to a file, the output filename is printed to stdout (e.g., "Compressed to: input.bin.zeck" or "Decompressed to: output.bin")
- Verbose statistics are shown by default (use
--no-verboseto disable) and include descriptive messages about compression/decompression ratios - Compression will exit with an error if the data cannot be compressed (when using
--endian bestand neither method produces compression) - A warning is shown when reading from stdin if no data was piped in
Main Playground
A playground/scratchpad for testing library functions.
Generate Test Data
Generates random test data files in the generated_data/ directory.
Example:
Generate Statistics
Generates comprehensive compression statistics and plots:
- Compression ratios across different input sizes
- Chance of compression being favorable
- Average and median compression ratios
- Statistics saved to
statistics_history/directory - Plots saved to
plots/directory
Plot Compression Ratios
Generates visualization plots of:
- Fibonacci numbers
- Compression ratios for various input ranges
Benchmarks
Zeckendorf Compression Benchmarks
Benchmarks compression, decompression, and round-trip performance for various data sizes (4 bytes to 16KB).
Fibonacci Benchmarks
Compares performance of different Fibonacci calculation algorithms:
- Slow iterative method
- Fast doubling method (~160x faster for large indices)
Working with Benchmark Baselines
Save a new baseline:
Compare to an existing baseline:
Performance Characteristics
- Fast Doubling Fibonacci: ~160x faster than iterative method for the 100,000th Fibonacci number
- Memoized Fast Doubling: Uses sparse HashMap caching for efficient memory usage with large, non-contiguous Fibonacci indices
- Memoization: Thread-safe caching significantly improves repeated calculations. The trade-off is that the cache takes up memory.
- Compression Effectiveness: Varies by input; compression ratios oscillate and become less favorable as input size increases
Algorithm Details
Zeckendorf Representation
Every positive integer can be uniquely represented as a sum of non-consecutive Fibonacci numbers. For example:
- 12 = 8 + 3 + 1 = F(6) + F(4) + F(2)
Compression Process
- Input data is interpreted as either a big-endian or little-endian integer (you can choose, or use
compress_zeck_bestto try both) - The integer is converted to its Zeckendorf representation (list of Fibonacci indices)
- The representation is encoded as bits (use/skip bits)
- Bits are packed into bytes (little-endian output)
The library provides functions to compress with either interpretation, or you can use compress_zeck_best to automatically try both and select the one that produces the smallest output.
File Format
The .zeck file format includes a 10-byte header:
- Version (1 byte): File format version (currently 1)
- Original Size (8 bytes): Original uncompressed file size in bytes (little-endian)
- Flags (1 byte): Endianness and reserved flags
- Bit 0: Big endian flag (1 = big endian, 0 = little endian)
- Bits 1-7: Reserved for future use
The header is followed by the compressed data. This format automatically preserves the original file size, allowing proper restoration of leading or trailing zero bytes during decompression.
Effective Fibonacci Indices
The library uses "Effective Fibonacci Indices" (EFI) starting from 0, where:
- EFI 0 = Fibonacci Index 2 (value 1)
- EFI 1 = Fibonacci Index 3 (value 2)
- etc.
This avoids redundant Fibonacci numbers (F(0)=0 and F(1)=F(2)=1).
Limitations
- Compression is not guaranteed—some inputs may result in larger output
- Compression effectiveness decreases as input size increases
- The library supports both big-endian and little-endian interpretations, but other byte orderings or word boundaries are not currently explored
- ⚠️ Warning: Compressing or decompressing files larger than 10KB (10,000 bytes) is unstable due to time and memory pressure. The library may experience performance issues, excessive memory usage, or failures when processing files exceeding this size.
- Padless compression functions (
*_dangerous) do not preserve leading/trailing zero bytes—use the file format functions for automatic size preservation
NPM Versioning Quirk
For some reason, NPM was showing there were versions of zeck published between 1.0.0 and 1.0.6 from 2024 (we are in 2026), even though I never published them to npm. I don't know how this happened. So I bumped the version to 1.0.7 and was able to successfully publish it to npm. Maybe there was an old package with the same name that was deleted, and NPM is still showing the old versions.
Here is a snippet of the time object from the npm registry JSON (https://registry.npmjs.org/zeck):
"time": ,
License
This project is licensed under the MIT License - see the LICENSE.txt file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
References
- Fast Fibonacci Algorithms - Fast doubling algorithm reference
- Zeckendorf's Theorem - Every positive integer has a unique representation as a sum of non-consecutive Fibonacci numbers
- Exploring Fibonacci Based Compression - My blog post about the Zeckendorf representation algorithm and this library