0.1.1-SNAPSHOT: storages, sync tools, docs
This commit is contained in:
1 parent
3e6c487601
commit
babc3933eb
24 files changed
+925
-52
No files matched your search
@@ -0,0 +1,35 @@
|
||||
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()
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T> unpack(type: KType, packed: ByteArray): T {
|
||||
return Json.decodeFromString<T>(
|
||||
serializer(type) as KSerializer<T>,
|
||||
packed.decodeToString()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user