Efficient "nullable" on Enum codec

This commit is contained in:
DBotThePony 2025-04-11 08:15:55 +07:00
parent e9a0983ab2
commit ad71619b72
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -189,6 +189,35 @@ interface MatteryStreamCodec<in S : ByteBuf, V> : StreamCodec<@UnsafeVariance S,
val values: List<V> = listOf(*this.clazz.enumConstants!!) val values: List<V> = listOf(*this.clazz.enumConstants!!)
val valuesMap = values.associateBy { it.name } val valuesMap = values.associateBy { it.name }
private val nullable = object : MatteryStreamCodec<S, V?> {
override fun decode(stream: S): V? {
val value = stream.readVarInt()
if (value == 0) {
return null
} else {
val id = value ushr 1
return values.getOrNull(id) ?: throw NoSuchElementException("No such enum with index $id")
}
}
override fun encode(stream: S, value: V?) {
if (value == null) {
stream.writeVarInt(0)
} else {
stream.writeVarInt(1 or (value.ordinal shl 1))
}
}
override fun copy(value: V?): V? {
return value
}
override fun compare(a: V?, b: V?): Boolean {
return a === b
}
}
override fun decode(stream: S): V { override fun decode(stream: S): V {
val id = stream.readVarInt() val id = stream.readVarInt()
return values.getOrNull(id) ?: throw NoSuchElementException("No such enum with index $id") return values.getOrNull(id) ?: throw NoSuchElementException("No such enum with index $id")
@ -206,6 +235,10 @@ interface MatteryStreamCodec<in S : ByteBuf, V> : StreamCodec<@UnsafeVariance S,
return a === b return a === b
} }
fun nullable(): MatteryStreamCodec<S, V?> {
return nullable
}
companion object { companion object {
/** /**
* FIXME: enums with abstract methods which get compiled to subclasses, whose DO NOT expose "parent's" enum constants array * FIXME: enums with abstract methods which get compiled to subclasses, whose DO NOT expose "parent's" enum constants array