Class: UV::PriorityQueue

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/uv-priority-queue/version.rb,
lib/uv-priority-queue/priority_queue.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, loop = ::Libuv::Loop.current, &blk) ⇒ PriorityQueue

Returns a new instance of PriorityQueue.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/uv-priority-queue/priority_queue.rb', line 5

def initialize(opts = {}, loop = ::Libuv::Loop.current, &blk)
    blk ||= lambda { |x, y| (x <=> y) == 1 }
    fifo_blk = nil
    @fifo = !!opts[:fifo]
    if @fifo
        fifo_blk = lambda do |x,y|
            if x[0] == y[0]
                x[1] < y[1]
            else
                blk.call(x[0], y[0])
            end
        end
    end
    @heap = Containers::Heap.new(&(fifo_blk || blk))
    @callbacks = []
    @loop = loop || ::Libuv::Loop.default
end

Instance Method Details

#clearObject



35
36
37
# File 'lib/uv-priority-queue/priority_queue.rb', line 35

def clear
    @heap.clear
end

#delete(pri) ⇒ Object



63
64
65
# File 'lib/uv-priority-queue/priority_queue.rb', line 63

def delete(pri)
    @heap.delete(pri)
end

#empty?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/uv-priority-queue/priority_queue.rb', line 39

def empty?
    @heap.empty?
end

#has_priority?(priority) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/uv-priority-queue/priority_queue.rb', line 43

def has_priority?(priority)
    @heap.has_key?(priority)
end

#nextObject



47
48
49
# File 'lib/uv-priority-queue/priority_queue.rb', line 47

def next
    @heap.next
end

#pop(callback = nil, &blk) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/uv-priority-queue/priority_queue.rb', line 51

def pop(callback = nil, &blk)
    callback ||= blk
    @loop.schedule do
        if @heap.empty?
            @callbacks << callback
        else
            callback.call @heap.pop
        end
    end
    nil
end

#push(obj, pri) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/uv-priority-queue/priority_queue.rb', line 27

def push(obj, pri)
    pri = [pri, Time.now.to_i] if @fifo
    @loop.schedule do
        @heap.push(pri, obj)
        @callbacks.shift.call(@heap.pop) until @heap.empty? || @callbacks.empty?
    end
end

#sizeObject



23
24
25
# File 'lib/uv-priority-queue/priority_queue.rb', line 23

def size
    @heap.size
end