Efficient "nullable" on Enum codec
This commit is contained in:
parent
e9a0983ab2
commit
ad71619b72
@ -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
|
||||||
|
Loading…
Reference in New Issue
Block a user