Class: Nstrct::Instruction

Inherits:
Object
  • Object
show all
Defined in:
lib/nstrct/instruction.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, arguments = []) ⇒ Instruction

Instantiate a new instruction by its code and alist of arguments



36
37
38
# File 'lib/nstrct/instruction.rb', line 36

def initialize code, arguments=[]
  @code, @arguments = code, arguments
end

Instance Attribute Details

#argumentsObject

Returns the value of attribute arguments.



5
6
7
# File 'lib/nstrct/instruction.rb', line 5

def arguments
  @arguments
end

#codeObject

Returns the value of attribute code.



5
6
7
# File 'lib/nstrct/instruction.rb', line 5

def code
  @code
end

Class Method Details

.build(code, *args) ⇒ Object

Build an instruction for a code and some arguments.

Message.build_instruction 54, [ :boolean, true], [[:int8], [7, 8, 9]] ]


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/nstrct/instruction.rb', line 23

def self.build code, *args
  arguments = []
  args.each do |arg|
    if arg[0].is_a?(Array)
      arguments << Nstrct::Argument.new(arg[0][0], arg[1], true)
    else
      arguments << Nstrct::Argument.new(arg[0], arg[1], false)
    end
  end
  self.new(code, arguments)
end

.parse(data) ⇒ Object

Parse one message from the data stream.



8
9
10
11
12
13
14
15
16
17
# File 'lib/nstrct/instruction.rb', line 8

def self.parse data
  code = data.slice!(0..1).unpack('s>')[0]
  num_arguments = data.slice!(0).unpack('C')[0]
  data.slice!(0..1) # num_array_elements
  arguments = []
  num_arguments.times do
    arguments << Nstrct::Argument.parse(data)
  end
  self.new(code, arguments)
end

Instance Method Details

#argument_valuesObject

Get all the arguments values



41
42
43
# File 'lib/nstrct/instruction.rb', line 41

def argument_values
  @arguments.map{ |arg| arg.value }
end

#array_elementsObject

get all elements in arrays



46
47
48
# File 'lib/nstrct/instruction.rb', line 46

def array_elements
  @arguments.inject(0){ |sum, a| sum + (a.array ? a.value.size : 0) }
end

#inspectObject

Return a comparable inspection



62
63
64
# File 'lib/nstrct/instruction.rb', line 62

def inspect
  "#<Nstrct::Instructon code=#{@code.inspect}, arguments=#{@arguments.inspect}>"
end

#packObject

Pack a single instruction in a buffer



51
52
53
54
55
56
57
58
59
# File 'lib/nstrct/instruction.rb', line 51

def pack
  message = [@code].pack('s>')
  message += [@arguments.size].pack('C')
  message += [array_elements].pack('s>')
  @arguments.each do |arg|
    message += arg.pack
  end
  message
end