commonMain.com.bselzer.ktx.serialization.serializer.Point2DSerializer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of geometry-serialization Show documentation
Show all versions of geometry-serialization Show documentation
kotlinx.serialization for two and three dimensional geometrical objects.
The newest version!
package com.bselzer.ktx.serialization.serializer
import com.bselzer.ktx.geometry.dimension.bi.position.Point2D
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
/**
* A serializer for converting an array into a two-dimensional point.
*/
class Point2DSerializer : KSerializer {
/**
* The serializer of the 2D point data.
*/
private val serializer = ListSerializer(Double.serializer())
@OptIn(ExperimentalSerializationApi::class)
override val descriptor: SerialDescriptor = SerialDescriptor(Point2D::class.qualifiedName!!, serializer.descriptor)
override fun deserialize(decoder: Decoder): Point2D = deserialize(serializer.deserialize(decoder))
/**
* Converts a list to a [Point2D].
*
* @param components the two-dimensional components
*/
fun deserialize(components: List) = Point2D(components.getOrElse(0) { 0.0 }, components.getOrElse(1) { 0.0 })
override fun serialize(encoder: Encoder, value: Point2D) {
val list = listOf(value.x, value.y)
serializer.serialize(encoder, list)
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy