EnumValueCodec writeByIndices

This commit is contained in:
DBotThePony 2023-01-29 22:31:50 +07:00
parent 44c0422387
commit b2998ccaa5
Signed by: DBot
GPG Key ID: DCC23B5715498507
3 changed files with 15 additions and 10 deletions

View File

@ -82,7 +82,7 @@ class SynchronizedRedstoneControl(
valueChanges.invoke(state, old)
}
}
}, name = if (fieldNamePrefix != null) "${fieldNamePrefix}_redstoneSetting" else null)
}, name = if (fieldNamePrefix != null) "${fieldNamePrefix}_redstoneSetting" else null, writeByIndices = true)
override var redstoneSignal: Int by synchronizer.int(0, setter = { value, access, setByRemote ->
if (setByRemote) {

View File

@ -75,21 +75,24 @@ val VarIntValueCodec = StreamCodec(DataInputStream::readVarIntLE, DataOutputStre
val VarLongValueCodec = StreamCodec(DataInputStream::readVarLongLE, DataOutputStream::writeVarLongLE)
val BinaryStringCodec = StreamCodec(DataInputStream::readBinaryString, DataOutputStream::writeBinaryString)
class EnumValueCodec<V : Enum<V>>(private val clazz: Class<out V>) : IStreamCodec<V> {
class EnumValueCodec<V : Enum<V>>(clazz: Class<out V>, val writeByIndices: Boolean = false) : IStreamCodec<V> {
private val values = clazz.enumConstants
override fun read(stream: DataInputStream): V {
val id = stream.readVarIntLE()
if (id >= values.size) {
throw IndexOutOfBoundsException("Unable to read enum $clazz, no such enum at index $id")
if (writeByIndices) {
val id = stream.readVarIntLE()
return values.getOrNull(id) ?: throw NoSuchElementException("No such enum with index $id")
}
return values[id]
val id = stream.readBinaryString()
return values.firstOrNull { id == it.name } ?: throw NoSuchElementException("No such enum $id")
}
override fun write(stream: DataOutputStream, value: V) {
stream.writeVarIntLE(value.ordinal)
if (writeByIndices)
stream.writeVarIntLE(value.ordinal)
else
stream.writeBinaryString(value.name)
}
override fun copy(value: V): V {

View File

@ -348,9 +348,10 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
value: T = type.enumConstants[0],
getter: FieldGetter<T>? = null,
setter: FieldSetter<T>? = null,
writeByIndices: Boolean = false,
name: String? = nextFieldName(),
): Field<T> {
return Field(value, EnumValueCodec(type), getter, setter, name = name ?: nextFieldName())
return Field(value, EnumValueCodec(type, writeByIndices = writeByIndices), getter, setter, name = name ?: nextFieldName())
}
@JvmOverloads
@ -358,9 +359,10 @@ class FieldSynchronizer(private val callback: Runnable, private val alwaysCallCa
value: T,
getter: FieldGetter<T>? = null,
setter: FieldSetter<T>? = null,
writeByIndices: Boolean = false,
name: String? = nextFieldName(),
): Field<T> {
return Field(value, EnumValueCodec(value::class.java), getter, setter, name = name ?: nextFieldName())
return Field(value, EnumValueCodec(value::class.java, writeByIndices = writeByIndices), getter, setter, name = name ?: nextFieldName())
}
@JvmOverloads