Module: MQTTPipe::Packer

Extended by:
Packer
Included in:
Packer
Defined in:
lib/mqtt_pipe/packer.rb

Overview

The packer module is used to pack/unpack classes that supports it.

Defined Under Namespace

Classes: EndOfPacket, FormatError

Instance Method Summary collapse

Instance Method Details

#pack(*values) ⇒ Object Also known as: []

Packs the arguments acording to their type.

An ArgumentError is raised if any given class does not support packing.



55
56
57
58
59
# File 'lib/mqtt_pipe/packer.rb', line 55

def pack *values
  values.map{|value| value.to_packed }.join
rescue NoMethodError
  raise ArgumentError, 'Unknown input format'
end

#read_packed_bytes(n = 1, from:, as: 'C') ⇒ Object

A simple helper method to read a given number of bytes from IO object and format them as anything supported by Array#unpack.

Raises:



90
91
92
93
94
95
# File 'lib/mqtt_pipe/packer.rb', line 90

def read_packed_bytes n = 1, from:, as: 'C'
  raw = from.read(n)
  raise FormatError if raw.nil? or raw.length != n
  
  raw.unpack(as).first
end

#supports_type?(type) ⇒ Boolean Also known as: supports?

Checks whether a class or object is supported by the packer. For arrays each item is checked recursivly

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/mqtt_pipe/packer.rb', line 33

def supports_type? type
  if type.is_a? Class
    type.to_packed
  elsif type.is_a? Array
    return type.detect{|obj| not supports_type? obj }.nil?
  else
    type.class.to_packed
  end
  return true
rescue NoMethodError
  return false
end

#unpack(raw, limit: nil) ⇒ Object

Unpacks a serialized object and returns an array of the original values.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/mqtt_pipe/packer.rb', line 68

def unpack raw, limit: nil
  raw = ::StringIO.new raw unless raw.respond_to? :read
  result = []
  
  # Either loop infinately or the number of times 
  # specified by limit
  
  (limit.nil? ? loop : limit.times).each do
    result << unpack_single(raw)
  end
  
  return result
rescue EndOfPacket
  return result
end