Add method for calculating the K&R hash code of a CP-1252-encoded string

Signed-off-by: Graham <gpe@openrs2.dev>
bzip2
Graham 4 years ago
parent be7cc9ac8a
commit 7ab3b3d335
  1. 10
      util/src/main/java/dev/openrs2/util/StringUtils.kt
  2. 7
      util/src/test/java/dev/openrs2/util/StringUtilsTest.kt

@ -1,5 +1,7 @@
package dev.openrs2.util
import dev.openrs2.util.charset.Cp1252Charset
fun CharSequence.indefiniteArticle(): String {
require(isNotEmpty())
@ -8,3 +10,11 @@ fun CharSequence.indefiniteArticle(): String {
else -> "a"
}
}
fun CharSequence.krHashCode(): Int {
var hash = 0
for (c in this) {
hash = ((hash shl 5) - hash) + Cp1252Charset.encode(c)
}
return hash
}

@ -13,4 +13,11 @@ object StringUtilsTest {
"".indefiniteArticle()
}
}
@Test
fun testKrHashCode() {
assertEquals(0, "".krHashCode())
assertEquals(99162322, "hello".krHashCode())
assertEquals(92340183, "h€llo".krHashCode())
}
}

Loading…
Cancel
Save