aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/collections/InstanceList.kt
blob: fd8c78600f4c741611f02e535307e990d8fb72a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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)
        }
    }
}