Method: Origami::Filter::RunLength#encode

Defined in:
lib/origami/filters/runlength.rb

#encode(stream) ⇒ Object

Encodes data using RLE compression method.

stream

The data to encode.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/origami/filters/runlength.rb', line 40

def encode(stream)
    result = "".b
    i = 0

    while i < stream.size

        # How many identical bytes coming?
        length = compute_run_length(stream, i)

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

        # Otherwise how many different bytes to copy?
        else
            next_pos = find_next_run(stream, i)
            length = next_pos - i

            result << (length - 1).chr << stream[i, length]

            i += length
        end
    end

    result << EOD.chr
end