summaryrefslogtreecommitdiff
path: root/runtime/commonMain/src/kotlinx/serialization/modules/SerialModule.kt
blob: d96e4eaa7a218a5930dd3b8b00aba8173547e56f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("UNCHECKED_CAST", "RedundantVisibilityModifier")

package kotlinx.serialization.modules

import kotlinx.serialization.*
import kotlin.reflect.*

/**
 * [SerialModule] is a collection of serializers used by [ContextSerializer] and [PolymorphicSerializer]
 * to override or provide serializers at the runtime, whereas at the compile-time they provided by the serialization plugin.
 *
 * It can be considered as a map where serializers are found using statically known KClasses.
 *
 * To enable runtime resolution of serializers, one of the special annotations must be used on target types
 * and a serial module with serializers should be used during construction of [SerialFormat].
 *
 * @see ContextualSerialization
 * @see Polymorphic
 */
public interface SerialModule {

    /**
     * Returns a contextual serializer associated with a given [kclass].
     * This method is used in context-sensitive operations on a property marked with [ContextualSerialization] by a [ContextSerializer]
     */
    public fun <T : Any> getContextual(kclass: KClass<T>): KSerializer<T>?

    /**
     * Returns a polymorphic serializer registered for a class of the given [value] in the scope of [baseClass].
     */
    public fun <T : Any> getPolymorphic(baseClass: KClass<T>, value: T): KSerializer<out T>?

    /**
     * Returns a polymorphic serializer registered for for a [serializedClassName] in the scope of [baseClass].
     */
    public fun <T : Any> getPolymorphic(baseClass: KClass<T>, serializedClassName: String): KSerializer<out T>?

    /**
     * Copies contents of this module to the given [collector].
     */
    public fun dumpTo(collector: SerialModuleCollector)
}

/**
 * A [SerialModule] which is empty and always returns `null`.
 */
public object EmptyModule : SerialModule {
    public override fun <T : Any> getContextual(kclass: KClass<T>): KSerializer<T>? = null
    public override fun <T : Any> getPolymorphic(baseClass: KClass<T>, value: T): KSerializer<out T>? = null
    public override fun <T : Any> getPolymorphic(
        baseClass: KClass<T>,
        serializedClassName: String
    ): KSerializer<out T>? = null

    public override fun dumpTo(collector: SerialModuleCollector) = Unit
}