Module: ProtocolBuffers::Varint

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

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.decode(io) ⇒ Object


26
27
28
29
30
31
32
33
34
35
36
# File 'lib/protocol_buffers/runtime/varint.rb', line 26

def self.decode(io)
  int_val = 0
  shift = 0
  loop do
    raise(DecodeError, "too many bytes when decoding varint") if shift >= 64
    byte = io.getc.ord
    int_val |= (byte & 0b0111_1111) << shift
    shift += 7
    return int_val if (byte & 0b1000_0000) == 0
  end
end

.decodeZigZag32(int_val) ⇒ Object Also known as: decodeZigZag64


47
48
49
# File 'lib/protocol_buffers/runtime/varint.rb', line 47

def self.decodeZigZag32(int_val)
  (int_val >> 1) ^ -(int_val & 1)
end

.encode(io, int_val) ⇒ Object


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/protocol_buffers/runtime/varint.rb', line 7

def self.encode(io, int_val)
  if int_val < 0
    # negative varints are always encoded with the full 10 bytes
    int_val = int_val & 0xffffffff_ffffffff
  end
  loop do
    byte = int_val & 0b0111_1111
    int_val >>= 7
    if int_val == 0
      io << byte.chr
      break
    else
      io << (byte | 0b1000_0000).chr
    end
  end
end

.encodeZigZag32(int_val) ⇒ Object


39
40
41
# File 'lib/protocol_buffers/runtime/varint.rb', line 39

def self.encodeZigZag32(int_val)
  (int_val << 1) ^ (int_val >> 31)
end

.encodeZigZag64(int_val) ⇒ Object


43
44
45
# File 'lib/protocol_buffers/runtime/varint.rb', line 43

def self.encodeZigZag64(int_val)
  (int_val << 1) ^ (int_val >> 63)
end