Module: Protobuf::Decoder

Defined in:
lib/protobuf/message/decoder.rb

Class Method Summary collapse

Class Method Details

.decode(stream, message) ⇒ Object

Read bytes from +stream+ and pass to +message+ object.



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/decoder.rb', line 11

def decode(stream, message)
  until stream.eof?
    tag, wire_type = read_key(stream)
    bytes =
      case wire_type
      when WireType::VARINT then
        read_varint(stream)
      when WireType::FIXED64 then
        read_fixed64(stream)
      when WireType::LENGTH_DELIMITED then
        read_length_delimited(stream)
      when WireType::START_GROUP then
        read_start_group(stream)
      when WireType::END_GROUP then
        read_end_group(stream)
      when WireType::FIXED32 then
        read_fixed32(stream)
      else
        raise InvalidWireType, wire_type
      end
    message.set_field(tag, bytes)
  end
  message
end

.read_end_group(stream) ⇒ Object

Not implemented.

Raises:

  • (NotImplementedError)


78
79
80
# File 'lib/protobuf/message/decoder.rb', line 78

def read_end_group(stream)
  raise NotImplementedError, 'Group is deprecated.'
end

.read_fixed32(stream) ⇒ Object

Read 32-bit string value from +stream+.



57
58
59
# File 'lib/protobuf/message/decoder.rb', line 57

def read_fixed32(stream)
  stream.read(4)
end

.read_fixed64(stream) ⇒ Object

Read 64-bit string value from +stream+.



62
63
64
# File 'lib/protobuf/message/decoder.rb', line 62

def read_fixed64(stream)
  stream.read(8)
end

.read_key(stream) ⇒ Object

Read key pair (tag and wire-type) from +stream+.



37
38
39
40
41
42
# File 'lib/protobuf/message/decoder.rb', line 37

def read_key(stream)
  bits = read_varint(stream)
  wire_type = bits & 0x07
  tag = bits >> 3
  [tag, wire_type]
end

.read_length_delimited(stream) ⇒ Object

Read length-delimited string value from +stream+.



67
68
69
70
# File 'lib/protobuf/message/decoder.rb', line 67

def read_length_delimited(stream)
  value_length = read_varint(stream)
  stream.read(value_length)
end

.read_start_group(stream) ⇒ Object

Not implemented.

Raises:

  • (NotImplementedError)


73
74
75
# File 'lib/protobuf/message/decoder.rb', line 73

def read_start_group(stream)
  raise NotImplementedError, 'Group is deprecated.'
end

.read_varint(stream) ⇒ Object

Read varint integer value from +stream+.



45
46
47
48
49
50
51
52
53
54
# File 'lib/protobuf/message/decoder.rb', line 45

def read_varint(stream)
  read_method = stream.respond_to?(:readbyte) ? :readbyte : :readchar
  value = index = 0
  begin
    byte = stream.__send__(read_method)
    value |= (byte & 0x7f) << (7 * index)
    index += 1
  end while (byte & 0x80).nonzero?
  value
end