From 977620f1b5218cc8a041742f970974a4bfff29cc Mon Sep 17 00:00:00 2001 From: Linnea Gräf Date: Sat, 5 Oct 2024 12:06:23 +0200 Subject: Add minion hopper tracker --- src/main/kotlin/moe/nea/ledger/ExpiringValue.kt | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/main/kotlin/moe/nea/ledger/ExpiringValue.kt (limited to 'src/main/kotlin/moe/nea/ledger/ExpiringValue.kt') 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(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 + } +} \ No newline at end of file -- cgit