implement numeric encodings, optimize

This commit is contained in:
2026-01-17 12:27:41 +01:00
parent 45d74d9cff
commit 55faf1d670
22 changed files with 355 additions and 249 deletions

View File

@@ -0,0 +1,40 @@
package com.infendro.encoding.numeric
import com.infendro.encoding.Encoding
import com.infendro.encoding.util.BigInt
import com.infendro.encoding.util.log2
import kotlin.math.ceil
open class NumericEncoding(
alphabet: ByteArray,
) : Encoding(alphabet) {
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 x = BigInt.from(bytes)
var i = result.size
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 index = alphabet.indexOf(bytes[i])
if (index == -1) throw Exception() //TODO
value = value.timesAdd(base, index)
}
return value.toByteArray()
}
}