2022-05-17 14:42:03 +00:00
|
|
|
import std/times
|
2023-04-19 13:06:00 +00:00
|
|
|
import pkg/chronos
|
2022-05-19 19:56:03 +00:00
|
|
|
import codex/clock
|
2022-05-17 14:42:03 +00:00
|
|
|
|
|
|
|
export clock
|
|
|
|
|
|
|
|
type
|
|
|
|
MockClock* = ref object of Clock
|
|
|
|
time: SecondsSince1970
|
2023-04-19 13:06:00 +00:00
|
|
|
waiting: seq[Waiting]
|
|
|
|
Waiting = ref object
|
|
|
|
until: SecondsSince1970
|
|
|
|
future: Future[void]
|
2022-05-17 14:42:03 +00:00
|
|
|
|
|
|
|
func new*(_: type MockClock,
|
|
|
|
time: SecondsSince1970 = getTime().toUnix): MockClock =
|
|
|
|
MockClock(time: time)
|
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc set*(clock: MockClock, time: SecondsSince1970) =
|
2022-05-17 14:42:03 +00:00
|
|
|
clock.time = time
|
2023-04-19 13:06:00 +00:00
|
|
|
var index = 0
|
|
|
|
while index < clock.waiting.len:
|
|
|
|
if clock.waiting[index].until <= clock.time:
|
|
|
|
clock.waiting[index].future.complete()
|
|
|
|
clock.waiting.del(index)
|
|
|
|
else:
|
|
|
|
inc index
|
2022-05-17 14:42:03 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc advance*(clock: MockClock, seconds: int64) =
|
|
|
|
clock.set(clock.time + seconds)
|
2022-05-17 14:42:03 +00:00
|
|
|
|
|
|
|
method now*(clock: MockClock): SecondsSince1970 =
|
|
|
|
clock.time
|
2023-04-19 13:06:00 +00:00
|
|
|
|
|
|
|
method waitUntil*(clock: MockClock, time: SecondsSince1970) {.async.} =
|
|
|
|
if time > clock.now():
|
|
|
|
let future = newFuture[void]()
|
|
|
|
clock.waiting.add(Waiting(until: time, future: future))
|
|
|
|
await future
|