org.jetbrains.kotlin.fir.caches.FirThreadUnsafeCachesFactory.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-compiler-embeddable Show documentation
Show all versions of kotlin-compiler-embeddable Show documentation
the Kotlin compiler embeddable
/*
* 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 = createValue)
override fun createCache(
initialCapacity: Int,
loadFactor: Float,
createValue: (K, CONTEXT) -> V
): FirCache =
FirThreadUnsafeCache(
NullableMap(HashMap(initialCapacity, loadFactor)),
createValue
)
override fun createCacheWithPostCompute(
createValue: (K, CONTEXT) -> Pair,
postCompute: (K, V, DATA) -> Unit
): FirCache =
FirThreadUnsafeCacheWithPostCompute(createValue, postCompute)
override fun createLazyValue(createValue: () -> V): FirLazyValue =
FirThreadUnsafeValue(createValue)
}
@Suppress("UNCHECKED_CAST")
private class FirThreadUnsafeCache(
private val map: NullableMap = NullableMap(),
private val createValue: (K, CONTEXT) -> V
) : FirCache() {
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 }
}
private class FirThreadUnsafeValue(createValue: () -> V) : FirLazyValue() {
private val lazyValue by lazy(LazyThreadSafetyMode.NONE, createValue)
override fun getValue(): V = lazyValue
}