implementations.FixedCodecProvider.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of fluid-json-coding Show documentation
Show all versions of fluid-json-coding Show documentation
A JSON library written in pure Kotlin (coding extension)
package com.github.fluidsonic.fluid.json
import java.util.concurrent.*
import kotlin.reflect.*
internal class FixedCodecProvider(
providers: Iterable>
) : JSONCodecProvider {
private val providers = providers.toSet().toTypedArray()
private val decoderCodecByType = ConcurrentHashMap, JSONDecoderCodec<*, Context>>()
private val encoderCodecByClass = ConcurrentHashMap, JSONEncoderCodec<*, Context>>()
@Suppress("LoopToCallChain", "UNCHECKED_CAST")
override fun decoderCodecForType(decodableType: JSONCodingType): JSONDecoderCodec? {
return decoderCodecByType.getOrPut(decodableType) {
for (provider in providers) {
val decoder = provider.decoderCodecForType(decodableType)
if (decoder != null) {
return@getOrPut decoder
}
}
return null
} as JSONDecoderCodec
}
@Suppress("LoopToCallChain", "UNCHECKED_CAST")
override fun encoderCodecForClass(encodableClass: KClass): JSONEncoderCodec? {
return encoderCodecByClass.getOrPut(encodableClass) {
for (provider in providers) {
val encoder = provider.encoderCodecForClass(encodableClass)
if (encoder != null) {
return@getOrPut encoder
}
}
return null
} as JSONEncoderCodec
}
}
@Suppress("FunctionName")
fun JSONCodecProvider(
vararg providers: JSONCodecProvider
) =
JSONCodecProvider(providers.asIterable())
@Suppress("FunctionName")
fun JSONCodecProvider(
providers: Iterable>
): JSONCodecProvider =
FixedCodecProvider(providers = providers)