All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.multiplatform.util.WeakMutableMap.kt Maven / Gradle / Ivy

The newest version!
package ru.casperix.multiplatform.util

import ru.casperix.misc.Disposable


class WeakMutableMap(val maxSize: Int) {
    data class Record(var marker: Long, val content: Content)

    private val map = mutableMapOf>()
    private var lastMarker = 0L

    fun getOrPut(key: Key, builder: () -> Value): Value {
        var changed = false
        val record = map.getOrPut(key) {
            changed = true
            val content = builder()
            Record(0L, content)
        }
        record.marker = ++lastMarker

        if (changed && map.size > maxSize) {
            removeMinMarker()
        }
        return record.content
    }

    private fun removeMinMarker() {
        val entry = map.minBy { (key, record) ->
            record.marker
        }
        (entry.value.content as? Disposable)?.dispose()
        map.remove(entry.key)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy