package moe.nea.ledger import kotlin.time.Duration import kotlin.time.Duration.Companion.nanoseconds class ExpiringValue(private val value: T) { val lastSeenAt: Long = System.nanoTime() val age get() = (System.nanoTime() - lastSeenAt).nanoseconds var taken = false fun get(expiry: Duration): T? { return if (!taken && expiry > age) value else null } companion object { fun empty(): ExpiringValue { val value = ExpiringValue(Unit) value.take() @Suppress("UNCHECKED_CAST") return value as ExpiringValue } } fun consume(expiry: Duration): T? = get(expiry).also { take() } fun take() { taken = true } }