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 pack(type: KType, payload: T): ByteArray fun unpack(type: KType,packed: ByteArray): T } inline fun MotherPacker.pack(payload: T) = pack(typeOf(), payload) inline fun MotherPacker.unpack(packed: ByteArray) = unpack(typeOf(), packed) class JsonPacker : MotherPacker { override fun pack(type: KType, payload: T): ByteArray { return Json.encodeToString(serializer(type), payload).encodeToByteArray() } override fun unpack(type: KType, packed: ByteArray): T { return Json.decodeFromString( serializer(type) as KSerializer, packed.decodeToString() ) } }