Module: Protocol::MQTT::VBI

Defined in:
lib/protocol/mqtt/vbi.rb

Overview

Variable Byte Integer (MQTT spec ยง1.5.5). Base-128, little-endian, continuation bit on byte 7. 1 to 4 bytes, max value 268,435,455.

Constant Summary collapse

MAX =
268_435_455
MAX_BYTES =
4

Class Method Summary collapse

Class Method Details

.decode(io) ⇒ Object

Decodes a VBI from io, which must respond to #read(n). Raises MalformedPacket on truncation or on a 5th continuation byte.

Raises:



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/protocol/mqtt/vbi.rb', line 29

def self.decode(io)
  multiplier = 1
  value = 0
  MAX_BYTES.times do
    byte = io.read(1) or raise MalformedPacket, "truncated VBI"
    byte = byte.unpack1("C")
    value += (byte & 0x7F) * multiplier
    return value if (byte & 0x80).zero?
    multiplier *= 128
  end
  raise MalformedPacket, "VBI exceeds 4 bytes"
end

.encode(value) ⇒ Object

Returns a frozen BINARY String of 1..4 bytes.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/protocol/mqtt/vbi.rb', line 13

def self.encode(value)
  raise ArgumentError, "VBI out of range: #{value}" if value.negative? || value > MAX
  bytes = +"".b
  loop do
    digit = value % 128
    value /= 128
    digit |= 0x80 if value.positive?
    bytes << digit
    break if value.zero?
  end
  bytes.freeze
end