Module: Beefcake::Message::Decode

Defined in:
lib/beefcake.rb

Instance Method Summary collapse

Instance Method Details

#decode(buf, o = self.new) ⇒ Object



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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/beefcake.rb', line 134

def decode(buf, o=self.new)
  if ! buf.is_a?(Buffer)
    buf = Buffer.new(buf)
  end

  # TODO: test for incomplete buffer
  while buf.length > 0
    fn, wire = buf.read_info

    fld = fields[fn]

    # We don't have a field for with index fn.
    # Ignore this data and move on.
    if fld.nil?
      buf.skip(wire)
      next
    end

    exp = Buffer.wire_for(fld.type)
    if wire != exp
      raise WrongTypeError.new(fld.name, exp, wire)
    end

    if fld.rule == :repeated && fld.opts[:packed]
      len = buf.read_uint64
      tmp = Buffer.new(buf.read(len))
      o[fld.name] ||= []
      while tmp.length > 0
        o[fld.name] << tmp.read(fld.type)
      end
	  elsif fld.rule == :repeated
      val = buf.read(fld.type)
      (o[fld.name] ||= []) << val
    else
      val = buf.read(fld.type)
      o[fld.name] = val
    end
  end

  # Set defaults
  fields.values.each do |f|
	  next if o[f.name] == false
    o[f.name] ||= f.opts[:default]
  end

  o.validate!

  o
end