com.github.stormbit.vksdk.utils.Serialization.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vk-bot-sdk-kotlin Show documentation
Show all versions of vk-bot-sdk-kotlin Show documentation
The Kotlin library for working with VK api
The newest version!
package com.github.stormbit.vksdk.utils
import kotlinx.serialization.*
import kotlinx.serialization.builtins.nullable
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.ClassSerialDescriptorBuilder
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
@Serializable
data class BooleanInt(val value: Boolean) {
@Serializer(forClass = BooleanInt::class)
companion object : KSerializer {
override fun serialize(encoder: Encoder, value: BooleanInt) =
encoder.encodeInt(if (value.value) 1 else 0)
override fun deserialize(decoder: Decoder): BooleanInt =
BooleanInt(decoder.decodeNullableSerializableValue(Int.serializer().nullable) == 1)
}
operator fun getValue(nothing: Nothing?, property: KProperty<*>): Boolean {
return value
}
}
interface IntEnum {
val value: Int
}
@Suppress("FunctionName")
fun > EnumDescriptor(clazz: KClass, cases: Array): SerialDescriptor {
return buildClassSerialDescriptor(clazz.simpleName ?: "") {
for (case in cases) element(case.name, descriptor(case))
}
}
private fun > ClassSerialDescriptorBuilder.descriptor(case: E): SerialDescriptor {
return buildClassSerialDescriptor("$serialName.${case.name}")
}
abstract class EnumIntSerializer(clazz: KClass, cases: Array) : KSerializer where E : Enum, E : IntEnum {
private val caseByInt: Map = cases.associateBy(IntEnum::value)
override val descriptor: SerialDescriptor = EnumDescriptor(clazz, cases)
override fun serialize(encoder: Encoder, value: E) = encoder.encodeInt(value.value)
override fun deserialize(decoder: Decoder): E = caseByInt.getValue(decoder.decodeInt())
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy