summaryrefslogtreecommitdiff
path: root/core/src/commonMain/kotlin/coffee/liz/rookery/util/Hash.kt
blob: 8c7c4476e96803b6be6e8e509ad67e550550bb75 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package coffee.liz.rookery.util

/** FNV-1a 64-bit, hex encoded. Used for deterministic ids so re-imports are idempotent. */
fun fnv64(vararg parts: String): String {
    var h = -0x340d631b7bdddcdbL // 0xcbf29ce484222325
    for ((i, p) in parts.withIndex()) {
        if (i > 0) { h = h xor 0x1f; h *= 0x100000001b3L }
        for (b in p.encodeToByteArray()) {
            h = h xor (b.toLong() and 0xff)
            h *= 0x100000001b3L
        }
    }
    return h.toULong().toString(16).padStart(16, '0')
}

fun fnv64(bytes: ByteArray): String {
    var h = -0x340d631b7bdddcdbL
    for (b in bytes) { h = h xor (b.toLong() and 0xff); h *= 0x100000001b3L }
    return h.toULong().toString(16).padStart(16, '0')
}