From 8048827121f46cbaf6209789f7e22dee02c26d60 Mon Sep 17 00:00:00 2001 From: Fiereu Date: Sun, 24 May 2026 11:20:02 +0200 Subject: [PATCH] feat(bytecodec): add bidirectional binary codec library --- bytecodec/build.gradle.kts | 6 + .../main/kotlin/de/fiereu/bytecodec/Atoms.kt | 328 ++++++++++++++++++ .../main/kotlin/de/fiereu/bytecodec/Buffer.kt | 19 + .../kotlin/de/fiereu/bytecodec/Buffers.kt | 88 +++++ .../main/kotlin/de/fiereu/bytecodec/Codec.kt | 7 + .../kotlin/de/fiereu/bytecodec/Combinators.kt | 267 ++++++++++++++ .../kotlin/de/fiereu/bytecodec/Exceptions.kt | 14 + .../kotlin/de/fiereu/bytecodec/PacketCodec.kt | 56 +++ .../de/fiereu/bytecodec/test/TestHelpers.kt | 47 +++ .../kotlin/de/fiereu/bytecodec/AtomsTest.kt | 140 ++++++++ .../kotlin/de/fiereu/bytecodec/BuffersTest.kt | 50 +++ .../de/fiereu/bytecodec/CombinatorsTest.kt | 134 +++++++ .../de/fiereu/bytecodec/PacketCodecTest.kt | 109 ++++++ settings.gradle.kts | 1 + 14 files changed, 1266 insertions(+) create mode 100644 bytecodec/build.gradle.kts create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Atoms.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffer.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffers.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Codec.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Combinators.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/Exceptions.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt create mode 100644 bytecodec/src/main/kotlin/de/fiereu/bytecodec/test/TestHelpers.kt create mode 100644 bytecodec/src/test/kotlin/de/fiereu/bytecodec/AtomsTest.kt create mode 100644 bytecodec/src/test/kotlin/de/fiereu/bytecodec/BuffersTest.kt create mode 100644 bytecodec/src/test/kotlin/de/fiereu/bytecodec/CombinatorsTest.kt create mode 100644 bytecodec/src/test/kotlin/de/fiereu/bytecodec/PacketCodecTest.kt diff --git a/bytecodec/build.gradle.kts b/bytecodec/build.gradle.kts new file mode 100644 index 0000000..1b734bf --- /dev/null +++ b/bytecodec/build.gradle.kts @@ -0,0 +1,6 @@ +plugins { + id("buildsrc.convention.kotlin-jvm") + id("buildsrc.convention.spotless") +} + +dependencies { testImplementation(libs.bundles.kotest) } diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Atoms.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Atoms.kt new file mode 100644 index 0000000..6452221 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Atoms.kt @@ -0,0 +1,328 @@ +package de.fiereu.bytecodec + +object Bool : Codec { + override fun read(buf: ReadBuffer): Boolean = buf.readByte() != 0.toByte() + + override fun write(buf: WriteBuffer, value: Boolean) { + buf.writeByte(if (value) 1 else 0) + } +} + +object S8 : Codec { + override fun read(buf: ReadBuffer): Byte = buf.readByte() + + override fun write(buf: WriteBuffer, value: Byte) { + buf.writeByte(value) + } +} + +object U8 : Codec { + override fun read(buf: ReadBuffer): Int = buf.readByte().toInt() and 0xFF + + override fun write(buf: WriteBuffer, value: Int) { + require(value in 0..0xFF) { "U8 out of range: $value" } + buf.writeByte(value.toByte()) + } +} + +object S16LE : Codec { + override fun read(buf: ReadBuffer): Short { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + return ((b1 shl 8) or b0).toShort() + } + + override fun write(buf: WriteBuffer, value: Short) { + val v = value.toInt() + buf.writeByte((v and 0xFF).toByte()) + buf.writeByte(((v ushr 8) and 0xFF).toByte()) + } +} + +object S16BE : Codec { + override fun read(buf: ReadBuffer): Short { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + return ((b0 shl 8) or b1).toShort() + } + + override fun write(buf: WriteBuffer, value: Short) { + val v = value.toInt() + buf.writeByte(((v ushr 8) and 0xFF).toByte()) + buf.writeByte((v and 0xFF).toByte()) + } +} + +object U16LE : Codec { + override fun read(buf: ReadBuffer): Int { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + return (b1 shl 8) or b0 + } + + override fun write(buf: WriteBuffer, value: Int) { + require(value in 0..0xFFFF) { "U16 out of range: $value" } + buf.writeByte((value and 0xFF).toByte()) + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + } +} + +object U16BE : Codec { + override fun read(buf: ReadBuffer): Int { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + return (b0 shl 8) or b1 + } + + override fun write(buf: WriteBuffer, value: Int) { + require(value in 0..0xFFFF) { "U16 out of range: $value" } + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + buf.writeByte((value and 0xFF).toByte()) + } +} + +object S32LE : Codec { + override fun read(buf: ReadBuffer): Int { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + val b2 = buf.readByte().toInt() and 0xFF + val b3 = buf.readByte().toInt() and 0xFF + return (b3 shl 24) or (b2 shl 16) or (b1 shl 8) or b0 + } + + override fun write(buf: WriteBuffer, value: Int) { + buf.writeByte((value and 0xFF).toByte()) + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + buf.writeByte(((value ushr 16) and 0xFF).toByte()) + buf.writeByte(((value ushr 24) and 0xFF).toByte()) + } +} + +object S32BE : Codec { + override fun read(buf: ReadBuffer): Int { + val b0 = buf.readByte().toInt() and 0xFF + val b1 = buf.readByte().toInt() and 0xFF + val b2 = buf.readByte().toInt() and 0xFF + val b3 = buf.readByte().toInt() and 0xFF + return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3 + } + + override fun write(buf: WriteBuffer, value: Int) { + buf.writeByte(((value ushr 24) and 0xFF).toByte()) + buf.writeByte(((value ushr 16) and 0xFF).toByte()) + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + buf.writeByte((value and 0xFF).toByte()) + } +} + +object U32LE : Codec { + override fun read(buf: ReadBuffer): Long { + val b0 = buf.readByte().toLong() and 0xFF + val b1 = buf.readByte().toLong() and 0xFF + val b2 = buf.readByte().toLong() and 0xFF + val b3 = buf.readByte().toLong() and 0xFF + return (b3 shl 24) or (b2 shl 16) or (b1 shl 8) or b0 + } + + override fun write(buf: WriteBuffer, value: Long) { + require(value in 0L..0xFFFFFFFFL) { "U32 out of range: $value" } + buf.writeByte((value and 0xFF).toByte()) + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + buf.writeByte(((value ushr 16) and 0xFF).toByte()) + buf.writeByte(((value ushr 24) and 0xFF).toByte()) + } +} + +object U32BE : Codec { + override fun read(buf: ReadBuffer): Long { + val b0 = buf.readByte().toLong() and 0xFF + val b1 = buf.readByte().toLong() and 0xFF + val b2 = buf.readByte().toLong() and 0xFF + val b3 = buf.readByte().toLong() and 0xFF + return (b0 shl 24) or (b1 shl 16) or (b2 shl 8) or b3 + } + + override fun write(buf: WriteBuffer, value: Long) { + require(value in 0L..0xFFFFFFFFL) { "U32 out of range: $value" } + buf.writeByte(((value ushr 24) and 0xFF).toByte()) + buf.writeByte(((value ushr 16) and 0xFF).toByte()) + buf.writeByte(((value ushr 8) and 0xFF).toByte()) + buf.writeByte((value and 0xFF).toByte()) + } +} + +object S64LE : Codec { + override fun read(buf: ReadBuffer): Long { + var result = 0L + var shift = 0 + repeat(8) { + result = result or ((buf.readByte().toLong() and 0xFF) shl shift) + shift += 8 + } + return result + } + + override fun write(buf: WriteBuffer, value: Long) { + var v = value + repeat(8) { + buf.writeByte((v and 0xFF).toByte()) + v = v ushr 8 + } + } +} + +object S64BE : Codec { + override fun read(buf: ReadBuffer): Long { + var result = 0L + repeat(8) { result = (result shl 8) or (buf.readByte().toLong() and 0xFF) } + return result + } + + override fun write(buf: WriteBuffer, value: Long) { + var shift = 56 + repeat(8) { + buf.writeByte(((value ushr shift) and 0xFF).toByte()) + shift -= 8 + } + } +} + +object F32LE : Codec { + override fun read(buf: ReadBuffer): Float = Float.fromBits(S32LE.read(buf)) + + override fun write(buf: WriteBuffer, value: Float) { + S32LE.write(buf, value.toRawBits()) + } +} + +object F32BE : Codec { + override fun read(buf: ReadBuffer): Float = Float.fromBits(S32BE.read(buf)) + + override fun write(buf: WriteBuffer, value: Float) { + S32BE.write(buf, value.toRawBits()) + } +} + +object F64LE : Codec { + override fun read(buf: ReadBuffer): Double = Double.fromBits(S64LE.read(buf)) + + override fun write(buf: WriteBuffer, value: Double) { + S64LE.write(buf, value.toRawBits()) + } +} + +object F64BE : Codec { + override fun read(buf: ReadBuffer): Double = Double.fromBits(S64BE.read(buf)) + + override fun write(buf: WriteBuffer, value: Double) { + S64BE.write(buf, value.toRawBits()) + } +} + +fun fixedBytes(n: Int): Codec { + require(n >= 0) { "fixedBytes negative size: $n" } + return object : Codec { + override fun read(buf: ReadBuffer): ByteArray { + val arr = ByteArray(n) + if (n > 0) buf.readBytes(arr) + return arr + } + + override fun write(buf: WriteBuffer, value: ByteArray) { + if (value.size != n) { + throw MalformedPacketException("fixedBytes($n) got ${value.size}") + } + if (n > 0) buf.writeBytes(value) + } + } +} + +fun unknownBytes(n: Int): Codec = fixedBytes(n) + +fun reserved(byte: Int, strict: Boolean = false): Codec { + val literal = (byte and 0xFF).toByte() + return object : Codec { + override fun read(buf: ReadBuffer) { + val read = buf.readByte() + if (strict && read != literal) { + throw ReservedByteMismatchException(byte and 0xFF, read.toInt() and 0xFF) + } + } + + override fun write(buf: WriteBuffer, value: Unit) { + buf.writeByte(literal) + } + } +} + +fun padding(n: Int, fill: Byte = 0): Codec { + require(n >= 0) { "padding negative size: $n" } + return object : Codec { + override fun read(buf: ReadBuffer) { + if (n > 0) buf.skip(n) + } + + override fun write(buf: WriteBuffer, value: Unit) { + repeat(n) { buf.writeByte(fill) } + } + } +} + +fun skip(n: Int): Codec = padding(n) + +object Utf16LeNullTerminated : Codec { + override fun read(buf: ReadBuffer): String { + val out = java.io.ByteArrayOutputStream() + while (true) { + val lo = buf.readByte() + val hi = buf.readByte() + if (lo == 0.toByte() && hi == 0.toByte()) break + out.write(lo.toInt() and 0xFF) + out.write(hi.toInt() and 0xFF) + } + return String(out.toByteArray(), Charsets.UTF_16LE) + } + + override fun write(buf: WriteBuffer, value: String) { + buf.writeBytes(value.toByteArray(Charsets.UTF_16LE)) + buf.writeByte(0) + buf.writeByte(0) + } +} + +object Utf16BeNullTerminated : Codec { + override fun read(buf: ReadBuffer): String { + val out = java.io.ByteArrayOutputStream() + while (true) { + val hi = buf.readByte() + val lo = buf.readByte() + if (hi == 0.toByte() && lo == 0.toByte()) break + out.write(hi.toInt() and 0xFF) + out.write(lo.toInt() and 0xFF) + } + return String(out.toByteArray(), Charsets.UTF_16BE) + } + + override fun write(buf: WriteBuffer, value: String) { + buf.writeBytes(value.toByteArray(Charsets.UTF_16BE)) + buf.writeByte(0) + buf.writeByte(0) + } +} + +object AsciiNullTerminated : Codec { + override fun read(buf: ReadBuffer): String { + val out = java.io.ByteArrayOutputStream() + while (true) { + val b = buf.readByte() + if (b == 0.toByte()) break + out.write(b.toInt() and 0xFF) + } + return String(out.toByteArray(), Charsets.US_ASCII) + } + + override fun write(buf: WriteBuffer, value: String) { + buf.writeBytes(value.toByteArray(Charsets.US_ASCII)) + buf.writeByte(0) + } +} diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffer.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffer.kt new file mode 100644 index 0000000..3f58b1f --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffer.kt @@ -0,0 +1,19 @@ +package de.fiereu.bytecodec + +interface ReadBuffer { + fun readByte(): Byte + + fun readBytes(dst: ByteArray, offset: Int = 0, length: Int = dst.size - offset) + + fun skip(n: Int) + + fun remaining(): Int +} + +interface WriteBuffer { + fun writeByte(value: Byte) + + fun writeBytes(src: ByteArray, offset: Int = 0, length: Int = src.size - offset) +} + +interface Buffer : ReadBuffer, WriteBuffer diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffers.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffers.kt new file mode 100644 index 0000000..6d3e116 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Buffers.kt @@ -0,0 +1,88 @@ +package de.fiereu.bytecodec + +import java.nio.ByteBuffer + +class ByteArrayReadBuffer( + private val array: ByteArray, + private val offset: Int = 0, + private val length: Int = array.size - offset, +) : ReadBuffer { + init { + require(offset >= 0) { "offset < 0" } + require(length >= 0) { "length < 0" } + require(offset + length <= array.size) { "offset + length > array.size" } + } + + private var pos = 0 + + override fun readByte(): Byte { + if (pos >= length) throw IndexOutOfBoundsException("read past end") + return array[offset + pos++] + } + + override fun readBytes(dst: ByteArray, offset: Int, length: Int) { + if (this.pos + length > this.length) throw IndexOutOfBoundsException("read past end") + System.arraycopy(array, this.offset + pos, dst, offset, length) + pos += length + } + + override fun skip(n: Int) { + if (n < 0) throw IndexOutOfBoundsException("negative skip") + if (pos + n > length) throw IndexOutOfBoundsException("skip past end") + pos += n + } + + override fun remaining(): Int = length - pos +} + +class GrowableWriteBuffer(initialCapacity: Int = 256) : WriteBuffer { + private var buf: ByteArray = ByteArray(initialCapacity.coerceAtLeast(16)) + private var pos: Int = 0 + + fun size(): Int = pos + + fun toByteArray(): ByteArray = buf.copyOf(pos) + + private fun ensure(extra: Int) { + val needed = pos + extra + if (needed <= buf.size) return + var newSize = buf.size + while (newSize < needed) newSize *= 2 + buf = buf.copyOf(newSize) + } + + override fun writeByte(value: Byte) { + ensure(1) + buf[pos++] = value + } + + override fun writeBytes(src: ByteArray, offset: Int, length: Int) { + ensure(length) + System.arraycopy(src, offset, buf, pos, length) + pos += length + } +} + +class NioReadBuffer(private val nio: ByteBuffer) : ReadBuffer { + override fun readByte(): Byte = nio.get() + + override fun readBytes(dst: ByteArray, offset: Int, length: Int) { + nio.get(dst, offset, length) + } + + override fun skip(n: Int) { + nio.position(nio.position() + n) + } + + override fun remaining(): Int = nio.remaining() +} + +class NioWriteBuffer(private val nio: ByteBuffer) : WriteBuffer { + override fun writeByte(value: Byte) { + nio.put(value) + } + + override fun writeBytes(src: ByteArray, offset: Int, length: Int) { + nio.put(src, offset, length) + } +} diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Codec.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Codec.kt new file mode 100644 index 0000000..1062f56 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Codec.kt @@ -0,0 +1,7 @@ +package de.fiereu.bytecodec + +interface Codec { + fun read(buf: ReadBuffer): T + + fun write(buf: WriteBuffer, value: T) +} diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Combinators.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Combinators.kt new file mode 100644 index 0000000..da8c450 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Combinators.kt @@ -0,0 +1,267 @@ +package de.fiereu.bytecodec + +import java.nio.charset.Charset + +fun Codec.imap(decode: (T) -> R, encode: (R) -> T): Codec { + val inner = this + return object : Codec { + override fun read(buf: ReadBuffer): R = decode(inner.read(buf)) + + override fun write(buf: WriteBuffer, value: R) { + inner.write(buf, encode(value)) + } + } +} + +fun Codec.imapCatching( + decode: (T) -> R, + encode: (R) -> T, + onError: (T, Throwable) -> String = { v, _ -> "Cannot decode $v" }, +): Codec { + val inner = this + return object : Codec { + override fun read(buf: ReadBuffer): R { + val raw = inner.read(buf) + return try { + decode(raw) + } catch (e: CodecException) { + throw e + } catch (e: Throwable) { + throw MalformedPacketException(onError(raw, e), e) + } + } + + override fun write(buf: WriteBuffer, value: R) { + inner.write(buf, encode(value)) + } + } +} + +fun Codec.listPrefixed(prefix: Codec): Codec> { + val inner = this + return object : Codec> { + override fun read(buf: ReadBuffer): List { + val n = prefix.read(buf) + if (n < 0) throw MalformedPacketException("negative list length: $n") + val list = ArrayList(n.coerceAtMost(1024)) + repeat(n) { list.add(inner.read(buf)) } + return list + } + + override fun write(buf: WriteBuffer, value: List) { + prefix.write(buf, value.size) + for (item in value) inner.write(buf, item) + } + } +} + +fun Codec.repeat(count: Int): Codec> { + require(count >= 0) { "repeat negative count: $count" } + val inner = this + return object : Codec> { + override fun read(buf: ReadBuffer): List = List(count) { inner.read(buf) } + + override fun write(buf: WriteBuffer, value: List) { + if (value.size != count) { + throw MalformedPacketException("repeat($count) got ${value.size}") + } + for (item in value) inner.write(buf, item) + } + } +} + +fun bytesPrefixed(prefix: Codec): Codec = + object : Codec { + override fun read(buf: ReadBuffer): ByteArray { + val n = prefix.read(buf) + if (n < 0) throw MalformedPacketException("negative byte length: $n") + val arr = ByteArray(n) + if (n > 0) buf.readBytes(arr) + return arr + } + + override fun write(buf: WriteBuffer, value: ByteArray) { + prefix.write(buf, value.size) + if (value.isNotEmpty()) buf.writeBytes(value) + } + } + +fun stringPrefixed(prefix: Codec, charset: Charset): Codec = + object : Codec { + override fun read(buf: ReadBuffer): String { + val n = prefix.read(buf) + if (n < 0) throw MalformedPacketException("negative string length: $n") + val arr = ByteArray(n) + if (n > 0) buf.readBytes(arr) + return String(arr, charset) + } + + override fun write(buf: WriteBuffer, value: String) { + val arr = value.toByteArray(charset) + prefix.write(buf, arr.size) + if (arr.isNotEmpty()) buf.writeBytes(arr) + } + } + +inline fun > enumByOrdinalByte(): Codec { + val values = enumValues() + val name = E::class.simpleName ?: "enum" + return U8.imapCatching( + decode = { ord -> + if (ord !in values.indices) { + throw MalformedPacketException("ordinal $ord out of range for $name") + } + values[ord] + }, + encode = { it.ordinal }, + ) +} + +inline fun > enumByOrdinalU16LE(): Codec { + val values = enumValues() + val name = E::class.simpleName ?: "enum" + return U16LE.imapCatching( + decode = { ord -> + if (ord !in values.indices) { + throw MalformedPacketException("ordinal $ord out of range for $name") + } + values[ord] + }, + encode = { it.ordinal }, + ) +} + +fun > enumBy( + prefix: Codec, + lookup: (Int) -> E, + keyOf: (E) -> Int, +): Codec = + object : Codec { + override fun read(buf: ReadBuffer): E { + val key = prefix.read(buf) + return try { + lookup(key) + } catch (e: CodecException) { + throw e + } catch (e: Throwable) { + throw MalformedPacketException("no enum value for key $key", e) + } + } + + override fun write(buf: WriteBuffer, value: E) { + prefix.write(buf, keyOf(value)) + } + } + +fun choose( + tag: Codec, + identify: (T) -> Int, + vararg branches: Pair>, +): Codec { + val byTag: Map> = branches.toMap() + require(byTag.size == branches.size) { "duplicate branch tags in choose" } + return object : Codec { + override fun read(buf: ReadBuffer): T { + val t = tag.read(buf) + val branch = byTag[t] ?: throw UnknownTagException(t) + return branch.read(buf) + } + + override fun write(buf: WriteBuffer, value: T) { + val t = identify(value) + val branch = + byTag[t] + ?: throw MalformedPacketException("identify returned unknown tag 0x${t.toString(16)}") + tag.write(buf, t) + @Suppress("UNCHECKED_CAST") (branch as Codec).write(buf, value) + } + } +} + +fun Codec.optional(flag: Codec = Bool): Codec { + val inner = this + return object : Codec { + override fun read(buf: ReadBuffer): T? { + val present = flag.read(buf) + return if (present) inner.read(buf) else null + } + + override fun write(buf: WriteBuffer, value: T?) { + flag.write(buf, value != null) + if (value != null) inner.write(buf, value) + } + } +} + +fun Codec.then(other: Codec): Codec> { + val first = this + return object : Codec> { + override fun read(buf: ReadBuffer): Pair = first.read(buf) to other.read(buf) + + override fun write(buf: WriteBuffer, value: Pair) { + first.write(buf, value.first) + other.write(buf, value.second) + } + } +} + +interface BitsBuilder { + fun bit(index: Int, name: String) +} + +class BitSet32 +internal constructor( + internal val raw: Int, + internal val byName: Map, +) { + operator fun get(index: Int): Boolean { + require(index in 0..31) { "bit index out of range: $index" } + return (raw ushr index) and 1 != 0 + } + + operator fun get(name: String): Boolean { + val i = byName[name] ?: error("unknown bit name: $name") + return get(i) + } + + fun toRaw(): Int = raw + + override fun equals(other: Any?): Boolean = other is BitSet32 && other.raw == raw + + override fun hashCode(): Int = raw +} + +class BitsCodec +internal constructor( + private val backing: Codec, + private val byName: Map, +) : Codec { + override fun read(buf: ReadBuffer): BitSet32 = BitSet32(backing.read(buf), byName) + + override fun write(buf: WriteBuffer, value: BitSet32) { + backing.write(buf, value.raw) + } + + fun of(vararg bits: Pair): BitSet32 { + var raw = 0 + for ((name, set) in bits) { + val i = byName[name] ?: error("unknown bit name: $name") + if (set) raw = raw or (1 shl i) + } + return BitSet32(raw, byName) + } +} + +fun bitsLE(backing: Codec, builder: BitsBuilder.() -> Unit): BitsCodec { + val map = LinkedHashMap() + val b = + object : BitsBuilder { + override fun bit(index: Int, name: String) { + require(index in 0..31) { "bit index out of range: $index" } + require(name !in map) { "duplicate bit name: $name" } + map[name] = index + } + } + b.builder() + return BitsCodec(backing, map) +} diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Exceptions.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Exceptions.kt new file mode 100644 index 0000000..f994180 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/Exceptions.kt @@ -0,0 +1,14 @@ +package de.fiereu.bytecodec + +open class CodecException(message: String, cause: Throwable? = null) : + RuntimeException(message, cause) + +class MalformedPacketException(message: String, cause: Throwable? = null) : + CodecException(message, cause) + +class UnknownTagException(val tag: Int) : CodecException("No branch for tag 0x${tag.toString(16)}") + +class ReservedByteMismatchException(val expected: Int, val actual: Int) : + CodecException( + "Expected reserved 0x${expected.toString(16)}, got 0x${actual.toString(16)}", + ) diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt new file mode 100644 index 0000000..2bec106 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/PacketCodec.kt @@ -0,0 +1,56 @@ +package de.fiereu.bytecodec + +interface CodecScope

