refactor encodings
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user