/* * Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved * * You may use, distribute and modify this code under the * terms of the private license, which you must obtain from the author * * To obtain the license, contact the author: https://t.me/real_sergeych or email to * real dot sergeych at gmail. */ package net.sergeych.utools import kotlinx.serialization.KSerializer import kotlinx.serialization.serializer import net.sergeych.bintools.toDataSource import net.sergeych.bipack.BipackDecoder import net.sergeych.bipack.BipackEncoder /** * Effectively pack anyk nullable object. The result could be effectively packed * in turn as a part of a more complex structure. * * To avoid packing non-null mark, * we use a zero-size array, which, if in turn encoded, packs into a single * zero byte. Thus, we avoid extra byte spending for unnecessary null * check. */ inline fun pack(element: T?): UByteArray = pack(serializer(), element) /** * Unpack nullable data packed with [pack] */ inline fun unpack(encoded: UByteArray): T = unpack(serializer(), encoded) /** * Effectively pack anyk nullable object. The result could be effectively packed * in turn as a part of a more complex structure. * * To avoid packing non-null mark, * we use a zero-size array, which, if in turn encoded, packs into a single * zero byte. Thus, we avoid extra byte spending for unnecessary null * check. */ fun pack(serializer: KSerializer, element: T?): UByteArray = if (element == null) ubyteArrayOf() else BipackEncoder.encode(serializer,element).toUByteArray() /** * Unpack nullable data packed with [pack] */ @Suppress("UNCHECKED_CAST") fun unpack(serializer: KSerializer, encoded: UByteArray): T = if (encoded.isEmpty()) null as T else BipackDecoder.decode(encoded.asByteArray().toDataSource(),serializer)