scoop:scoop.asyncio:0.1.0
src/loop/loop_timer_heap.scoop
Selected production source · src/loop/loop_timer_heap.scoop
1
package scoop.asyncio3
import scoop.time.Duration4
import scoop.time.TimeMark6
internal struct LoopDeadline(val started: TimeMark, val duration: Duration) {7
fun before(other: LoopDeadline): Boolean {8
val startOrder = started.compareTo(other.started)9
val waitOrder = duration.compareTo(other.duration)10
if (startOrder <= 0 && waitOrder <= 0)11
return startOrder < 0 || waitOrder < 012
if (startOrder >= 0 && waitOrder >= 0)13
return false14
// Both durations are nonnegative. Their difference fits even for Long.MAX_VALUE seconds.15
return started.reading - other.started.reading < other.duration - duration16
}18
fun expired(now: TimeMark): Boolean = now - started >= duration20
fun remaining(now: TimeMark): Duration = duration - (now - started)21
}23
// A timer stores its owner-only position so cancellation removes it without retaining tombstones.24
internal class LoopTimerHeap {25
private val entries = ArrayList<LoopTimer>()27
val size: Long get() = entries.size28
fun first(): LoopTimer = entries[0L]30
fun add(timer: LoopTimer) {31
timer.heapIndex = entries.size32
entries.add(timer)33
up(timer.heapIndex)34
}36
fun remove(timer: LoopTimer) {37
val index = timer.heapIndex38
if (index < 0L)39
return40
val last = entries.removeAt(entries.size - 1L)41
timer.heapIndex = -1L42
if (index == entries.size)43
return44
entries[index] = last45
last.heapIndex = index46
if (up(index) == index)47
down(index)48
}50
private fun swap(left: Long, right: Long) {51
val saved = entries[left]52
entries[left] = entries[right]53
entries[right] = saved54
entries[left].heapIndex = left55
saved.heapIndex = right56
}58
private fun up(start: Long): Long {59
var index = start60
while (index > 0L) {61
val parent = (index - 1L) / 2L62
if (!entries[index].deadline.before(entries[parent].deadline))63
break64
swap(index, parent)65
index = parent66
}67
return index68
}70
private fun down(start: Long) {71
var index = start72
while (index < entries.size / 2L) {73
var child = index * 2L + 1L74
if (75
child +76
1L <77
entries.size &&78
entries[child + 1L].deadline.before(entries[child].deadline)79
)80
child += 1L81
if (!entries[child].deadline.before(entries[index].deadline))82
break83
swap(index, child)84
index = child85
}86
}87
}