aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/collections/InstanceList.kt
diff options
context:
space:
mode:
authorLinnea Gräf <nea@nea.moe>2024-09-24 11:40:15 +0200
committerLinnea Gräf <nea@nea.moe>2024-09-24 11:40:15 +0200
commit420f2a61e1cc64d68bf03825e8fd70cf49ac6a01 (patch)
tree540f2beaf99bda96af3c145cbfe81faebba76bee /src/main/kotlin/util/collections/InstanceList.kt
parent64099bd2628490b06392766c6d1b9425f26788a3 (diff)
downloadfirmament-420f2a61e1cc64d68bf03825e8fd70cf49ac6a01.tar.gz
firmament-420f2a61e1cc64d68bf03825e8fd70cf49ac6a01.tar.bz2
firmament-420f2a61e1cc64d68bf03825e8fd70cf49ac6a01.zip
Use weak caches for custom textures
Diffstat (limited to 'src/main/kotlin/util/collections/InstanceList.kt')
-rw-r--r--src/main/kotlin/util/collections/InstanceList.kt57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/main/kotlin/util/collections/InstanceList.kt b/src/main/kotlin/util/collections/InstanceList.kt
new file mode 100644
index 0000000..fd8c786
--- /dev/null
+++ b/src/main/kotlin/util/collections/InstanceList.kt
@@ -0,0 +1,57 @@
+package moe.nea.firmament.util.collections
+
+import java.lang.ref.ReferenceQueue
+import java.lang.ref.WeakReference
+
+class InstanceList<T : Any>(val name: String) {
+ val queue = object : ReferenceQueue<T>() {}
+ val set = mutableSetOf<Ref>()
+
+ val size: Int
+ get() {
+ clearOldReferences()
+ return set.size
+ }
+
+ fun clearOldReferences() {
+ while (true) {
+ val reference = queue.poll() ?: break
+ set.remove(reference)
+ }
+ }
+
+ fun getAll(): List<T> {
+ clearOldReferences()
+ return set.mapNotNull { it.get() }
+ }
+
+ fun add(t: T) {
+ set.add(Ref(t))
+ }
+
+ init {
+ if (init)
+ allInstances.add(this)
+ }
+
+ inner class Ref(referent: T) : WeakReference<T>(referent) {
+ val hashCode = System.identityHashCode(referent)
+ override fun equals(other: Any?): Boolean {
+ return other is InstanceList<*>.Ref && hashCode == other.hashCode && get() === other.get()
+ }
+
+ override fun hashCode(): Int {
+ return hashCode
+ }
+ }
+
+ companion object {
+ private var init = false
+ val allInstances = InstanceList<InstanceList<*>>("InstanceLists")
+
+ init {
+ init = true
+ allInstances.add(allInstances)
+ }
+ }
+}