Class: ParseQueue

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

Constant Summary collapse

DFB =

The default fetch block

Proc.new { false }
VERSION =
"0.2.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&fetch) ⇒ ParseQueue

Set up the parser queue.



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

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

Instance Attribute Details

#positionObject

The current read point of the queue.



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

def position
  @position
end

Instance Method Details

#fetch_allObject

Fetch all possible items.



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/parse_queue.rb', line 51

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?



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

def fwd_count
  index_limit - @position
end

#getObject

Get an item from the buffer.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/parse_queue.rb', line 33

def get
  if @position == index_limit
    item = @fetch.call

    unless item
      @fetch = DFB
      fail ParseQueueNoFwd
    end

    @buffer << item
  end

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

#rev_countObject

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



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

def rev_count
  @position - @offset
end

#shiftObject

Release any items before the current item.



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

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

#try(&block) ⇒ Object

Try to process some items with roll back on failure.



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

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.



90
91
92
93
# File 'lib/parse_queue.rb', line 90

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

#unget(count = 1) ⇒ Object

Undo the last get.



71
72
73
74
# File 'lib/parse_queue.rb', line 71

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