feat(bytecodec): add bidirectional binary codec library

This commit is contained in:
Fiereu committed 2026-05-26 17:36:22 +02:00
1 parent dbb027d021
commit 8048827121
14 files changed
+1266

No files matched your search

@@ -0,0 +1,328 @@
package de.fiereu.bytecodec
object Bool : Codec<Boolean> {
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<Byte> {
override fun read(buf: ReadBuffer): Byte = buf.readByte()
override fun write(buf: WriteBuffer, value: Byte) {
buf.writeByte(value)
}
}
object U8 : Codec<Int> {
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<Short> {
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<Short> {
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<Int> {
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<Int> {
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<Int> {
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<Int> {
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<Long> {
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<Long> {
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<Long> {
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<Long> {
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<Float> {
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<Float> {
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<Double> {
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<Double> {
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<ByteArray> {
require(n >= 0) { "fixedBytes negative size: $n" }
return object : Codec<ByteArray> {
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<ByteArray> = fixedBytes(n)
fun reserved(byte: Int, strict: Boolean = false): Codec<Unit> {
val literal = (byte and 0xFF).toByte()
return object : Codec<Unit> {
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<Unit> {
require(n >= 0) { "padding negative size: $n" }
return object : Codec<Unit> {
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<Unit> = padding(n)
object Utf16LeNullTerminated : Codec<String> {
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<String> {
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<String> {
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)
}
}
@@ -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
@@ -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)
}
}
@@ -0,0 +1,7 @@
package de.fiereu.bytecodec
interface Codec<T> {
fun read(buf: ReadBuffer): T
fun write(buf: WriteBuffer, value: T)
}
@@ -0,0 +1,267 @@
package de.fiereu.bytecodec
import java.nio.charset.Charset
fun <T, R> Codec<T>.imap(decode: (T) -> R, encode: (R) -> T): Codec<R> {
val inner = this
return object : Codec<R> {
override fun read(buf: ReadBuffer): R = decode(inner.read(buf))
override fun write(buf: WriteBuffer, value: R) {
inner.write(buf, encode(value))
}
}
}
fun <T, R> Codec<T>.imapCatching(
decode: (T) -> R,
encode: (R) -> T,
onError: (T, Throwable) -> String = { v, _ -> "Cannot decode $v" },
): Codec<R> {
val inner = this
return object : Codec<R> {
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 <T> Codec<T>.listPrefixed(prefix: Codec<Int>): Codec<List<T>> {
val inner = this
return object : Codec<List<T>> {
override fun read(buf: ReadBuffer): List<T> {
val n = prefix.read(buf)
if (n < 0) throw MalformedPacketException("negative list length: $n")
val list = ArrayList<T>(n.coerceAtMost(1024))
repeat(n) { list.add(inner.read(buf)) }
return list
}
override fun write(buf: WriteBuffer, value: List<T>) {
prefix.write(buf, value.size)
for (item in value) inner.write(buf, item)
}
}
}
fun <T> Codec<T>.repeat(count: Int): Codec<List<T>> {
require(count >= 0) { "repeat negative count: $count" }
val inner = this
return object : Codec<List<T>> {
override fun read(buf: ReadBuffer): List<T> = List(count) { inner.read(buf) }
override fun write(buf: WriteBuffer, value: List<T>) {
if (value.size != count) {
throw MalformedPacketException("repeat($count) got ${value.size}")
}
for (item in value) inner.write(buf, item)
}
}
}
fun bytesPrefixed(prefix: Codec<Int>): Codec<ByteArray> =
object : Codec<ByteArray> {
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<Int>, charset: Charset): Codec<String> =
object : Codec<String> {
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 <reified E : Enum<E>> enumByOrdinalByte(): Codec<E> {
val values = enumValues<E>()
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 <reified E : Enum<E>> enumByOrdinalU16LE(): Codec<E> {
val values = enumValues<E>()
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 <E : Enum<E>> enumBy(
prefix: Codec<Int>,
lookup: (Int) -> E,
keyOf: (E) -> Int,
): Codec<E> =
object : Codec<E> {
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 <T : Any> choose(
tag: Codec<Int>,
identify: (T) -> Int,
vararg branches: Pair<Int, Codec<out T>>,
): Codec<T> {
val byTag: Map<Int, Codec<out T>> = branches.toMap()
require(byTag.size == branches.size) { "duplicate branch tags in choose" }
return object : Codec<T> {
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<T>).write(buf, value)
}
}
}
fun <T : Any> Codec<T>.optional(flag: Codec<Boolean> = Bool): Codec<T?> {
val inner = this
return object : Codec<T?> {
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 <A, B> Codec<A>.then(other: Codec<B>): Codec<Pair<A, B>> {
val first = this
return object : Codec<Pair<A, B>> {
override fun read(buf: ReadBuffer): Pair<A, B> = first.read(buf) to other.read(buf)
override fun write(buf: WriteBuffer, value: Pair<A, B>) {
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<String, Int>,
) {
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<Int>,
private val byName: Map<String, Int>,
) : Codec<BitSet32> {
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<String, Boolean>): 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<Int>, builder: BitsBuilder.() -> Unit): BitsCodec {
val map = LinkedHashMap<String, Int>()
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)
}
@@ -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)}",
)
@@ -0,0 +1,56 @@
package de.fiereu.bytecodec
interface CodecScope<P> {
fun <T> field(codec: Codec<T>, get: (P) -> T): T
fun structural(codec: Codec<Unit>)
}
internal class ReadingScope<P>(private val buf: ReadBuffer) : CodecScope<P> {
override fun <T> field(codec: Codec<T>, get: (P) -> T): T = codec.read(buf)
override fun structural(codec: Codec<Unit>) {
codec.read(buf)
}
}
internal class WritingScope<P>(
private val buf: WriteBuffer,
private val value: P,
) : CodecScope<P> {
override fun <T> field(codec: Codec<T>, get: (P) -> T): T {
val v = get(value)
codec.write(buf, v)
return v
}
override fun structural(codec: Codec<Unit>) {
codec.write(buf, Unit)
}
}
abstract class PacketCodec<P> : Codec<P> {
protected abstract fun CodecScope<P>.body(): P
final override fun read(buf: ReadBuffer): P {
val scope = ReadingScope<P>(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))
}
@@ -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 <T> Codec<T>.encodeToBytes(value: T): ByteArray {
val buf = GrowableWriteBuffer()
write(buf, value)
return buf.toByteArray()
}
fun <T> Codec<T>.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 <T> Codec<T>.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 <T> Codec<T>.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) }
@@ -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<IllegalArgumentException> { 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<MalformedPacketException> { 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<ReservedByteMismatchException> { 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)
}
})
@@ -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<IndexOutOfBoundsException> { 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
}
})
@@ -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<MalformedPacketException> { 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<MalformedPacketException> { 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<Color>()
codec.assertValueRoundtrip(Color.RED)
codec.assertValueRoundtrip(Color.BLUE)
codec.encodeToBytes(Color.BLUE) shouldBe byteArrayOf(0x02)
shouldThrow<MalformedPacketException> { 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<Color>(
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<Any> =
choose(
tag = U8,
identify = { v ->
when (v) {
is Int -> 0x01
is String -> 0x02
else -> error("unhandled $v")
}
},
0x01 to U16LE as Codec<out Any>,
0x02 to AsciiNullTerminated as Codec<out Any>,
)
codec.encodeToBytes(0x1234) shouldBe byteArrayOf(0x01, 0x34, 0x12)
codec.encodeToBytes("ok") shouldBe byteArrayOf(0x02, 0x6F, 0x6B, 0x00)
shouldThrow<UnknownTagException> { 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
}
})
@@ -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<GameServer>() {
override fun CodecScope<GameServer>.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<LoadEntityPacket>() {
override fun CodecScope<LoadEntityPacket>.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)
}
})