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

jvmMain.dev.gitlive.firebase.internal._decoders.kt Maven / Gradle / Ivy

Go to download

The Firebase Kotlin SDK is a Kotlin-first SDK for Firebase. It's API is similar to the Firebase Android SDK Kotlin Extensions but also supports multiplatform projects, enabling you to use Firebase directly from your common source targeting iOS, Android or JS.

There is a newer version: 2.1.0
Show newest version
/*
 * Copyright (c) 2020 GitLive Ltd.  Use of this source code is governed by the Apache 2.0 license.
 */

package dev.gitlive.firebase.internal

import kotlinx.serialization.descriptors.PolymorphicKind
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.StructureKind
import kotlinx.serialization.encoding.CompositeDecoder

public actual fun FirebaseDecoder.structureDecoder(descriptor: SerialDescriptor, polymorphicIsNested: Boolean): CompositeDecoder = when (descriptor.kind) {
    StructureKind.CLASS, StructureKind.OBJECT -> decodeAsMap(false)
    StructureKind.LIST -> (value as? List<*>).orEmpty().let {
        FirebaseCompositeDecoder(it.size, settings) { _, index -> it[index] }
    }

    StructureKind.MAP -> (value as? Map<*, *>).orEmpty().entries.toList().let {
        FirebaseCompositeDecoder(
            it.size,
            settings,
        ) { _, index -> it[index / 2].run { if (index % 2 == 0) key else value } }
    }

    is PolymorphicKind -> decodeAsMap(polymorphicIsNested)
    else -> TODO("The firebase-kotlin-sdk does not support $descriptor for serialization yet")
}

public actual fun getPolymorphicType(value: Any?, discriminator: String): String =
    (value as? Map<*, *>).orEmpty()[discriminator] as String

private fun FirebaseDecoder.decodeAsMap(isNestedPolymorphic: Boolean): CompositeDecoder = (value as? Map<*, *>).orEmpty().let { map ->
    FirebaseClassDecoder(map.size, settings, { map.containsKey(it) }) { desc, index ->
        if (isNestedPolymorphic) {
            if (desc.getElementName(index) == "value") {
                map
            } else {
                map[desc.getElementName(index)]
            }
        } else {
            map[desc.getElementName(index)]
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy