refactor encodings

This commit is contained in:
2025-11-10 18:59:53 +01:00
parent 08a79efa04
commit 71a47af43c
5 changed files with 55 additions and 55 deletions

View File

@@ -6,28 +6,28 @@ import kotlin.math.pow
sealed class Encoding {
abstract fun encode(
bytes: ByteArray,
): ByteArray
bytes: UByteArray,
): UByteArray
abstract fun decode(
bytes: ByteArray,
): ByteArray
bytes: UByteArray,
): UByteArray
protected fun encode(
bytes: ByteArray,
characters: Array<Byte>,
padding: Byte? = null,
): ByteArray {
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<Byte>()
val encoded = mutableListOf<UByte>()
var buffer = 0U
var bits = 0
for (byte in bytes) {
buffer = (buffer shl 8) + byte.toUByte()
buffer = (buffer shl 8) + byte
bits += 8
while (bits >= length) {
@@ -52,18 +52,18 @@ sealed class Encoding {
}
}
return encoded.toByteArray()
return encoded.toUByteArray()
}
protected fun decode(
bytes: ByteArray,
characters: Array<Byte>,
padding: Byte? = null,
): ByteArray {
bytes: UByteArray,
characters: UByteArray,
padding: UByte? = null,
): UByteArray {
val length = log2(characters.size).toInt()
val mask = 0xFFU
val decoded = mutableListOf<Byte>()
val decoded = mutableListOf<UByte>()
var buffer = 0U
var bits = 0
@@ -79,7 +79,7 @@ sealed class Encoding {
if (bits >= 8) {
val offset = bits - 8
val character = (buffer shr offset).toByte()
val character = (buffer shr offset).toUByte()
buffer = buffer and (mask shl offset).inv()
bits -= 8
@@ -87,6 +87,6 @@ sealed class Encoding {
}
}
return decoded.toByteArray()
return decoded.toUByteArray()
}
}