Class: Origami::Filter::ASCII85

Inherits:
Object
  • Object
show all
Includes:
Origami::Filter
Defined in:
lib/origami/filters/ascii.rb

Overview

Class representing a filter used to encode and decode data written in base85 encoding.

Constant Summary collapse

EOD =

:nodoc:

"~>"

Constants included from Origami::Filter

A85, AHx, CCF, Fl, RL

Instance Method Summary collapse

Methods included from Origami::Filter

included, #initialize

Instance Method Details

#decode(string) ⇒ Object

Decodes the given data encoded in base85.

string

The data to decode.



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/origami/filters/ascii.rb', line 116

def decode(string)
    input = filter_input(string)

    i = 0
    result = ''.b

    while i < input.size

        outblock = ""
        value = 0
        addend = 0

        if input[i] == "z"
            codelen = 1
        else
            codelen = 5

            if input.length - i < codelen
                raise InvalidASCII85StringError.new("Invalid length", input_data: string, decoded_data: result) if input.length - i == 1

                addend = codelen - (input.length - i)
                input << "u" * addend
            end

            # Decode the 5 characters input block into a 32 bit integer.
            begin
                value = decode_block input[i, codelen]
            rescue InvalidASCII85StringError => error
                error.input_data = string
                error.decoded_data = result
                raise(error)
            end
        end

        outblock = [ value ].pack "L>"
        outblock = outblock[0, 4 - addend]

        result << outblock

        i = i + codelen
    end

    result
end

#encode(stream) ⇒ Object

Encodes given data into base85.

stream

The data to encode.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/origami/filters/ascii.rb', line 80

def encode(stream)
    i = 0
    code = "".b
    input = stream.dup

    while i < input.size do

        if input.length - i < 4
            addend = 4 - (input.length - i)
            input << "\0" * addend
        else
            addend = 0
        end

        # Encode the 4 bytes input value into a 5 character string.
        value = input[i, 4].unpack("L>")[0]
        outblock = encode_block(value)

        outblock = "z" if outblock == "!!!!!" and addend == 0

        if addend != 0
            outblock = outblock[0, 4 - addend + 1]
        end

        code << outblock

        i = i + 4
    end

    code
end