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

org.jetbrains.kotlin.fir.caches.FirThreadUnsafeCachesFactory.kt Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
/*
 * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package org.jetbrains.kotlin.fir.caches

object FirThreadUnsafeCachesFactory : FirCachesFactory() {
    override fun  createCache(createValue: (K, CONTEXT) -> V): FirCache =
        FirThreadUnsafeCache(createValue)

    override fun  createCacheWithPostCompute(
        createValue: (K, CONTEXT) -> Pair,
        postCompute: (K, V, DATA) -> Unit
    ): FirCache =
        FirThreadUnsafeCacheWithPostCompute(createValue, postCompute)
}

@Suppress("UNCHECKED_CAST")
private class FirThreadUnsafeCache(
    private val createValue: (K, CONTEXT) -> V
) : FirCache() {
    private val map = NullableMap()

    override fun getValue(key: K, context: CONTEXT): V =
        map.getOrElse(key) {
            createValue(key, context).also { createdValue ->
                map[key] = createdValue
            }
        }

    override fun getValueIfComputed(key: K): V? =
        map.getOrElse(key) { null as V }
}


private class FirThreadUnsafeCacheWithPostCompute(
    private val createValue: (K, CONTEXT) -> Pair,
    private val postCompute: (K, V, DATA) -> Unit
) : FirCache() {
    private val map = NullableMap()

    override fun getValue(key: K, context: CONTEXT): V =
        map.getOrElse(key) {
            val (createdValue, data) = createValue(key, context)
            map[key] = createdValue
            postCompute(key, createdValue, data)
            createdValue
        }


    @Suppress("UNCHECKED_CAST")
    override fun getValueIfComputed(key: K): V? =
        map.getOrElse(key) { null as V }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy