summaryrefslogtreecommitdiff
path: root/src/main/kotlin/SizedMessageField.kt
blob: c40a2a6f9f3b32899a8a61d325701824a1ca9402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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)
}