A simple queue that optionally provides an upper size limit.
Recognized options include:
:limit
Size limit for the queue. If not specified, the queue can grow arbitrarily large.
:drop_oldest
If set to true, then when an item is added to a full queue, the oldest item is dropped. If set to false or not specified, then the new item is not added.
# File lib/sawmill/util/queue.rb, line 57 def initialize(opts_={}) limit_ = opts_[:limit] @buffer = limit_ ? ::Array.new(limit_) : [] @push_ptr = limit_ ? 0 : nil @pop_ptr = nil @drop_oldest = limit_ && opts_[:drop_oldest] end
Return the oldest item in the queue, or nil if the queue is empty.
# File lib/sawmill/util/queue.rb, line 100 def dequeue if @push_ptr if @pop_ptr object_ = @buffer[@pop_ptr] @buffer[@pop_ptr] = nil @pop_ptr += 1 @pop_ptr = 0 if @pop_ptr == @buffer.size @pop_ptr = nil if @pop_ptr == @push_ptr object_ else nil end else @buffer.shift end end
Return an array of the contents of the queue, in order.
# File lib/sawmill/util/queue.rb, line 120 def dequeue_all if @push_ptr if @pop_ptr if @pop_ptr < @push_ptr ret_ = @buffer[@pop_ptr..@push_ptr-1] else ret_ = @buffer[@pop_ptr..-1] + @buffer[0..@push_ptr-1] end @buffer.fill(nil) @push_ptr = 0 @pop_ptr = nil ret_ else [] end else ret_ = @buffer @buffer = [] ret_ end end
Attempt to push an item on the queue.
If the queue is full, then the behavior is determined by the :drop_oldest setting provided to the constructor.
Returns true if the object was pushed on the queue, or false if the queue was full.
# File lib/sawmill/util/queue.rb, line 74 def enqueue(object_) result_ = true if @push_ptr if @pop_ptr == @push_ptr if @drop_oldest @pop_ptr += 1 @pop_ptr = 0 if @pop_ptr == @buffer.size result_ = false else return false end elsif @pop_ptr.nil? @pop_ptr = @push_ptr end @buffer[@push_ptr] = object_ @push_ptr += 1 @push_ptr = 0 if @push_ptr == @buffer.size else @buffer.push(object_) end result_ end
Return the size of the queue, which is 0 if the queue is empty.
# File lib/sawmill/util/queue.rb, line 145 def size if @push_ptr if @pop_ptr value_ = @push_ptr - @pop_ptr value_ > 0 ? value_ : value_ + @buffer.size else 0 end else @buffer.size end end