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

org.hnau.base.data.AutoKeyCache.kt Maven / Gradle / Ivy

package org.hnau.base.data


open class AutoKeyCache(
        private val keysGenerator: () -> K,
        private val tryCount: Int = 1000
) {

    private val container = HashMap()

    fun put(data: V): K? {
        val key = generateNewKey() ?: return null
        container[key] = data
        return key
    }

    private fun generateNewKey(): K? {
        repeat(tryCount) {
            keysGenerator()
                    .takeIf { container[it] == null }
                    ?.let { return it }
        }
        return null
    }

    fun get(key: K) = container[key]

    fun remove(key: K) = container.remove(key)

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy