class Timers::Events

Maintains a PriorityHeap of events ordered on time, which can be cancelled.

def fire(time)

Fire all handles for which Handle#time is less than the given time.
def fire(time)
	merge!
	
	while handle = @sequence.peek and handle.time <= time
		@sequence.pop
		handle.fire(time)
	end
end

def first

Returns the first non-cancelled handle.
def first
	merge!
	
	while (handle = @sequence.peek)
		return handle unless handle.cancelled?
		@sequence.pop
	end
end

def flush!

def flush!
	while @queue.last&.cancelled?
		@queue.pop
	end
end

def initialize

def initialize
	# A sequence of handles, maintained in sorted order, future to present.
	# @sequence.last is the next event to be fired.
	@sequence = PriorityHeap.new
	@queue = []
end

def merge!

Move all non-cancelled timers from the pending queue to the priority heap
def merge!
	while handle = @queue.pop
		next if handle.cancelled?
		
		@sequence.push(handle)
	end
end

def schedule(time, callback)

Add an event at the given time.
def schedule(time, callback)
	flush!
	
	handle = Handle.new(time.to_f, callback)
	
	@queue << handle
	
	return handle
end

def size

Returns the number of pending (possibly cancelled) events.
def size
	@sequence.size + @queue.size
end