package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.util.PlatformLock /** * Thread-safe LRU for archive metadata (page lists, chapter lists). Bounded by entry count and total * weight; oversized values are returned by callers but not retained. */ internal class BoundedCache( private val maxEntries: Int, private val maxWeight: Int, private val weightOf: (V) -> Int, ) { private val lock = PlatformLock() private val values = LinkedHashMap() private var weight = 0L init { require(maxEntries > 0 && maxWeight > 0) } operator fun get(key: K): V? = lock.withLock { values.remove(key)?.also { values[key] = it } } fun clear() = lock.withLock { values.clear() weight = 0L } operator fun set(key: K, value: V) { val valueWeight = weightOf(value) require(valueWeight >= 0) lock.withLock { values.remove(key)?.let { weight -= weightOf(it) } if (valueWeight > maxWeight) return@withLock values[key] = value weight += valueWeight while (values.size > maxEntries || weight > maxWeight) { val oldest = values.entries.first() weight -= weightOf(oldest.value) values.remove(oldest.key) } } } }