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

commonMain.io.github.jan.supabase.collections.AtomicMutableMap.kt Maven / Gradle / Ivy

There is a newer version: 3.0.2
Show newest version
package io.github.jan.supabase.collections

import io.github.jan.supabase.annotations.SupabaseInternal
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update

/**
 * A multiplatform, thread-safe [MutableMap], implemented using AtomicFU. Thanks to the author of [klogging](https://github.com/klogging/klogging)!
 */
@SupabaseInternal
class AtomicMutableMap(
    vararg pairs: Pair
) : MutableMap {

    private val map = atomic(mapOf(*pairs))

    override val entries: MutableSet>
        get() = map.value.toMutableMap().entries
    override val keys: MutableSet
        get() = map.value.toMutableMap().keys
    override val size: Int
        get() = map.value.size
    override val values: MutableCollection
        get() = map.value.toMutableMap().values

    override fun clear() {
        map.update { emptyMap() }
    }

    override fun isEmpty(): Boolean = map.value.isEmpty()

    override fun remove(key: K): V? {
        var removedValue: V? = null
        map.update { current ->
            buildMap {
                putAll(current)
                removedValue = remove(key)
            }
        }
        return removedValue
    }

    override fun putAll(from: Map) = map.update { current ->
        buildMap {
            putAll(current)
            putAll(from)
        }
    }

    override fun put(key: K, value: V): V? {
        var previousValue: V? = null
        map.update { current ->
            buildMap {
                putAll(current)
                previousValue = put(key, value)
            }
        }
        return previousValue
    }

    override fun get(key: K): V? = map.value[key]

    override fun containsValue(value: V): Boolean = map.value.containsValue(value)

    override fun containsKey(key: K): Boolean = map.value.containsKey(key)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy