Module: Protobuf::Encoder
- Defined in:
- lib/protobuf/message/encoder.rb
Class Method Summary collapse
-
.encode(stream, message) ⇒ Object
Encode +message+ and write to +stream+.
-
.write_pair(stream, field, value) ⇒ Object
Encode key and value, and write to +stream+.
Class Method Details
.encode(stream, message) ⇒ Object
Encode +message+ and write to +stream+.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/protobuf/message/encoder.rb', line 11 def encode(stream, ) # FIXME make this not as ghetto raise NotInitializedError, "Message %s is not initialized (one or more fields is improperly set): %s" % [.class.name, JSON.parse(.to_json)] unless .initialized? .each_field do |field, value| next unless .has_field?(field.name) if field.repeated? if field.packed? key = (field.tag << 3) | WireType::LENGTH_DELIMITED packed_value = value.map {|val| field.encode(val) }.join stream.write(Field::VarintField.encode(key)) stream.write(Field::VarintField.encode(packed_value.size)) stream.write(packed_value) else value.each do |val| write_pair(stream, field, val) end end else write_pair(stream, field, value) end end end |
.write_pair(stream, field, value) ⇒ Object
Encode key and value, and write to +stream+.
37 38 39 40 41 42 43 |
# File 'lib/protobuf/message/encoder.rb', line 37 def write_pair(stream, field, value) key = (field.tag << 3) | field.wire_type key_bytes = Field::VarintField.encode(key) stream.write(key_bytes) bytes = field.encode(value) stream.write(bytes) end |