Class: ZMachine::HashedWheel

Inherits:
Object
  • Object
show all
Defined in:
lib/zmachine/hashed_wheel.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number_of_slots, tick_length, start_time = System.nano_time) ⇒ HashedWheel

Returns a new instance of HashedWheel.



28
29
30
31
32
33
# File 'lib/zmachine/hashed_wheel.rb', line 28

def initialize(number_of_slots, tick_length, start_time = System.nano_time)
  @slots = Array.new(number_of_slots) { [] }
  @tick_length = tick_length * 1_000_000
  @last = start_time
  @current_tick = 0
end

Instance Attribute Details

#lastObject

Returns the value of attribute last.



26
27
28
# File 'lib/zmachine/hashed_wheel.rb', line 26

def last
  @last
end

#slotsObject (readonly)

Returns the value of attribute slots.



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

def slots
  @slots
end

Instance Method Details

#add(timeout, &block) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/zmachine/hashed_wheel.rb', line 35

def add(timeout, &block)
  timeout *= 1_000_000 # ms to ns
  ticks = timeout / @tick_length
  slot  = (@current_tick + ticks) % @slots.length
  HashedWheelTimeout.new(System.nano_time + timeout, &block).tap do |hwt|
    @slots[slot] << hwt
  end
end

#advance(now = System.nano_time) ⇒ Object

returns all timeouts



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/zmachine/hashed_wheel.rb', line 51

def advance(now = System.nano_time)
  passed_ticks = (now - @last) / @tick_length
  result = []
  begin
    @current_tick %= @slots.length
    @slots[@current_tick].delete_if do |timeout|
      result << timeout if timeout.deadline < now
    end
    @current_tick += 1
    passed_ticks -= 1
  end while passed_ticks > 0
  @last = now
  result.reject do |timeout|
    timeout.canceled?
  end
end

#reset(time = System.nano_time) ⇒ Object



44
45
46
47
48
# File 'lib/zmachine/hashed_wheel.rb', line 44

def reset(time = System.nano_time)
  @slots = Array.new(@slots.length) { [] }
  @current_tick = 0
  @last = time
end