import java.math.BigInteger /** * [SizedInteger] represents an unsigned integer number of arbitrary yet fixed length. It's useful for storing integers * got from a connection as message fields. * * @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 SizedInteger(val size: ULong, value: BigInteger) { init { if (!this.sizeOk(size, value)) { throw IllegalArgumentException() } } constructor(size: ULong) : this(size, 0.toBigInteger()) /** * @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: ULong, value: BigInteger): Boolean { val requiredSize = value.toByteArray().size.toUInt() return requiredSize <= size } private fun sizeOk(value: BigInteger): Boolean = sizeOk(this.size, value) }