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

net.chestmc.NamespacedKey.kt Maven / Gradle / Ivy

package net.chestmc

import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

/**
 * A namespaced key is a identifier key with a namespace and a key.
 * This is commonly used to store objects that need a id.
 * All [NamespacedKey] will be formated as lowercase.
 */
@Serializable(NamespacedKeySerializer::class)
data class NamespacedKey internal constructor(
  val namespace: String,
  val key: String,
) : Comparable {
  companion object {

    /**
     * Constructs a new namespaced key with the specified namespace and key.
     */
    fun of(namespace: String, key: String): NamespacedKey =
      NamespacedKey(namespace.lowercase(), key.lowercase())

    /**
     * Converts the specified string to a namespaced key.
     */
    fun from(string: String): NamespacedKey {
      val split = string.split(':', limit = 2)
      return of(split[0], split[1])
    }
  }

  override fun toString(): String {
    return "$namespace:$key"
  }

  override fun compareTo(other: NamespacedKey): Int {
    return toString().compareTo(other.toString())
  }
}


/**
 * A serializer type used to serialize/deserialize [NamespacedKey].
 */
object NamespacedKeySerializer : KSerializer {
  override val descriptor = PrimitiveSerialDescriptor("NamespacedKey", PrimitiveKind.STRING)

  override fun deserialize(decoder: Decoder): NamespacedKey {
    return NamespacedKey.from(decoder.decodeString())
  }

  override fun serialize(encoder: Encoder, value: NamespacedKey) {
    encoder.encodeString(value.toString())
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy