dymokomi/luce-ui
Source of release 0.19.3
## The run loop's main-thread timers: a flat array of at most 256, scanned
## linearly on every query and service pass. `after` runs a callback once,
## `every` repeats it, `post` runs it on the next serviced turn, and `cancel` stops
## one by the handle it was given. `service` fires everything due, so an application
## drives periodic work — a settings poll, a status message that fades, a check for a
## background result — without a busy per-frame callback. Callbacks are thread-bound
## like every interop callback, so only the main loop schedules and fires them.
import interop
import ownership
import memory
import time
import result
struct Timer:
var id: i64
var deadline: u64
var interval: u64
var callback: interop.Callback[unit, unit]?
var active: bool
## The timers and the next handle to give out; handles start at 1 and are never
## reused.
pub struct Scheduler:
var timers: Timer[]
var next_id: i64
pub func init():
var empty: Timer[]
self.timers = empty
self.next_id = 0
## Append one armed timer and return its handle. Growing copies the edges into
## the new backing and frees only the old memory, so each timer keeps one edge.
func schedule(deadline: u64, interval: u64, callback: interop.Callback[unit, unit]) -> i64!:
if self.timers.length >= 256:
error(result.limit, "a scheduler holds at most 256 timers")
self.next_id = self.next_id +? 1 else error(result.limit, "timer identities exhausted")
let id = self.next_id
let n = self.timers.length
var grown = try new Timer[n + 1] --- in memory.heap
for index in 0..<n:
grown[index] = self.timers[index]
grown[n] = Timer(id = id, deadline = deadline, interval = interval, callback = callback.clone(), active = true)
if n > 0:
free(self.timers) in memory.heap
self.timers = grown
return id
## Run `callback` once, `seconds` from now.
pub func after(seconds: f64, callback: interop.Callback[unit, unit]) -> i64!:
let delay = 0.0 if seconds < 0.0 else seconds
return try self.schedule(time.now() + (u64)(delay * 1000000000.0), 0, callback)
## Run `callback` every `seconds`, starting one interval from now.
pub func every(seconds: f64, callback: interop.Callback[unit, unit]) -> i64!:
if seconds <= 0.0:
error(result.invalid, "a repeating timer needs a positive interval")
let interval = (u64)(seconds * 1000000000.0)
return try self.schedule(time.now() + interval, interval, callback)
## Run `callback` on the next serviced turn, to defer work back to the main loop.
pub func post(callback: interop.Callback[unit, unit]) -> i64!:
return try self.schedule(time.now(), 0, callback)
## Stop a timer by its handle. Canceling one from inside a callback is safe: the
## slot is emptied now and packed away after the current service pass finishes.
pub func cancel(id: i64):
for index in 0..<self.timers.length:
if self.timers[index].id == id and self.timers[index].active:
self.clear(index)
return
## Empty slot `index`, then release its callback. Releasing the last edge of a
## closure can run a collection that traces this scheduler, so the slot must
## already be empty by then, or the trace visits a dead callback.
func clear(index: usize):
let held = self.timers[index].callback
self.timers[index].callback = none
self.timers[index].active = false
if let callback = held:
callback.release()
## The soonest deadline still pending, for a loop that means to sleep until then.
pub func next_deadline() -> u64?:
var soonest: u64? = none
for index in 0..<self.timers.length:
if self.timers[index].active:
if let current = soonest:
if self.timers[index].deadline < current:
soonest = self.timers[index].deadline
else:
soonest = self.timers[index].deadline
return soonest
## Fire every timer whose deadline has passed. Repeating timers re-arm from `now`;
## one-shots drop out. Returns the first callback failure, like the input path. A
## callback that schedules more timers is safe — the fresh slots wait for the next
## pass — and one that cancels a timer clears it before it can fire again.
pub func service(now: u64) -> interop.Outcome[unit]:
let length = self.timers.length
for index in 0..<length:
if self.timers[index].active and self.timers[index].deadline <= now:
if let callback = self.timers[index].callback:
let outcome = callback.invoke(())
if not outcome.is_success():
return outcome
outcome.release()
if self.timers[index].active:
if self.timers[index].interval > 0:
self.timers[index].deadline = now +? self.timers[index].interval else now
else:
self.clear(index)
self.compact()
return result.success[unit](())
## Drop emptied slots. Best effort: a failed shrink keeps the tombstones, which
## service and next_deadline already skip, and a later pass reclaims them.
func compact():
var live: usize = 0
for index in 0..<self.timers.length:
if self.timers[index].active:
live += 1
if live == self.timers.length:
return
if live == 0:
if self.timers.length > 0:
free(self.timers) in memory.heap
var empty: Timer[]
self.timers = empty
return
var packed = new Timer[live] --- in memory.heap catch failure:
return
var cursor: usize = 0
for index in 0..<self.timers.length:
if self.timers[index].active:
packed[cursor] = self.timers[index]
cursor += 1
free(self.timers) in memory.heap
self.timers = packed
## Detach every timer before releasing any, for the reason `clear` gives.
pub func close():
let old = self.timers
var empty: Timer[]
self.timers = empty
for index in 0..<old.length:
if let callback = old[index].callback:
callback.release()
if old.length > 0:
free(old) in memory.heap
pub func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
for index in 0..<self.timers.length:
if let callback = self.timers[index].callback:
callback.trace(visit, context)