chore: move hex encode and decode into a shared common util (#62)

This commit is contained in:
Fiereu authored and GitHub committed 2026-07-25 21:37:53 +02:00
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() }
}
})
@@ -4,13 +4,11 @@ import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.*
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
import de.fiereu.openmmo.common.utils.hexToBytes
private fun reserved(hex: String): Codec<Unit> =
object : Codec<Unit> {
private val bytes = seg(hex)
private val bytes = hex.hexToBytes()
override fun read(buf: ReadBuffer) {
if (bytes.isNotEmpty()) buf.readBytes(ByteArray(bytes.size))
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.net.game.packets.battle
import de.fiereu.bytecodec.*
import de.fiereu.openmmo.common.utils.hexToBytes
/**
* The field state for a wild encounter (opcode 0x30). Each side sends a monster count that sizes
@@ -15,11 +16,8 @@ data class BattleFieldStatePacket(
val wildParty: List<BattleMonBlock>,
)
private fun seg(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
private val PREAMBLE = seg("02000000000000000000000000ff000000000016000000ff00200006")
private val APPEARANCE = seg("ff00024c031aac0f00038001a400040000000000")
private val PREAMBLE = "02000000000000000000000000ff000000000016000000ff00200006".hexToBytes()
private val APPEARANCE = "ff00024c031aac0f00038001a400040000000000".hexToBytes()
object BattleFieldStatePacketCodec : PacketCodec<BattleFieldStatePacket>() {
override fun CodecScope<BattleFieldStatePacket>.body(): BattleFieldStatePacket {
@@ -2,14 +2,13 @@ package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.common.utils.toHex
import de.fiereu.openmmo.net.game.packets.battle.BattleMonBlock
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
private fun patrat(): BattleMonBlock =
BattleMonBlock(
slot = 1,
@@ -49,7 +48,7 @@ class BattleSwitchInPacketTest :
fullBlock = false,
)
val bytes = BattleSwitchInPacketCodec.encodeToBytes(packet)
bytes.hex() shouldBe "000000010000ef010600000000000003ff0000000066666666"
bytes.toHex() shouldBe "000000010000ef010600000000000003ff0000000066666666"
}
// A benched monster coming out carries its full block then its active detail. The block
@@ -2,16 +2,13 @@ package de.fiereu.openmmo.net.game
import de.fiereu.bytecodec.test.decodeBytes
import de.fiereu.bytecodec.test.encodeToBytes
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.common.utils.toHex
import de.fiereu.openmmo.net.game.packets.dialog.CreatureDataArg
import de.fiereu.openmmo.net.game.packets.dialog.DialogActionPacketCodec
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
private fun bytes(hex: String): ByteArray =
hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) }
class DialogActionPacketTest :
FunSpec({
// Every case is a real 0x21 dialog action from the NPC interaction capture.
@@ -25,15 +22,15 @@ class DialogActionPacketTest :
test("round-trips every captured dialog action byte for byte") {
captures.forEach { hex ->
val packet = DialogActionPacketCodec.decodeBytes(bytes(hex))
DialogActionPacketCodec.encodeToBytes(packet).hex() shouldBe hex
val packet = DialogActionPacketCodec.decodeBytes(hex.hexToBytes())
DialogActionPacketCodec.encodeToBytes(packet).toHex() shouldBe hex
}
}
test("decodes the fields of a dialog action carrying a creature arg") {
val packet =
DialogActionPacketCodec.decodeBytes(
bytes("0d04f80600010ae008bf86c4c01ab004000001000992d00300"))
"0d04f80600010ae008bf86c4c01ab004000001000992d00300".hexToBytes())
packet.flags shouldBe 0x0d.toByte()
packet.actionType shouldBe 0x04.toByte()
packet.textId shouldBe 0x010006f8
+1 -3
View File
@@ -1,5 +1,3 @@
# Retail ROMs live here for codegen (identified by GBA header game code + version, not filename).
# They are copyrighted and must never be committed. This .gitignore keeps the folder tracked
# while ignoring everything else in it.
# ROMs for codegen (identified by GBA header, not filename). Never commit them.
*
!.gitignore
@@ -6,6 +6,7 @@ import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.enums.ChatType
import de.fiereu.openmmo.common.enums.Language
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.common.utils.hexToBytes
import de.fiereu.openmmo.maps.MapManager
import de.fiereu.openmmo.net.game.codecs.SkinSet
import de.fiereu.openmmo.net.game.packets.CharacterEntry
@@ -42,9 +43,6 @@ import javax.inject.Singleton
private val log = KotlinLogging.logger {}
private fun hexToBytes(hex: String): ByteArray =
ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
// The world-flag table the client loads on join. Groups one to three are zlib streams that each
// decompress to a 67-byte flag block, the fourth is empty. The client reads real flag state while
// building the follower and party, so empty groups leave a lookup null and crash it.
@@ -55,7 +53,7 @@ private val WORLD_FLAG_GROUPS =
"789c637060a00434303032000012c500c2",
"",
)
.map(::hexToBytes)
.map(String::hexToBytes)
private const val POKE_BALL_ITEM_ID: Short = 5004
private const val POKE_BALL_OBJECT_ID = 0x0000000000015000L
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.server.login.auth
import de.fiereu.openmmo.common.enums.LoginState
import de.fiereu.openmmo.common.utils.toHex
import java.security.MessageDigest
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
@@ -16,10 +17,8 @@ interface UserService {
}
@Suppress("kotlin:S4790")
internal fun sha1Hex(value: String): String {
val sha1 = MessageDigest.getInstance("SHA-1").digest(value.toByteArray())
return sha1.joinToString("") { "%02x".format(it) }
}
internal fun sha1Hex(value: String): String =
MessageDigest.getInstance("SHA-1").digest(value.toByteArray()).toHex()
@Singleton
class InMemoryUserStore @Inject constructor() : UserService {
@@ -1,6 +1,7 @@
package de.fiereu.openmmo.server.login.auth
import de.fiereu.openmmo.common.enums.LoginState
import de.fiereu.openmmo.common.utils.toHex
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
@@ -46,7 +47,5 @@ class InMemoryUserStoreTest :
}
})
private fun sha1HexOf(input: String): String {
val digest = java.security.MessageDigest.getInstance("SHA-1").digest(input.toByteArray())
return digest.joinToString("") { "%02x".format(it) }
}
private fun sha1HexOf(input: String): String =
java.security.MessageDigest.getInstance("SHA-1").digest(input.toByteArray()).toHex()