{ + fun field(codec: Codec, get: (P) -> T): T + + fun structural(codec: Codec) +} + +internal class ReadingScope

(private val buf: ReadBuffer) : CodecScope

{ + override fun field(codec: Codec, get: (P) -> T): T = codec.read(buf) + + override fun structural(codec: Codec) { + codec.read(buf) + } +} + +internal class WritingScope

( + private val buf: WriteBuffer, + private val value: P, +) : CodecScope

{ + override fun field(codec: Codec, get: (P) -> T): T { + val v = get(value) + codec.write(buf, v) + return v + } + + override fun structural(codec: Codec) { + codec.write(buf, Unit) + } +} + +abstract class PacketCodec

: Codec

{ + protected abstract fun CodecScope

.body(): P + + final override fun read(buf: ReadBuffer): P { + val scope = ReadingScope

(buf) + return with(scope) { body() } + } + + final override fun write(buf: WriteBuffer, value: P) { + val scope = WritingScope(buf, value) + with(scope) { body() } + } +} + +fun CodecScope<*>.reserved(byte: Int = 0, strict: Boolean = false) { + structural(de.fiereu.bytecodec.reserved(byte = byte, strict = strict)) +} + +fun CodecScope<*>.padding(n: Int, fill: Byte = 0) { + structural(de.fiereu.bytecodec.padding(n = n, fill = fill)) +} + +fun CodecScope<*>.skip(n: Int) { + structural(de.fiereu.bytecodec.skip(n = n)) +} diff --git a/bytecodec/src/main/kotlin/de/fiereu/bytecodec/test/TestHelpers.kt b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/test/TestHelpers.kt new file mode 100644 index 0000000..c4b9d84 --- /dev/null +++ b/bytecodec/src/main/kotlin/de/fiereu/bytecodec/test/TestHelpers.kt @@ -0,0 +1,47 @@ +package de.fiereu.bytecodec.test + +import de.fiereu.bytecodec.ByteArrayReadBuffer +import de.fiereu.bytecodec.Codec +import de.fiereu.bytecodec.GrowableWriteBuffer + +private fun contentEqual(a: Any?, b: Any?): Boolean = + when { + a is ByteArray && b is ByteArray -> a.contentEquals(b) + a is Array<*> && b is Array<*> -> a.contentDeepEquals(b) + else -> a == b + } + +fun Codec.encodeToBytes(value: T): ByteArray { + val buf = GrowableWriteBuffer() + write(buf, value) + return buf.toByteArray() +} + +fun Codec.decodeBytes(bytes: ByteArray): T { + val buf = ByteArrayReadBuffer(bytes) + val value = read(buf) + check(buf.remaining() == 0) { "decode left ${buf.remaining()} bytes unread" } + return value +} + +fun Codec.assertValueRoundtrip(value: T) { + val bytes = encodeToBytes(value) + val decoded = decodeBytes(bytes) + if (!contentEqual(decoded, value)) { + throw AssertionError( + "value roundtrip mismatch: original=$value decoded=$decoded bytes=${bytes.toHex()}", + ) + } +} + +fun Codec.assertBytesRoundtrip(bytes: ByteArray) { + val value = decodeBytes(bytes) + val reencoded = encodeToBytes(value) + if (!reencoded.contentEquals(bytes)) { + throw AssertionError( + "bytes roundtrip mismatch: original=${bytes.toHex()} reencoded=${reencoded.toHex()} value=$value", + ) + } +} + +private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it.toInt() and 0xFF) } diff --git a/bytecodec/src/test/kotlin/de/fiereu/bytecodec/AtomsTest.kt b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/AtomsTest.kt new file mode 100644 index 0000000..40f2717 --- /dev/null +++ b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/AtomsTest.kt @@ -0,0 +1,140 @@ +package de.fiereu.bytecodec + +import de.fiereu.bytecodec.test.assertBytesRoundtrip +import de.fiereu.bytecodec.test.assertValueRoundtrip +import de.fiereu.bytecodec.test.decodeBytes +import de.fiereu.bytecodec.test.encodeToBytes +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +class AtomsTest : + FunSpec({ + test("Bool roundtrips") { + Bool.assertValueRoundtrip(true) + Bool.assertValueRoundtrip(false) + Bool.encodeToBytes(true) shouldBe byteArrayOf(0x01) + Bool.encodeToBytes(false) shouldBe byteArrayOf(0x00) + Bool.decodeBytes(byteArrayOf(0x05)) shouldBe true + } + + test("U8 wire format") { + U8.encodeToBytes(0) shouldBe byteArrayOf(0x00) + U8.encodeToBytes(255) shouldBe byteArrayOf(0xFF.toByte()) + U8.decodeBytes(byteArrayOf(0xFF.toByte())) shouldBe 255 + shouldThrow { U8.encodeToBytes(256) } + } + + test("S8 wire format") { + S8.assertValueRoundtrip(0) + S8.assertValueRoundtrip(-1) + S8.assertValueRoundtrip(127) + S8.assertValueRoundtrip(-128) + } + + test("U16LE wire format") { + U16LE.encodeToBytes(0x1234) shouldBe byteArrayOf(0x34, 0x12) + U16LE.decodeBytes(byteArrayOf(0x34, 0x12)) shouldBe 0x1234 + } + + test("U16BE wire format") { + U16BE.encodeToBytes(0x1234) shouldBe byteArrayOf(0x12, 0x34) + U16BE.decodeBytes(byteArrayOf(0x12, 0x34)) shouldBe 0x1234 + } + + test("S16LE signed") { + S16LE.assertValueRoundtrip((-1).toShort()) + S16LE.assertValueRoundtrip(Short.MIN_VALUE) + S16LE.assertValueRoundtrip(Short.MAX_VALUE) + } + + test("S32LE wire format") { + S32LE.encodeToBytes(0x11223344) shouldBe byteArrayOf(0x44, 0x33, 0x22, 0x11) + S32LE.decodeBytes(byteArrayOf(0x44, 0x33, 0x22, 0x11)) shouldBe 0x11223344 + S32LE.assertValueRoundtrip(Int.MIN_VALUE) + S32LE.assertValueRoundtrip(Int.MAX_VALUE) + } + + test("S32BE wire format") { + S32BE.encodeToBytes(0x11223344) shouldBe byteArrayOf(0x11, 0x22, 0x33, 0x44) + S32BE.assertValueRoundtrip(Int.MIN_VALUE) + } + + test("U32LE roundtrip across full range") { + U32LE.assertValueRoundtrip(0L) + U32LE.assertValueRoundtrip(0xFFFFFFFFL) + U32LE.encodeToBytes(0xFFFFFFFFL) shouldBe + byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()) + } + + test("U32BE roundtrip") { + U32BE.encodeToBytes(0x11223344L) shouldBe byteArrayOf(0x11, 0x22, 0x33, 0x44) + } + + test("S64LE wire format") { + S64LE.encodeToBytes(0x0102030405060708L) shouldBe + byteArrayOf(0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01) + S64LE.assertValueRoundtrip(Long.MIN_VALUE) + S64LE.assertValueRoundtrip(Long.MAX_VALUE) + } + + test("S64BE wire format") { + S64BE.encodeToBytes(0x0102030405060708L) shouldBe + byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08) + } + + test("F32 / F64 roundtrip") { + F32LE.assertValueRoundtrip(3.14f) + F32BE.assertValueRoundtrip(-0.0f) + F64LE.assertValueRoundtrip(2.718281828) + F64BE.assertValueRoundtrip(Double.NEGATIVE_INFINITY) + } + + test("fixedBytes preserves payload") { + val codec = fixedBytes(4) + val payload = byteArrayOf(0x01, 0x02, 0x03, 0x04) + codec.assertBytesRoundtrip(payload) + shouldThrow { codec.encodeToBytes(byteArrayOf(0, 0, 0)) } + } + + test("unknownBytes is lossless") { + val codec = unknownBytes(3) + codec.assertBytesRoundtrip(byteArrayOf(0xDE.toByte(), 0xAD.toByte(), 0xBE.toByte())) + } + + test("reserved strict checks value") { + val codec = reserved(0xAB, strict = true) + codec.decodeBytes(byteArrayOf(0xAB.toByte())) shouldBe Unit + shouldThrow { codec.decodeBytes(byteArrayOf(0x01)) } + } + + test("reserved non-strict accepts anything on read but writes literal") { + val codec = reserved(0x00) + codec.decodeBytes(byteArrayOf(0xFF.toByte())) shouldBe Unit + codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x00) + } + + test("padding writes fill bytes") { + val codec = padding(3, fill = 0xAA.toByte()) + codec.encodeToBytes(Unit) shouldBe byteArrayOf(0xAA.toByte(), 0xAA.toByte(), 0xAA.toByte()) + } + + test("Utf16LeNullTerminated roundtrip") { + Utf16LeNullTerminated.assertValueRoundtrip("hello") + Utf16LeNullTerminated.assertValueRoundtrip("") + Utf16LeNullTerminated.assertValueRoundtrip("naïve résumé") + Utf16LeNullTerminated.encodeToBytes("ab") shouldBe + byteArrayOf(0x61, 0x00, 0x62, 0x00, 0x00, 0x00) + } + + test("Utf16BeNullTerminated roundtrip") { + Utf16BeNullTerminated.assertValueRoundtrip("hello") + Utf16BeNullTerminated.encodeToBytes("ab") shouldBe + byteArrayOf(0x00, 0x61, 0x00, 0x62, 0x00, 0x00) + } + + test("AsciiNullTerminated roundtrip") { + AsciiNullTerminated.assertValueRoundtrip("hello") + AsciiNullTerminated.encodeToBytes("ab") shouldBe byteArrayOf(0x61, 0x62, 0x00) + } + }) diff --git a/bytecodec/src/test/kotlin/de/fiereu/bytecodec/BuffersTest.kt b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/BuffersTest.kt new file mode 100644 index 0000000..ef5b404 --- /dev/null +++ b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/BuffersTest.kt @@ -0,0 +1,50 @@ +package de.fiereu.bytecodec + +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import java.nio.ByteBuffer + +class BuffersTest : + FunSpec({ + test("ByteArrayReadBuffer sequential read") { + val buf = ByteArrayReadBuffer(byteArrayOf(1, 2, 3, 4)) + buf.readByte() shouldBe 1 + buf.remaining() shouldBe 3 + val dst = ByteArray(2) + buf.readBytes(dst) + dst shouldBe byteArrayOf(2, 3) + buf.skip(1) + buf.remaining() shouldBe 0 + shouldThrow { buf.readByte() } + } + + test("ByteArrayReadBuffer respects offset and length") { + val buf = ByteArrayReadBuffer(byteArrayOf(9, 1, 2, 3, 9), offset = 1, length = 3) + buf.remaining() shouldBe 3 + val arr = ByteArray(3) + buf.readBytes(arr) + arr shouldBe byteArrayOf(1, 2, 3) + } + + test("GrowableWriteBuffer grows on demand") { + val buf = GrowableWriteBuffer(initialCapacity = 2) + repeat(10) { buf.writeByte(it.toByte()) } + buf.size() shouldBe 10 + buf.toByteArray() shouldBe byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) + } + + test("NioReadBuffer / NioWriteBuffer interoperate") { + val nio = ByteBuffer.allocate(8) + val write = NioWriteBuffer(nio) + write.writeByte(0x11) + write.writeBytes(byteArrayOf(0x22, 0x33)) + nio.flip() + val read = NioReadBuffer(nio) + read.readByte() shouldBe 0x11 + val arr = ByteArray(2) + read.readBytes(arr) + arr shouldBe byteArrayOf(0x22, 0x33) + read.remaining() shouldBe 0 + } + }) diff --git a/bytecodec/src/test/kotlin/de/fiereu/bytecodec/CombinatorsTest.kt b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/CombinatorsTest.kt new file mode 100644 index 0000000..d2d44c8 --- /dev/null +++ b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/CombinatorsTest.kt @@ -0,0 +1,134 @@ +package de.fiereu.bytecodec + +import de.fiereu.bytecodec.test.assertBytesRoundtrip +import de.fiereu.bytecodec.test.assertValueRoundtrip +import de.fiereu.bytecodec.test.decodeBytes +import de.fiereu.bytecodec.test.encodeToBytes +import io.kotest.assertions.throwables.shouldThrow +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +private enum class Color { + RED, + GREEN, + BLUE +} + +class CombinatorsTest : + FunSpec({ + test("imap lifts an atom") { + val codec = U8.imap(decode = { it + 1 }, encode = { it - 1 }) + codec.encodeToBytes(10) shouldBe byteArrayOf(0x09) + codec.decodeBytes(byteArrayOf(0x09)) shouldBe 10 + } + + test("imapCatching wraps non-CodecException") { + val codec = + U8.imapCatching( + decode = { error("boom") }, + encode = { _: Int -> 0 }, + ) + shouldThrow { codec.decodeBytes(byteArrayOf(0x00)) } + } + + test("listPrefixed with U8 prefix") { + val codec = U16LE.listPrefixed(U8) + codec.assertValueRoundtrip(listOf(1, 2, 3)) + codec.encodeToBytes(emptyList()) shouldBe byteArrayOf(0x00) + codec.encodeToBytes(listOf(0x1234, 0x5678)) shouldBe + byteArrayOf(0x02, 0x34, 0x12, 0x78, 0x56) + } + + test("repeat is fixed-count") { + val codec = U8.repeat(3) + codec.assertBytesRoundtrip(byteArrayOf(1, 2, 3)) + shouldThrow { codec.encodeToBytes(listOf(1, 2)) } + } + + test("bytesPrefixed") { + val codec = bytesPrefixed(U8) + codec.assertBytesRoundtrip(byteArrayOf(0x03, 0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())) + } + + test("stringPrefixed UTF-8") { + val codec = stringPrefixed(U8, Charsets.UTF_8) + codec.assertValueRoundtrip("hello") + val bytes = "héllo".toByteArray(Charsets.UTF_8) + codec.encodeToBytes("héllo")[0].toInt() shouldBe bytes.size + } + + test("enumByOrdinalByte") { + val codec = enumByOrdinalByte() + codec.assertValueRoundtrip(Color.RED) + codec.assertValueRoundtrip(Color.BLUE) + codec.encodeToBytes(Color.BLUE) shouldBe byteArrayOf(0x02) + shouldThrow { codec.decodeBytes(byteArrayOf(0x05)) } + } + + test("enumBy with custom mapping") { + val keys = mapOf(Color.RED to 10, Color.GREEN to 20, Color.BLUE to 30) + val reverse = keys.entries.associate { (k, v) -> v to k } + val codec = + enumBy( + prefix = U8, + lookup = { reverse[it] ?: throw MalformedPacketException("bad key $it") }, + keyOf = { keys.getValue(it) }, + ) + codec.encodeToBytes(Color.GREEN) shouldBe byteArrayOf(20) + codec.decodeBytes(byteArrayOf(30)) shouldBe Color.BLUE + } + + test("choose dispatches on tag") { + val u8List = U8.listPrefixed(U8) + val codec: Codec = + choose( + tag = U8, + identify = { v -> + when (v) { + is Int -> 0x01 + is String -> 0x02 + else -> error("unhandled $v") + } + }, + 0x01 to U16LE as Codec, + 0x02 to AsciiNullTerminated as Codec, + ) + codec.encodeToBytes(0x1234) shouldBe byteArrayOf(0x01, 0x34, 0x12) + codec.encodeToBytes("ok") shouldBe byteArrayOf(0x02, 0x6F, 0x6B, 0x00) + shouldThrow { codec.decodeBytes(byteArrayOf(0xFE.toByte())) } + u8List.encodeToBytes(emptyList()).size shouldBe 1 + } + + test("optional with explicit flag") { + val codec = U16LE.optional() + codec.assertValueRoundtrip(null) + codec.assertValueRoundtrip(0x1234) + codec.encodeToBytes(null) shouldBe byteArrayOf(0x00) + codec.encodeToBytes(0x1234) shouldBe byteArrayOf(0x01, 0x34, 0x12) + } + + test("then pairs two codecs") { + val codec = U8.then(U16LE) + codec.assertValueRoundtrip(5 to 0x1234) + codec.encodeToBytes(5 to 0x1234) shouldBe byteArrayOf(0x05, 0x34, 0x12) + } + + test("bitsLE roundtrip") { + val codec = + bitsLE(U8) { + bit(0, "a") + bit(3, "b") + bit(7, "c") + } + val set = codec.of("a" to true, "b" to false, "c" to true) + set["a"] shouldBe true + set["b"] shouldBe false + set["c"] shouldBe true + set[0] shouldBe true + val bytes = codec.encodeToBytes(set) + bytes shouldBe byteArrayOf(0b10000001.toByte()) + val decoded = codec.decodeBytes(bytes) + decoded["a"] shouldBe true + decoded["c"] shouldBe true + } + }) diff --git a/bytecodec/src/test/kotlin/de/fiereu/bytecodec/PacketCodecTest.kt b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/PacketCodecTest.kt new file mode 100644 index 0000000..67dae60 --- /dev/null +++ b/bytecodec/src/test/kotlin/de/fiereu/bytecodec/PacketCodecTest.kt @@ -0,0 +1,109 @@ +package de.fiereu.bytecodec + +import de.fiereu.bytecodec.test.assertBytesRoundtrip +import de.fiereu.bytecodec.test.assertValueRoundtrip +import de.fiereu.bytecodec.test.encodeToBytes +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe + +private data class GameServer( + val id: Int, + val name: String, + val currentPlayers: Int, + val maxPlayers: Int, + val joinable: Boolean, +) + +private object GameServerCodec : PacketCodec() { + override fun CodecScope.body() = + GameServer( + id = field(U8, GameServer::id), + name = field(Utf16LeNullTerminated, GameServer::name), + currentPlayers = field(U16LE, GameServer::currentPlayers), + maxPlayers = field(U16LE, GameServer::maxPlayers), + joinable = field(Bool, GameServer::joinable), + ) +} + +private data class LoadEntityPacket( + val entityId: Long, + val name: String, + val gateA: ByteArray?, + val gateB: Int?, +) { + override fun equals(other: Any?): Boolean = + other is LoadEntityPacket && + entityId == other.entityId && + name == other.name && + (gateA?.contentEquals(other.gateA) ?: (other.gateA == null)) && + gateB == other.gateB + + override fun hashCode(): Int = entityId.hashCode() +} + +private object LoadEntityCodec : PacketCodec() { + override fun CodecScope.body(): LoadEntityPacket { + val entityId = field(S64BE, LoadEntityPacket::entityId) + reserved(0) + val name = field(Utf16LeNullTerminated, LoadEntityPacket::name) + val flags = + field(U16LE) { + var f = 0 + if (it.gateA != null) f = f or 0x01 + if (it.gateB != null) f = f or 0x02 + f + } + val gateA = if (flags and 0x01 != 0) field(unknownBytes(2)) { it.gateA!! } else null + val gateB = if (flags and 0x02 != 0) field(U32LE) { it.gateB!!.toLong() }.toInt() else null + return LoadEntityPacket(entityId, name, gateA, gateB) + } +} + +class PacketCodecTest : + FunSpec({ + test("simple PacketCodec roundtrip") { + val pkt = + GameServer( + id = 1, name = "alpha", currentPlayers = 10, maxPlayers = 100, joinable = true) + GameServerCodec.assertValueRoundtrip(pkt) + } + + test("byte-level layout of GameServer") { + val bytes = GameServerCodec.encodeToBytes(GameServer(7, "ab", 3, 9, false)) + bytes shouldBe + byteArrayOf( + 0x07, + 0x61, + 0x00, + 0x62, + 0x00, + 0x00, + 0x00, + 0x03, + 0x00, + 0x09, + 0x00, + 0x00, + ) + } + + test("complex packet with reserved, flags, optional sections") { + LoadEntityCodec.assertValueRoundtrip( + LoadEntityPacket(42L, "world", gateA = null, gateB = null), + ) + LoadEntityCodec.assertValueRoundtrip( + LoadEntityPacket( + entityId = 0x0102030405060708L, + name = "x", + gateA = byteArrayOf(0xAA.toByte(), 0xBB.toByte()), + gateB = 0x11223344, + ), + ) + } + + test("structural reserved bytes survive bytes roundtrip") { + val pkt = LoadEntityPacket(1L, "y", null, null) + val bytes = LoadEntityCodec.encodeToBytes(pkt) + LoadEntityCodec.assertBytesRoundtrip(bytes) + } + }) diff --git a/settings.gradle.kts b/settings.gradle.kts index bdc7a5b..813088c 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -14,6 +14,7 @@ rootProject.name = "openmmo" include(":keys") include(":patcher") include(":common") +include(":bytecodec") include(":protocol") include(":protocol.tls") include(":protocol.login")