Class: Protopuffs::VarInt

Inherits:
Numeric show all
Defined in:
lib/protopuffs/message/field.rb

Direct Known Subclasses

Int32, Int64, UInt32, UInt64

Instance Attribute Summary

Attributes inherited from MessageField

#default, #identifier, #tag

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Numeric

#initialize

Methods inherited from MessageField

factory, #key, #optional?, #repeated?, shift_tag, #to_wire_format_with_value

Constructor Details

This class inherits a constructor from Protopuffs::Numeric

Class Method Details

.decode(bytes) ⇒ Object



101
102
103
104
105
106
107
# File 'lib/protopuffs/message/field.rb', line 101

def self.decode(bytes)
  value = 0
  bytes.each_with_index do |byte, index|
    value |= byte << (7 * index)
  end
  value
end

.encode(value) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/protopuffs/message/field.rb', line 111

def self.encode(value)
  return [0].pack('C') if value.zero?
  bytes = []
  until value.zero?
    byte = 0
    7.times do |i|
      byte |= (value & 1) << i
      value >>= 1
    end
    byte |= 0b10000000
    bytes << byte
  end
  bytes[-1] &= 0b01111111
  bytes.pack('C*')
end

.shift(buffer) ⇒ Object



92
93
94
95
96
97
98
99
100
# File 'lib/protopuffs/message/field.rb', line 92

def self.shift(buffer)
  bytes = []
  begin
    # Use #readbyte in Ruby 1.9, and #readchar in Ruby 1.8
    byte = buffer.send(buffer.respond_to?(:readbyte) ? :readbyte : :readchar)
    bytes << (byte & 0b01111111)
  end while byte >> 7 == 1
  bytes
end

.wire_typeObject



91
# File 'lib/protopuffs/message/field.rb', line 91

def self.wire_type; WireType::VARINT end

Instance Method Details

#decode(bytes) ⇒ Object



108
109
110
# File 'lib/protopuffs/message/field.rb', line 108

def decode(bytes)
  VarInt.decode(bytes)
end