Fix ref hash strategy

This commit is contained in:
DBotThePony 2023-08-19 17:38:19 +07:00
parent 159c82cadd
commit 9d79e52c43
Signed by: DBot
GPG Key ID: DCC23B5715498507
2 changed files with 5 additions and 32 deletions

View File

@ -4,42 +4,15 @@ import it.unimi.dsi.fastutil.Hash
import java.lang.ref.Reference
object ReferenceHashStrategy : Hash.Strategy<Any?> {
@Suppress("UNCHECKED_CAST")
override fun equals(a: Any?, b: Any?): Boolean {
if (a === b) return true
if (a == null || b == null) return false
if (a is Reference<*>) {
if (a.refersTo(null) || b == null) return false
if (b is Reference<*>) {
if (b.refersTo(null)) return false
return (b as Reference<Any>).refersTo(a.get() ?: return false)
} else {
return (a as Reference<Any>).refersTo(b)
}
if (b is Reference<*>) return a.get() == b.get()
return a.get() == b
} else if (b is Reference<*>) {
if (b.refersTo(null) || a == null) return false
return (b as Reference<Any>).refersTo(a)
}
return a == b
}
override fun hashCode(o: Any?): Int {
return o.hashCode()
}
}
object StrictReferenceHashStrategy : Hash.Strategy<Any?> {
@Suppress("UNCHECKED_CAST")
override fun equals(a: Any?, b: Any?): Boolean {
if (a === b) return true
if (a is Reference<*>) {
if (b is Reference<*>) return false
return b != null && (a as Reference<Any>).refersTo(b)
} else if (b is Reference<*>) {
return a != null && (b as Reference<Any>).refersTo(a)
return b.get() == a
} else {
return a == b
}

View File

@ -8,7 +8,7 @@ import java.lang.ref.ReferenceQueue
class WeakHashSet<E : Any>(initialCapacity: Int = 16, loadFactor: Float = 0.75f, linked: Boolean = false) : MutableSet<E> {
private val queue = ReferenceQueue<E>()
private val backing: ObjectSet<Any> = if (linked) ObjectLinkedOpenCustomHashSet(initialCapacity, loadFactor, StrictReferenceHashStrategy) else ObjectOpenCustomHashSet(initialCapacity, loadFactor, StrictReferenceHashStrategy)
private val backing: ObjectSet<Any> = if (linked) ObjectLinkedOpenCustomHashSet(initialCapacity, loadFactor, ReferenceHashStrategy) else ObjectOpenCustomHashSet(initialCapacity, loadFactor, ReferenceHashStrategy)
private fun purge() {
var next = queue.poll()