chore: move hex encode and decode into a shared common util (#62)
This commit is contained in:
1 parent
9c52eeb8c6
commit
35f498f0de
10 files changed
+70
-35
No files matched your search
@@ -0,0 +1,20 @@
|
||||
package de.fiereu.openmmo.common.utils
|
||||
|
||||
/**
|
||||
* Decodes a hex string into the bytes it spells, for example `"0c2e"` into `[0x0c, 0x2e]`.
|
||||
*
|
||||
* @throws IllegalArgumentException if the length is odd or a character is not a hex digit.
|
||||
*/
|
||||
fun String.hexToBytes(): ByteArray {
|
||||
require(length % 2 == 0) { "hex string must have an even length, got $length" }
|
||||
return ByteArray(length / 2) {
|
||||
val index = it * 2
|
||||
val high = Character.digit(this[index], 16)
|
||||
val low = Character.digit(this[index + 1], 16)
|
||||
require(high >= 0 && low >= 0) { "invalid hex digit at index $index" }
|
||||
((high shl 4) or low).toByte()
|
||||
}
|
||||
}
|
||||
|
||||
/** Encodes the bytes as a lowercase hex string without separators, for example `"0c2e"`. */
|
||||
fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
|
||||
@@ -0,0 +1,29 @@
|
||||
package de.fiereu.openmmo.common.utils
|
||||
|
||||
import io.kotest.assertions.throwables.shouldThrow
|
||||
import io.kotest.core.spec.style.FunSpec
|
||||
import io.kotest.matchers.shouldBe
|
||||
|
||||
class HexTest :
|
||||
FunSpec({
|
||||
test("decodes a hex string into bytes") {
|
||||
"0c2e0dff00".hexToBytes() shouldBe byteArrayOf(0x0c, 0x2e, 0x0d, -1, 0)
|
||||
}
|
||||
|
||||
test("decodes upper case digits") { "FF0A".hexToBytes() shouldBe byteArrayOf(-1, 0x0a) }
|
||||
|
||||
test("encodes bytes as lower case hex") {
|
||||
byteArrayOf(0x0c, 0x2e, 0x0d, -1, 0).toHex() shouldBe "0c2e0dff00"
|
||||
}
|
||||
|
||||
test("round-trips an empty value") {
|
||||
"".hexToBytes() shouldBe byteArrayOf()
|
||||
byteArrayOf().toHex() shouldBe ""
|
||||
}
|
||||
|
||||
test("rejects an odd length") { shouldThrow<IllegalArgumentException> { "abc".hexToBytes() } }
|
||||
|
||||
test("rejects a non hex digit") {
|
||||
shouldThrow<IllegalArgumentException> { "0g".hexToBytes() }
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user