Parent

Methods

Included Modules

Class/Module Index [+]

Quicksearch

Origami::Filter::RunLength

Class representing a Filter used to encode and decode data using RLE compression algorithm.

Public Instance Methods

decode(stream) click to toggle source

Decodes data using RLE decompression method.

stream

The data to decode.

# File lib/origami/filters/runlength.rb, line 93
def decode(stream)
  raise InvalidRunLengthDataError, "No end marker" unless stream.include?(EOD.chr)
  
  i = 0
  result = ""
  until stream[i].ord == EOD do
  
    length = stream[i].ord
    if length < EOD
      result << stream[i + 1, length + 1]
      i = i + length + 2
    else
      result << stream[i + 1,1] * (257 - length)
      i = i + 2
    end
    
  end
  
  result
end
encode(stream) click to toggle source

Encodes data using RLE compression method.

stream

The data to encode.

# File lib/origami/filters/runlength.rb, line 45
def encode(stream)

  result = ""
  i = 0

  while i < stream.size
    
    #
    # How many identical bytes coming?
    #
    length = 1
    while i+1 < stream.size and length < EOD and stream[i] == stream[i+1]
      length = length + 1
      i = i + 1
    end

    #
    # If more than 1, then compress them.
    #
    if length > 1
      result << (257 - length).chr << stream[i,1]

    #
    # Otherwise how many different bytes to copy ?
    #
    else
      j = i
      while j+1 < stream.size and (j - i + 1) < EOD and stream[j] != stream[j+1]
        j = j + 1
      end

      length = j - i
      result << length.chr << stream[i, length+1]

      i = j
    end

    i = i + 1
  end

  result << EOD.chr
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.