Class: Cabriolet::Compressors::LZSS

Inherits:
Base
  • Object
show all
Defined in:
lib/cabriolet/compressors/lzss.rb

Overview

LZSS compressor for creating LZSS-compressed data

LZSS (Lempel-Ziv-Storer-Szymanski) is a derivative of LZ77 compression. It uses a 4096-byte sliding window with a control byte mechanism to indicate whether the next operation is a literal byte copy or a match from the window history.

The compression algorithm searches for matching sequences in the sliding window and encodes them as (offset, length) pairs when the match is 3 or more bytes. Shorter sequences are encoded as literal bytes.

Constant Summary collapse

WINDOW_SIZE =

LZSS algorithm constants

4096
WINDOW_FILL =
0x20
MIN_MATCH =
3
MAX_MATCH =

0x0F + 3

18
MODE_EXPAND =

LZSS modes

0
MODE_MSHELP =
1
MODE_QBASIC =
2

Instance Attribute Summary collapse

Attributes inherited from Base

#buffer_size, #input, #io_system, #output

Instance Method Summary collapse

Constructor Details

#initialize(io_system, input, output, buffer_size, mode = MODE_EXPAND) ⇒ LZSS

Initialize LZSS compressor

Parameters:



36
37
38
39
40
41
42
43
# File 'lib/cabriolet/compressors/lzss.rb', line 36

def initialize(io_system, input, output, buffer_size,
               mode = MODE_EXPAND)
  super(io_system, input, output, buffer_size)
  @mode = mode
  @window = Array.new(WINDOW_SIZE, WINDOW_FILL)
  @window_pos = initialize_window_position
  @invert = mode == MODE_MSHELP ? 0xFF : 0x00
end

Instance Attribute Details

#modeObject (readonly)

Returns the value of attribute mode.



27
28
29
# File 'lib/cabriolet/compressors/lzss.rb', line 27

def mode
  @mode
end

#windowObject (readonly)

Returns the value of attribute window.



27
28
29
# File 'lib/cabriolet/compressors/lzss.rb', line 27

def window
  @window
end

#window_posObject (readonly)

Returns the value of attribute window_pos.



27
28
29
# File 'lib/cabriolet/compressors/lzss.rb', line 27

def window_pos
  @window_pos
end

Instance Method Details

#compressInteger

Compress input data using LZSS algorithm

Returns:

  • (Integer)

    Number of bytes written



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/cabriolet/compressors/lzss.rb', line 48

def compress
  bytes_written = 0
  input_data = read_all_input
  input_pos = 0

  while input_pos < input_data.bytesize
    control_byte, encoded_ops, input_pos = process_block(
      input_data,
      input_pos,
    )
    bytes_written += write_block(control_byte, encoded_ops)
  end

  bytes_written
end