diff options
Diffstat (limited to 'src/main/kotlin/moe/nea/ledger/ExpiringValue.kt')
-rw-r--r-- | src/main/kotlin/moe/nea/ledger/ExpiringValue.kt | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/main/kotlin/moe/nea/ledger/ExpiringValue.kt b/src/main/kotlin/moe/nea/ledger/ExpiringValue.kt new file mode 100644 index 0000000..dac4751 --- /dev/null +++ b/src/main/kotlin/moe/nea/ledger/ExpiringValue.kt @@ -0,0 +1,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 + } +}
\ No newline at end of file |