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

tech.codingzen.kdi.dsl.module.ModuleDsl.kt Maven / Gradle / Ivy

package tech.codingzen.kdi.dsl.module

import tech.codingzen.kdi.InternalKdi
import tech.codingzen.kdi.data_structure.Descriptor
import tech.codingzen.kdi.Provider
import tech.codingzen.kdi.FQCN
import tech.codingzen.kdi.Tag
import tech.codingzen.kdi.data_structure.Providers
import tech.codingzen.kdi.data_structure.Kdi
import tech.codingzen.kdi.data_structure.KdiModule


class ModuleDsl {
  private val trie = mutableMapOf>()
  private val hash = this.hashCode()

  @PublishedApi
  @InternalKdi
  internal val tracked = mutableMapOf>>()

  val module: KdiModule get() = KdiModule.Impl(trie, tracked)

  inline fun  instance(t: T, tag: Tag = Kdi.defaultTag): Unit {
    provider(tag, Providers.instance(t))
  }

  inline fun  single(tag: Tag = Kdi.defaultTag, crossinline provider: Provider): Unit {
    provider(tag, Providers.single(provider))
  }

  inline fun  provider(tag: Tag = Kdi.defaultTag, noinline provider: Provider): Unit {
    val descriptor = Kdi.descriptor(tag)

    @Suppress("UNCHECKED_CAST")
    val cFactory = provider as Provider
    addCreator(this, descriptor, cFactory)
  }

  @InternalKdi
  fun addCreator(ref: Any, descriptor: Descriptor, provider: Provider): Unit {
    if (hash == ref.hashCode()) trie[descriptor] = provider
    else throw IllegalStateException("Only ModuleDsl can call addCreator")
  }

  @InternalKdi
  fun addTracked(ref: Any, fqcn: FQCN, provider: Provider): Unit {
    if (hash == ref.hashCode()) {
      tracked.putIfAbsent(fqcn, mutableSetOf())
      tracked[fqcn]!!.add(provider)
    } else throw IllegalStateException("Only ModuleDsl can call addCreator")
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy