All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.bselzer.ktx.serialization.serializer.PolygonSerializer.kt Maven / Gradle / Ivy

There is a newer version: 7.0.0
Show newest version
package com.bselzer.ktx.serialization.serializer

import com.bselzer.ktx.geometry.dimension.bi.polygon.Polygon
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 generic serializer for serializing polygons.
 */
abstract class PolygonSerializer : KSerializer {
    /**
     * The serializer of the point data.
     */
    private val serializer = ListSerializer(ListSerializer(Double.serializer()))

    abstract val serialName: String

    @OptIn(ExperimentalSerializationApi::class)
    override val descriptor: SerialDescriptor
        get() = SerialDescriptor(serialName, serializer.descriptor)

    override fun deserialize(decoder: Decoder): TPolygon = deserialize(serializer.deserialize(decoder))

    /**
     * @return the point at the [index] or a default
     */
    protected fun List.at(index: Int) = getOrElse(index) { Point2D() }

    /**
     * Converts a list of point components into a polygon.
     *
     * @return the polygon constructed by the [points]
     */
    @JvmName("deserializeComponents")
    fun deserialize(points: List>) = deserialize(points.map { components -> Point2D(components.getOrElse(0) { 0.0 }, components.getOrElse(1) { 0.0 }) })

    /**
     * Converts a list of points into a polygon.
     *
     * @return the polygon constructed by the [points]
     */
    abstract fun deserialize(points: List): TPolygon

    override fun serialize(encoder: Encoder, value: TPolygon) {
        serializer.serialize(encoder, value.points.map { point -> listOf(point.x, point.y) })
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy