feat(bytecodec): add a constant atom for fixed wire bytes (#53)

This commit is contained in:
Fiereu authored and GitHub committed 2026-07-25 16:30:08 +02:00
1 parent 5e75f5cca7
commit 017f6bca60
3 files changed
+49 -1

No files matched your search

@@ -268,6 +268,34 @@ fun reserved(byte: Int, strict: Boolean = false): Codec<Unit> {
} }
} }
/** A fixed protocol byte: writes [byte] verbatim and skips one byte when reading. */
fun constant(byte: Int): Codec<Unit> {
val literal = (byte and 0xFF).toByte()
return object : Codec<Unit> {
override fun read(buf: ReadBuffer) {
buf.skip(1)
}
override fun write(buf: WriteBuffer, value: Unit) {
buf.writeByte(literal)
}
}
}
/** A fixed protocol segment: writes [bytes] verbatim and skips over them when reading. */
fun constant(bytes: ByteArray): Codec<Unit> {
val literal = bytes.copyOf()
return object : Codec<Unit> {
override fun read(buf: ReadBuffer) {
buf.skip(literal.size)
}
override fun write(buf: WriteBuffer, value: Unit) {
buf.writeBytes(literal)
}
}
}
fun padding(n: Int, fill: Byte = 0): Codec<Unit> { fun padding(n: Int, fill: Byte = 0): Codec<Unit> {
require(n >= 0) { "padding negative size: $n" } require(n >= 0) { "padding negative size: $n" }
return object : Codec<Unit> { return object : Codec<Unit> {
@@ -43,7 +43,7 @@ abstract class PacketCodec<P> : Codec<P> {
} }
} }
fun CodecScope<*>.reserved(byte: Int = 0, strict: Boolean = false) { fun CodecScope<*>.reserved(byte: Int, strict: Boolean = false) {
structural(de.fiereu.bytecodec.reserved(byte = byte, strict = strict)) structural(de.fiereu.bytecodec.reserved(byte = byte, strict = strict))
} }
@@ -54,3 +54,11 @@ fun CodecScope<*>.padding(n: Int, fill: Byte = 0) {
fun CodecScope<*>.skip(n: Int) { fun CodecScope<*>.skip(n: Int) {
structural(de.fiereu.bytecodec.skip(n = n)) structural(de.fiereu.bytecodec.skip(n = n))
} }
fun CodecScope<*>.constant(byte: Int) {
structural(de.fiereu.bytecodec.constant(byte = byte))
}
fun CodecScope<*>.constant(bytes: ByteArray) {
structural(de.fiereu.bytecodec.constant(bytes = bytes))
}
@@ -114,6 +114,18 @@ class AtomsTest :
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x00) codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x00)
} }
test("constant byte writes the literal and skips it on read") {
val codec = constant(0x2A)
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x2A)
codec.decodeBytes(byteArrayOf(0x0A)) shouldBe Unit
}
test("constant segment writes the literal and skips it on read") {
val codec = constant(byteArrayOf(0x01, 0x02, 0x03))
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0x01, 0x02, 0x03)
codec.decodeBytes(byteArrayOf(0x0A, 0x0B, 0x0C)) shouldBe Unit
}
test("padding writes fill bytes") { test("padding writes fill bytes") {
val codec = padding(3, fill = 0xAA.toByte()) val codec = padding(3, fill = 0xAA.toByte())
codec.encodeToBytes(Unit) shouldBe byteArrayOf(0xAA.toByte(), 0xAA.toByte(), 0xAA.toByte()) codec.encodeToBytes(Unit) shouldBe byteArrayOf(0xAA.toByte(), 0xAA.toByte(), 0xAA.toByte())