LZ77 Lite

medium · compression, lz77, dictionary

LZ77 Lite

Implement a greedy LZ77 compressor and decompressor.

Types

type Token struct {
    Literal  byte
    Length   int
    Distance int
    IsMatch  bool
}

func LZ77Compress(data []byte, window int, lookahead int) []Token
func LZ77Decompress(tokens []Token) []byte

Token rules

  • Literal: IsMatch=false, Literal set, Length=0, Distance=0.
  • Match: IsMatch=true, Length>=3, Distance>=1 (bytes back from current position).

Greedy matching

At each position:

  1. Search the previous window bytes for the longest match (up to lookahead).
  2. If multiple matches have the same length, pick the smallest distance.
  3. If the best length is < 3, emit a literal instead.

Notes

  • Overlapping copies are allowed during decompression.
  • If window <= 0 or lookahead <= 0, treat all input as literals.
Run tests to see results
No issues detected