From 3d00fa24e4a9ac58f1c2d275571bf86e5cbc8fdc Mon Sep 17 00:00:00 2001 From: Edoardo La Greca Date: Wed, 30 Jul 2025 18:22:02 +0200 Subject: add size method to NinePMessage --- src/main/kotlin/NinePMessage.kt | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'src/main/kotlin') diff --git a/src/main/kotlin/NinePMessage.kt b/src/main/kotlin/NinePMessage.kt index 9edf361..1d0530a 100644 --- a/src/main/kotlin/NinePMessage.kt +++ b/src/main/kotlin/NinePMessage.kt @@ -14,6 +14,17 @@ import kotlin.math.pow * @param fieldValuesStr A map of each field name into its value. This map only stores string values. */ class NinePMessage(val type: NinePMessageType, val tag: UShort, val fieldNames: List, val fieldValuesInt: Map, val fieldValuesStr: Map) { + /** + * Intersection between [fieldNames] and [fieldValuesInt]. In other words: the amount of integer fields that are + * going to be used when writing the message. + */ + private val insecInts = fieldNames.intersect(fieldValuesInt.keys) + /** + * Intersection between [fieldNames] and [fieldValuesStr]. In other words: the amount of string fields that are + * going to be used when writing the message. + */ + private val insecStrs = fieldNames.intersect(fieldValuesStr.keys) + /** * Send the message using the given networking API. * @@ -21,14 +32,10 @@ class NinePMessage(val type: NinePMessageType, val tag: UShort, val fieldNames: * @throws IllegalArgumentException if [fieldNames], [fieldValuesInt], and [fieldValuesStr] are incoherent. */ fun write(npt: NetworkPacketTransporter) { - // shorthands - val insecInts = fieldNames.intersect(fieldValuesInt.keys) - val insecStrs = fieldNames.intersect(fieldValuesStr.keys) // check that names in fieldNames exist as keys in either fieldValuesInt or fieldValuesStr but not both require(insecInts.size == fieldNames.size - insecStrs.size) - val totalSize = 4 + 1 + 2 + insecInts.sumOf { fieldValuesInt[it]!!.size } + insecStrs.sumOf { 2 + fieldValuesStr[it]!!.length } - + val totalSize = size() writeMessageSizeType(npt, totalSize, type) writeInteger(npt, SizedMessageField(2, tag.toInt().toBigInteger())) for (field in fieldNames) { @@ -79,4 +86,11 @@ class NinePMessage(val type: NinePMessageType, val tag: UShort, val fieldNames: writeInteger(npt, SizedMessageField(4, size.toBigInteger())) writeInteger(npt, SizedMessageField(1, type.value.toInt().toBigInteger())) } + + /** + * Calculate the expected size of the message. + */ + fun size(): Int { + return 4 + 1 + 2 + this.insecInts.sumOf { this.fieldValuesInt[it]!!.size } + this.insecStrs.sumOf { 2 + this.fieldValuesStr[it]!!.length } + } } \ No newline at end of file -- cgit v1.2.3