Class: ParseQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/parse_queue.rb,
lib/parse_queue/version.rb

Overview

The RCTP queue for parser token flow with backtracking.

Constant Summary collapse

DFB =

The default fetch block

Proc.new { false }
VERSION =
"0.2.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&fetch) ⇒ ParseQueue

Set up the parser queue.



17
18
19
20
21
# File 'lib/parse_queue.rb', line 17

def initialize(&fetch)
  @fetch  = fetch
  @buffer = []
  @offset = @position = 0
end

Instance Attribute Details

#positionObject

The current read point of the queue.



11
12
13
# File 'lib/parse_queue.rb', line 11

def position
  @position
end

Instance Method Details

#fetch_allObject

Fetch all possible items.



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/parse_queue.rb', line 43

def fetch_all
  loop do
    item = @fetch.call

    unless item
      @fetch = DFB
      return
    end

    @buffer << item
  end
end

#fwd_countObject

How many unread items are in this parse queue?



24
25
26
# File 'lib/parse_queue.rb', line 24

def fwd_count
  index_limit - @position
end

#getObject

Get an item from the buffer.



34
35
36
37
38
39
40
# File 'lib/parse_queue.rb', line 34

def get
  @buffer << fetch_one if @position == index_limit

  result = @buffer[rev_count]
  @position += 1
  result
end

#rev_countObject

How many already read items are still in this parse queue?



29
30
31
# File 'lib/parse_queue.rb', line 29

def rev_count
  @position - @offset
end

#shiftObject

Release any items before the current item.



69
70
71
72
# File 'lib/parse_queue.rb', line 69

def shift
  @buffer.shift(rev_count)
  @offset = @position
end

#try(&block) ⇒ Object

Try to process some items with roll back on failure.



75
76
77
78
79
# File 'lib/parse_queue.rb', line 75

def try(&block)
  save = @position
  self.position = save unless (result = block.call)
  result
end

#try!(&block) ⇒ Object

Process some items with a shift on success and a roll back on failure.



82
83
84
85
# File 'lib/parse_queue.rb', line 82

def try!(&block)
  shift if (result = try(&block))
  result
end

#unget(count = 1) ⇒ Object

Undo the last get.



63
64
65
66
# File 'lib/parse_queue.rb', line 63

def unget(count=1)
  @position -= count
  validate_position
end