summaryrefslogtreecommitdiff
path: root/src/main/kotlin/SizedMessageField.kt
diff options
context:
space:
mode:
authorEdoardo La Greca2025-07-12 19:14:26 +0200
committerEdoardo La Greca2025-07-13 21:22:19 +0200
commit917599228501ae235ffaf01b515c8b06cf8595b0 (patch)
treef7dc4ff08bf44a9b029346aaaec39b23dd35321e /src/main/kotlin/SizedMessageField.kt
parentc916a1c14813fbb96288b0c75efd29e01ee6a0df (diff)
Diffstat (limited to 'src/main/kotlin/SizedMessageField.kt')
-rw-r--r--src/main/kotlin/SizedMessageField.kt35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/main/kotlin/SizedMessageField.kt b/src/main/kotlin/SizedMessageField.kt
new file mode 100644
index 0000000..c40a2a6
--- /dev/null
+++ b/src/main/kotlin/SizedMessageField.kt
@@ -0,0 +1,35 @@
+import java.math.BigInteger
+
+/**
+ * [SizedMessageField] represents an unsigned integer number stored in a message field (i.e. a contiguous region of
+ * memory) of fixed size.
+ *
+ * @param size The size of the field, measured in bytes.
+ * @param value The value of the field.
+ *
+ * @throws IllegalArgumentException if the size required to store the provided value is bigger than the provided size.
+ */
+class SizedMessageField(val size: Int, value: BigInteger) {
+ init {
+ if (!this.sizeOk(size, value)) {
+ throw IllegalArgumentException()
+ }
+ }
+
+ /**
+ * @throws IllegalStateException on set if the declared size is not enough for the new value.
+ */
+ var value = value
+ set(value) {
+ if (!this.sizeOk(value)) {
+ throw IllegalStateException()
+ }
+ }
+
+ private fun sizeOk(size: Int, value: BigInteger): Boolean {
+ val requiredSize = value.toByteArray().size
+ return requiredSize <= size
+ }
+ private fun sizeOk(value: BigInteger): Boolean = sizeOk(this.size, value)
+ private fun sizeOk(): Boolean = sizeOk(this.size, this.value)
+} \ No newline at end of file