https://kotlinlang.org logo
Title
c

Carlos Ballesteros Velasco

05/23/2023, 3:43 PM
Hello. I'm trying to simulate
System.identityHashCode
from java in WASM. In JS I had this code: But I guess this might not work in WASM. Does anybody know if it is possible to get a stable pointer to the object or a numeric id identifying the object?
b

bashor

05/23/2023, 6:22 PM
Does your objects override hashCode? Why do you not use
object.hashCode()
?
There is no pointer
c

Carlos Ballesteros Velasco

05/23/2023, 6:45 PM
Well, this is something generic because I have an:
IdentityHashMap
that does that. It is used there but also exposed so some people use it.
I have implemented like this:
@JsFun("""(obj) => {
    if (window.IDENTITY_HASH_CODE_SYMBOL === undefined) {
        window.IDENTITY_HASH_CODE_SYMBOL = Symbol("KotlinIdentityHashCode");
        window.lastIdentityHashCodeId = 0;
    }
    if (obj == null) return 0;
    if (obj[window.IDENTITY_HASH_CODE_SYMBOL] === undefined) {
        obj[window.IDENTITY_HASH_CODE_SYMBOL] = (window.lastIdentityHashCodeId = window.lastIdentityHashCodeId + 1 | 0);
    }
    return obj[window.IDENTITY_HASH_CODE_SYMBOL];
}""")
internal external fun anyIdentityHashCodeJsRef(ref: JsReference<Any>): Int

internal actual fun anyIdentityHashCode(obj: Any?): Int {
    if (obj == null) return 0
    return anyIdentityHashCodeJsRef(obj.toJsReference())
    //println("anyIdentityHashCode not implemented in WASM!")
    //return -1
}
though untested yet. It will work if toJsReference() returns always the same object, and won't in the other case