BoundedCache.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/BoundedCache.kt
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.util.PlatformLock45/**6 * Thread-safe LRU for archive metadata (page lists, chapter lists). Bounded by entry count and total7 * weight; oversized values are returned by callers but not retained.8 */9internal class BoundedCache<K, V>(10 private val maxEntries: Int,11 private val maxWeight: Int,12 private val weightOf: (V) -> Int,13) {14 private val lock = PlatformLock()15 private val values = LinkedHashMap<K, V>()16 private var weight = 0L1718 init {19 require(maxEntries > 0 && maxWeight > 0)20 }2122 operator fun get(key: K): V? = lock.withLock {23 values.remove(key)?.also { values[key] = it }24 }2526 fun clear() = lock.withLock {27 values.clear()28 weight = 0L29 }3031 operator fun set(key: K, value: V) {32 val valueWeight = weightOf(value)33 require(valueWeight >= 0)34 lock.withLock {35 values.remove(key)?.let { weight -= weightOf(it) }36 if (valueWeight > maxWeight) return@withLock37 values[key] = value38 weight += valueWeight39 while (values.size > maxEntries || weight > maxWeight) {40 val oldest = values.entries.first()41 weight -= weightOf(oldest.value)42 values.remove(oldest.key)43 }44 }45 }46}47