Class: Nibbler::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/nibbler/parser.rb

Defined Under Namespace

Classes: RunningStatus

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(library) ⇒ Parser



7
8
9
10
11
# File 'lib/nibbler/parser.rb', line 7

def initialize(library)
  @library = library
  @running_status = RunningStatus.new
  @buffer = []
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



5
6
7
# File 'lib/nibbler/parser.rb', line 5

def buffer
  @buffer
end

Instance Method Details

#nibbles_to_message(fragment) ⇒ Hash?

If possible, convert the given fragment to a MIDI message



49
50
51
52
53
54
55
# File 'lib/nibbler/parser.rb', line 49

def nibbles_to_message(fragment)
  if fragment.length >= 2
    # convert the part of the fragment to start with to a numeric
    slice = fragment.slice(0..1).map(&:hex)
    compute_message(slice, fragment)
  end
end

#process(nibbles) ⇒ Hash

Process the given nibbles and add them to the buffer



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/nibbler/parser.rb', line 16

def process(nibbles)
  report = {
    :messages => [],
    :processed => [],
    :rejected => []
  }
  pointer = 0
  @buffer += nibbles
  # Iterate through nibbles in the buffer until a status message is found
  while pointer <= (@buffer.length - 1)
    # fragment is the piece of the buffer to look at
    fragment = get_fragment(pointer)
    # See if there really is a message there
    unless (processed = nibbles_to_message(fragment)).nil?
      # if fragment contains a real message, reject the nibbles that precede it
      report[:rejected] += @buffer.slice(0, pointer)
      # and record it
      @buffer = fragment.dup # fragment now has the remaining nibbles for next pass
      fragment = nil # Reset fragment
      pointer = 0 # Reset iterator
      report[:messages] << processed[:message]
      report[:processed] += processed[:processed]
    else
      @running_status.cancel
      pointer += 1
    end
  end
  report
end