35 lines
1.1 KiB
Kotlin

package net.sergeych.bintools
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import kotlin.reflect.KType
import kotlin.reflect.typeOf
/**
* Experimental interface for packing and unpacking binary formats.
* Initial support intended for BiPack and BOSS to make it fast replaceable.
* Also, JSON text version with binary converter is presented by default.
*/
interface MotherPacker {
fun <T>pack(type: KType, payload: T): ByteArray
fun <T>unpack(type: KType,packed: ByteArray): T
}
inline fun <reified T>MotherPacker.pack(payload: T) = pack(typeOf<T>(), payload)
inline fun <reified T>MotherPacker.unpack(packed: ByteArray) = unpack<T>(typeOf<T>(), packed)
class JsonPacker : MotherPacker {
override fun <T> pack(type: KType, payload: T): ByteArray {
return Json.encodeToString(serializer(type), payload).encodeToByteArray()
}
override fun <T> unpack(type: KType, packed: ByteArray): T {
return Json.decodeFromString<T>(
serializer(type) as KSerializer<T>,
packed.decodeToString()
)
}
}