implement composition

This commit is contained in:
2026-01-19 19:55:39 +01:00
parent 684b6d78ea
commit c1b8800e82
26 changed files with 91 additions and 68 deletions

View File

@@ -0,0 +1,43 @@
package com.infendro.encoding
import com.infendro.encoding.exception.IllegalByteException
import com.infendro.encoding.util.BigInt
import com.infendro.encoding.util.log2
import kotlin.math.ceil
class NumericEncoding internal constructor(
override val alphabet: ByteArray,
) : Encoding {
override fun encode(bytes: ByteArray): ByteArray {
if (bytes.isEmpty()) return byteArrayOf()
val size = ceil(bytes.size * 8 / log2(base)).toInt()
val result = ByteArray(size)
var i = result.size
var x = BigInt.from(bytes)
while (!x.isZero()) {
val (quotient, remainder) = x.divRem(base)
x = quotient
result[--i] = alphabet[remainder]
}
return result.copyOfRange(i, result.size)
}
override fun decode(bytes: ByteArray): ByteArray {
if (bytes.isEmpty()) return byteArrayOf()
var value = BigInt.zero
for (i in 0..<bytes.size) {
val byte = bytes[i]
val index = alphabet.indexOf(byte)
if (index == -1) throw IllegalByteException(byte)
value = value.timesAdd(base, index)
}
return value.toByteArray()
}
}