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

@@ -1,92 +1,15 @@
package com.infendro.encoding
import com.infendro.encoding.util.lcm
import com.infendro.encoding.util.log2
import kotlin.math.pow
sealed class Encoding {
abstract fun encode(
bytes: UByteArray,
): UByteArray
abstract fun decode(
bytes: UByteArray,
): UByteArray
protected fun encode(
bytes: UByteArray,
characters: UByteArray,
padding: UByte? = null,
): UByteArray {
val length = log2(characters.size).toInt()
val mask = (2.0.pow(length) - 1).toUInt()
val encoded = mutableListOf<UByte>()
var buffer = 0U
var bits = 0
for (byte in bytes) {
buffer = (buffer shl 8) + byte
bits += 8
while (bits >= length) {
val offset = bits - length
val index = (buffer shr offset).toInt()
buffer = buffer and (mask shl offset).inv()
bits -= length
encoded.add(characters[index])
}
}
if (bits > 0) {
buffer = buffer shl (length - bits)
val index = buffer.toInt()
encoded.add(characters[index])
}
if (padding != null) {
val block = lcm(length, 8) / length
while (encoded.size % block != 0) {
encoded.add(padding)
}
}
return encoded.toUByteArray()
abstract class Encoding(
val alphabet: ByteArray,
) {
init {
require(alphabet.isNotEmpty())
}
protected fun decode(
bytes: UByteArray,
characters: UByteArray,
padding: UByte? = null,
): UByteArray {
val length = log2(characters.size).toInt()
val mask = 0xffU
val base: Int
get() = alphabet.size
val decoded = mutableListOf<UByte>()
var buffer = 0U
var bits = 0
for (byte in bytes) {
if (byte == padding) break
val index = characters.indexOf(byte)
if (index == -1) throw Exception()
buffer = (buffer shl length) + index.toUByte()
bits += length
if (bits >= 8) {
val offset = bits - 8
val character = (buffer shr offset).toUByte()
buffer = buffer and (mask shl offset).inv()
bits -= 8
decoded.add(character)
}
}
return decoded.toUByteArray()
}
abstract fun encode(bytes: ByteArray): ByteArray
abstract fun decode(bytes: ByteArray): ByteArray
}