Class: Protocol::MQTT::Codec::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/protocol/mqtt/codec.rb

Overview

Cursor reader over a byte string.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes) ⇒ Reader

Returns a new instance of Reader.



17
18
19
20
# File 'lib/protocol/mqtt/codec.rb', line 17

def initialize(bytes)
  @bytes = bytes.b
  @pos = 0
end

Instance Attribute Details

#posObject (readonly)

Returns the value of attribute pos.



14
15
16
# File 'lib/protocol/mqtt/codec.rb', line 14

def pos
  @pos
end

Instance Method Details

#eof?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/protocol/mqtt/codec.rb', line 28

def eof?
  @pos >= @bytes.bytesize
end

#read(n) ⇒ Object

Raises:



33
34
35
36
37
38
# File 'lib/protocol/mqtt/codec.rb', line 33

def read(n)
  raise MalformedPacket, "truncated body: need #{n}, have #{remaining}" if remaining < n
  chunk = @bytes.byteslice(@pos, n)
  @pos += n
  chunk
end

#read_binaryObject



67
68
69
70
# File 'lib/protocol/mqtt/codec.rb', line 67

def read_binary
  len = read_u16
  read(len)
end

#read_restObject



78
79
80
# File 'lib/protocol/mqtt/codec.rb', line 78

def read_rest
  read(remaining)
end

#read_string_pairObject



73
74
75
# File 'lib/protocol/mqtt/codec.rb', line 73

def read_string_pair
  [read_utf8, read_utf8]
end

#read_u16Object



46
47
48
# File 'lib/protocol/mqtt/codec.rb', line 46

def read_u16
  read(2).unpack1("n")
end

#read_u32Object



51
52
53
# File 'lib/protocol/mqtt/codec.rb', line 51

def read_u32
  read(4).unpack1("N")
end

#read_u8Object



41
42
43
# File 'lib/protocol/mqtt/codec.rb', line 41

def read_u8
  read(1).unpack1("C")
end

#read_utf8Object



61
62
63
64
# File 'lib/protocol/mqtt/codec.rb', line 61

def read_utf8
  len = read_u16
  read(len).force_encoding(Encoding::UTF_8)
end

#read_vbiObject



56
57
58
# File 'lib/protocol/mqtt/codec.rb', line 56

def read_vbi
  VBI.decode(self)
end

#remainingObject



23
24
25
# File 'lib/protocol/mqtt/codec.rb', line 23

def remaining
  @bytes.bytesize - @pos
end