encoder and decoder now support extendable formats.

This commit is contained in:
sergeych committed 2023-03-12 22:48:21 +01:00
1 parent 6e65a216c5
commit 63b231975b
13 files changed
+288 -23

No files matched your search

@@ -1,5 +1,7 @@
package net.sergeych.bintools
import kotlin.reflect.typeOf
/**
* data input stream-like abstraction. We need it because
* kotlinx serialization is synchronous and there us nothing
@@ -8,23 +10,40 @@ package net.sergeych.bintools
*/
interface DataSource {
class EndOfData() : Exception("no more data available")
fun readByte(): Byte
val position: Int
fun readUByte() = readByte().toUByte()
@Suppress("unused")
fun readBytes(size: Int): ByteArray =
ByteArray(size).also { a ->
for( i in 0..size)
for (i in 0 until size)
a[i] = readByte()
}
fun readI32(): Int = bytesToInt(readBytes(4))
fun readI64(): Long = bytesToLong(readBytes(8))
fun readDouble() = Double.fromBits(readI64())
fun readFloat() = Float.fromBits(readI32())
}
fun ByteArray.toDataSource(): DataSource =
object : DataSource {
override var position = 0
var position = 0
private set
override fun readByte(): Byte = this@toDataSource[position++]
}
override fun readByte(): Byte =
if( position < size ) this@toDataSource[position++]
else throw DataSource.EndOfData()
}
inline fun <reified T : Any> DataSource.readNumber(): T = when(typeOf<T>()) {
typeOf<Double>() -> readDouble() as T
typeOf<Float>() -> readFloat() as T
else -> Smartint.decode(this)
}