Module: ProtocolBuffers::Encoder

Defined in:
lib/protocol_buffers/runtime/encoder.rb

Overview

:nodoc: all

Class Method Summary collapse

Class Method Details

.encode(io, message) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/protocol_buffers/runtime/encoder.rb', line 12

def self.encode(io, message)
  message.validate!

  message.fields.each do |tag, field|
    next unless message.value_for_tag?(tag)

    value = message.value_for_tag(tag)
    wire_type = field.wire_type
    tag = (field.tag << 3) | wire_type

    if field.repeated?
      next if value.size == 0

      if field.packed?
        # encode packed field in a LENGTH_DELIMITED wire
        wire_type = 2
        tag = (field.tag << 3) | wire_type
        buf = ProtocolBuffers.bin_sio
        value.each { |i| serialize_field_value(buf, field.wire_type, field.serialize(i)) }
        Varint.encode(io, tag)
        Varint.encode(io, buf.size)
        io.write(buf.string)
      else
        value.each { |i| serialize_field(io, tag, wire_type, field.serialize(i)) }
      end
    else
      serialize_field(io, tag, wire_type, field.serialize(value))
    end
  end

  message.each_unknown_field do |tag_int, value|
    wire_type = tag_int & 0b111
    serialize_field(io, tag_int, wire_type, value)
  end
end

.serialize_field(io, tag, wire_type, serialized) ⇒ Object



48
49
50
51
52
53
# File 'lib/protocol_buffers/runtime/encoder.rb', line 48

def self.serialize_field(io, tag, wire_type, serialized)
  # write the tag
  Varint.encode(io, tag)
  self.serialize_field_value(io, wire_type, serialized)
  Varint.encode(io, tag & ~3 | 4) if wire_type == 3
end

.serialize_field_value(io, wire_type, serialized) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/protocol_buffers/runtime/encoder.rb', line 55

def self.serialize_field_value(io, wire_type, serialized)
  # see comment in decoder.rb about magic numbers
  case wire_type
  when 0 # VARINT
    Varint.encode(io, serialized)
  when 1, 5 # FIXED64, FIXED32
    io.write(serialized)
  when 2 # LENGTH_DELIMITED
    Varint.encode(io, serialized.bytesize)
    io.write(serialized)
  when 3 # START_GROUP
    io.write(serialized)
  when 4 # END_GROUP: never appear
    raise(EncodeError, "Unexpected wire type END_GROUP")
  else
    raise(EncodeError, "unknown wire type: #{wire_type}")
  end
end