Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/loop_timer_heap.scoop

Selected production source · src/loop/loop_timer_heap.scoop

1package scoop.asyncio
3import scoop.time.Duration
4import scoop.time.TimeMark
6internal 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 < 0
12 if (startOrder >= 0 && waitOrder >= 0)
13 return false
14 // Both durations are nonnegative. Their difference fits even for Long.MAX_VALUE seconds.
15 return started.reading - other.started.reading < other.duration - duration
16 }
18 fun expired(now: TimeMark): Boolean = now - started >= duration
20 fun remaining(now: TimeMark): Duration = duration - (now - started)
23// A timer stores its owner-only position so cancellation removes it without retaining tombstones.
24internal class LoopTimerHeap {
25 private val entries = ArrayList<LoopTimer>()
27 val size: Long get() = entries.size
28 fun first(): LoopTimer = entries[0L]
30 fun add(timer: LoopTimer) {
31 timer.heapIndex = entries.size
32 entries.add(timer)
33 up(timer.heapIndex)
34 }
36 fun remove(timer: LoopTimer) {
37 val index = timer.heapIndex
38 if (index < 0L)
39 return
40 val last = entries.removeAt(entries.size - 1L)
41 timer.heapIndex = -1L
42 if (index == entries.size)
43 return
44 entries[index] = last
45 last.heapIndex = index
46 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] = saved
54 entries[left].heapIndex = left
55 saved.heapIndex = right
56 }
58 private fun up(start: Long): Long {
59 var index = start
60 while (index > 0L) {
61 val parent = (index - 1L) / 2L
62 if (!entries[index].deadline.before(entries[parent].deadline))
63 break
64 swap(index, parent)
65 index = parent
66 }
67 return index
68 }
70 private fun down(start: Long) {
71 var index = start
72 while (index < entries.size / 2L) {
73 var child = index * 2L + 1L
74 if (
75 child +
76 1L <
77 entries.size &&
78 entries[child + 1L].deadline.before(entries[child].deadline)
79 )
80 child += 1L
81 if (!entries[child].deadline.before(entries[index].deadline))
82 break
83 swap(index, child)
84 index = child
85 }
86 }