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