Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

Overview

This PR adds an implementation of the LZ77 compression algorithm to the compression module.

What is LZ77?

LZ77 is a lossless data compression algorithm published by Abraham Lempel and Jacob Ziv in 1977. It uses a sliding-window approach to identify repeated patterns and forms the basis for many modern compression formats including:

  • DEFLATE (used in gzip, PNG, ZIP)
  • LZSS
  • LZMA (7-Zip)
  • LZW (GIF)

Algorithm Details

LZ77 works by maintaining a sliding window divided into:

  • Search buffer: Previously seen data that can be referenced
  • Look-ahead buffer: Data currently being encoded

The algorithm encodes data as triplets (tokens):

  • Offset: Distance from current position to match start in search buffer
  • Length: Number of matching characters
  • Indicator: The next character after the match

Implementation Features

✅ Configurable window size and lookahead buffer size
✅ Token-based encoding using (offset, length, indicator) triplets
✅ Comprehensive test coverage (13+ test cases)
✅ Full rustdoc documentation with examples
✅ Zero external dependencies
✅ Efficient implementation with O(n²) worst-case complexity

API

// Create compressor with custom parameters
let compressor = LZ77Compressor::new(window_size, lookahead_buffer_size);

// Compress text to tokens
let compressed: Vec<Token> = compressor.compress("ababcbababaa");

// Decompress tokens back to text
let decompressed: String = compressor.decompress(&compressed);

Code Quality

  • ✅ All tests pass (cargo test)
  • ✅ Zero clippy warnings (cargo clippy -- -D warnings)
  • ✅ Properly formatted (cargo fmt)
  • ✅ Comprehensive documentation with examples
  • ✅ Follows repository conventions

Files Modified

  • src/compression/lz77.rs (new file, ~280 lines)
  • src/compression/mod.rs (added module declaration and re-exports)

Testing

The implementation includes extensive tests:

  • ✅ Basic compression/decompression
  • ✅ Round-trip verification with multiple inputs
  • ✅ Edge cases (single character, empty buffers)
  • ✅ Error conditions (invalid parameters)
  • ✅ All examples from the original Python implementation

Example Usage

use the_algorithms_rust::compression::{LZ77Compressor, Token};

fn main() {
    let compressor = LZ77Compressor::new(13, 6);
    
    // Compress
    let text = "cabracadabrarrarrad";
    let compressed = compressor.compress(text);
    println!("Compressed into {} tokens", compressed.len());
    
    // Decompress
    let decompressed = compressor.decompress(&compressed);
    assert_eq!(text, decompressed);
}

Compression Examples

Input: "ababcbababaa"
Compressed: [(0,0,'a'), (0,0,'b'), (2,2,'c'), (4,3,'a'), (2,2,'a')]

Input: "aacaacabcabaaac"
Compressed: [(0,0,'a'), (1,1,'c'), (3,4,'b'), (3,3,'a'), (1,2,'c')]

Input: "cabracadabrarrarrad"
Compressed: [(0,0,'c'), (0,0,'a'), (0,0,'b'), (0,0,'r'), (3,1,'c'), 
             (2,1,'d'), (7,4,'r'), (3,5,'d')]

References

  • Wikipedia: LZ77 and LZ78
  • Original paper: Ziv, J.; Lempel, A. (1977). "A Universal Algorithm for Sequential Data Compression"

Checklist

  • Code follows project style guidelines
  • All tests pass (cargo test)
  • Code is properly formatted (cargo fmt)
  • No clippy warnings (cargo clippy -- -D warnings)
  • Documentation is complete with examples
  • Module properly exported in mod.rs
  • Algorithm tested with edge cases
  • Doctests compile and pass

Note: This implementation prioritizes clarity and correctness over raw performance. While the algorithm has O(n²) worst-case complexity, it's suitable for educational purposes and moderate-sized inputs. Production implementations often use hash tables or suffix arrays for optimization.

@AliAlimohammadi
Copy link
Contributor Author

@siriak, this is ready to be merged.

@codecov-commenter
Copy link

codecov-commenter commented Dec 30, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.77%. Comparing base (ea93ffd) to head (1033ee6).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #982      +/-   ##
==========================================
+ Coverage   95.73%   95.77%   +0.03%     
==========================================
  Files         352      353       +1     
  Lines       23166    23363     +197     
==========================================
+ Hits        22179    22375     +196     
- Misses        987      988       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@siriak
Copy link
Member

siriak commented Dec 30, 2025

Please resolve the conflicts

@AliAlimohammadi
Copy link
Contributor Author

Please resolve the conflicts

Fixed.

@siriak siriak merged commit ba7ca98 into TheAlgorithms:master Dec 30, 2025
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-lz77-compression branch December 30, 2025 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants