Class: ParseQueue

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

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&fetch) ⇒ ParseQueue

Set up the parser queue.



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

def initialize(&fetch)
  @fetch = fetch || lambda { false }
  @buffer = []
  @offset = @position = 0
end

Instance Attribute Details

#offsetObject (readonly)

The number of old items removed from the queue.



15
16
17
# File 'lib/parse_queue.rb', line 15

def offset
  @offset
end

#positionObject

The current read point of the queue.



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

def position
  @position
end

Instance Method Details

#add(*items) ⇒ Object

Manually add items to the buffer



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

def add(*items)
  @buffer += items.flatten
end

#back_upObject

Undo the last get.



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

def back_up
  @position -= 1
  validate_position
end

#getObject

Get an item from the buffer.



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

def get
  if @position >= (@buffer.length + @offset)
    item = @fetch.call
    fail ParseQueueNoFwd unless item
    @buffer << item
  end

  result = @buffer[@position - @offset]
  @position += 1
  result
end

#read_allObject

Get all possible items



48
49
50
51
52
53
54
# File 'lib/parse_queue.rb', line 48

def read_all
  loop do
    item = @fetch.call
    return unless item
    @buffer << item
  end
end

#shiftObject

Release any items before the current item.



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

def shift
  @buffer.shift(@position - @offset)
  @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
  @position = save unless block.call
  validate_position
end

#try!(&block) ⇒ Object

Try to process some items with shift of success and roll back on failure.



82
83
84
85
86
87
88
89
90
91
# File 'lib/parse_queue.rb', line 82

def try!(&block)
  save = @position

  if block.call
    shift
  else
    @position = save
    validate_position
  end
end

#unreadObject

How many unread items are in this parse queue?



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

def unread
  @buffer.length - @position + @offset
end

#validate_positionObject

Is this a valid position?



94
95
96
97
# File 'lib/parse_queue.rb', line 94

def validate_position
  fail ParseQueueNoRev if @position < @offset
  fail ParseQueueNoFwd if @position >= (@buffer.length + @offset)
end