blob: dac4751e5541dafd698567df148ad33173fdf80e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package moe.nea.ledger
import kotlin.time.Duration
import kotlin.time.Duration.Companion.nanoseconds
class ExpiringValue<T>(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 <T> empty(): ExpiringValue<T> {
val value = ExpiringValue(Unit)
value.take()
@Suppress("UNCHECKED_CAST")
return value as ExpiringValue<T>
}
}
fun consume(expiry: Duration): T? = get(expiry).also { take() }
fun take() {
taken = true
}
}
|