io.wavebeans.execution.distributed.WindowSerializer.kt Maven / Gradle / Ivy
package io.wavebeans.execution.distributed
import io.wavebeans.lib.WaveBeansClassLoader
import io.wavebeans.lib.stream.fft.FftSample
import io.wavebeans.lib.stream.window.Window
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.reflect.jvm.jvmName
object WindowOfAnySerializer : KSerializer> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor(FftSample::class.jvmName) {
element("size", Int.serializer().descriptor)
element("step", Int.serializer().descriptor)
element("elements", ListObjectSerializer.descriptor)
element("zeroElFn", String.serializer().descriptor)
}
override fun deserialize(decoder: Decoder): Window {
val dec = decoder.beginStructure(descriptor)
var size: Int? = null
var step: Int? = null
var elements: List? = null
var zeroEl: (() -> Any)? = null
@Suppress("UNCHECKED_CAST")
loop@ while (true) {
when (val i = dec.decodeElementIndex(descriptor)) {
CompositeDecoder.DECODE_DONE -> break@loop
0 -> size = dec.decodeIntElement(descriptor, i)
1 -> step = dec.decodeIntElement(descriptor, i)
2 -> elements = dec.decodeSerializableElement(descriptor, i, ListObjectSerializer)
3 -> {
val clazz = WaveBeansClassLoader.classForName(dec.decodeStringElement(descriptor, i))
val constructor = clazz.declaredConstructors.first { it.parameterCount == 0 }
constructor.isAccessible = true
zeroEl = constructor.newInstance() as () -> Any
}
}
}
dec.endStructure(descriptor)
return Window(size!!, step!!, elements!!, zeroEl!!)
}
override fun serialize(encoder: Encoder, value: Window) {
val s = encoder.beginStructure(descriptor)
s.encodeIntElement(descriptor, 0, value.size)
s.encodeIntElement(descriptor, 1, value.step)
s.encodeSerializableElement(descriptor, 2, ListObjectSerializer, value.elements)
s.encodeStringElement(descriptor, 3, value.zeroEl::class.jvmName)
s.endStructure(descriptor)
}
}