commit 44c7579892cbea5b7a70e006ee6c943591124762
parent 37519ca0d5b269b461624a2c0aa3679b060938ad
Author: rhunk <101876869+rhunk@users.noreply.github.com>
Date:   Tue, 21 Nov 2023 18:53:36 +0100

feat(common): proto utils

Diffstat:
Mcommon/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoEditor.kt | 24++++++++++++++++++++++++
Mcommon/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoReader.kt | 4+++-
2 files changed, 27 insertions(+), 1 deletion(-)

diff --git a/common/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoEditor.kt b/common/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoEditor.kt @@ -26,6 +26,30 @@ class EditorContext( fun remove(id: Int) = wires.remove(id) fun remove(id: Int, index: Int) = wires[id]?.removeAt(index) + + fun edit(id: Int, callback: EditorContext.() -> Unit) { + val wire = wires[id]?.firstOrNull() ?: return + val editor = ProtoEditor(wire.value as ByteArray) + editor.edit { + callback() + } + remove(id) + addBuffer(id, editor.toByteArray()) + } + + fun editEach(id: Int, callback: EditorContext.() -> Unit) { + val wires = wires[id] ?: return + val newWires = mutableListOf<Wire>() + wires.toList().forEachIndexed { _, wire -> + val editor = ProtoEditor(wire.value as ByteArray) + editor.edit { + callback() + } + newWires.add(Wire(wire.id, WireType.CHUNK, editor.toByteArray())) + } + wires.clear() + wires.addAll(newWires) + } } class ProtoEditor( diff --git a/common/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoReader.kt b/common/src/main/kotlin/me/rhunk/snapenhance/common/util/protobuf/ProtoReader.kt @@ -2,7 +2,9 @@ package me.rhunk.snapenhance.common.util.protobuf import java.util.UUID -data class Wire(val id: Int, val type: WireType, val value: Any) +data class Wire(val id: Int, val type: WireType, val value: Any) { + fun toReader() = ProtoReader(value as ByteArray) +} class ProtoReader(private val buffer: ByteArray) { private var offset: Int = 0