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

implementations.FixedCodecProvider.kt Maven / Gradle / Ivy

There is a newer version: 0.9.24
Show newest version
package com.github.fluidsonic.fluid.json

import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass


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)




© 2015 - 2024 Weber Informatics LLC | Privacy Policy