Module: ProtocolBuffers::VarintPure

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

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#decode(io) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/protocol_buffers/runtime/varint.rb', line 21

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

#encode(io, int_val) ⇒ Object



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

def 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