[kotlin-tooling-core] Add Interner.clear API

This commit is contained in:
Sebastian Sellmair
2023-03-20 11:00:44 +01:00
committed by Space Team
parent 22b0a8d9fb
commit f5fadc1f68
3 changed files with 24 additions and 1 deletions
@@ -145,6 +145,7 @@ public abstract interface class org/jetbrains/kotlin/tooling/core/HasMutableExtr
}
public abstract interface class org/jetbrains/kotlin/tooling/core/Interner {
public abstract fun clear ()V
public abstract fun getOrPut (Ljava/lang/Object;)Ljava/lang/Object;
}
@@ -20,6 +20,7 @@ fun Interner(lock: Lock? = null): Interner = InternerImpl(Strong(), lock)
interface Interner {
fun <T : Any> getOrPut(value: T): T
fun clear()
}
private class InternerImpl(
@@ -29,6 +30,7 @@ private class InternerImpl(
interface Store {
fun <T : Any> getOrPut(value: T): T
fun clear()
class Weak : Store {
private val references = WeakHashMap<Any, WeakReference<Any>>()
@@ -39,6 +41,10 @@ private class InternerImpl(
value
}) as T
}
override fun clear() {
return references.clear()
}
}
@Suppress("UNCHECKED_CAST")
@@ -47,10 +53,22 @@ private class InternerImpl(
override fun <T : Any> getOrPut(value: T): T {
return references.getOrPut(value) { value } as T
}
override fun clear() {
return references.clear()
}
}
}
override fun <T : Any> getOrPut(value: T): T {
return lock?.withLock { store.getOrPut(value) } ?: store.getOrPut(value)
return withLockIfAny { store.getOrPut(value) }
}
override fun clear() {
return withLockIfAny { store.clear() }
}
private inline fun <T> withLockIfAny(action: () -> T): T {
return if (lock != null) lock.withLock(action) else action()
}
}
@@ -8,6 +8,7 @@
package org.jetbrains.kotlin.tooling.core
import org.junit.Test
import kotlin.test.assertNotSame
import kotlin.test.assertSame
class InternerTest {
@@ -36,5 +37,8 @@ class InternerTest {
assertSame(sample1A, interner.getOrPut(sample1B))
assertSame(sample0A, interner.getOrPut(sample0A))
assertSame(sample0A, interner.getOrPut(sample0B))
interner.clear()
assertNotSame(sample0A, interner.getOrPut(Sample(0)))
}
}