Revert "Polyfill dataresult"

This reverts commit e3df0d82e0.
This commit is contained in:
DBotThePony 2024-01-01 17:30:48 +07:00
parent e3df0d82e0
commit 2cc8215cb0
Signed by: DBot
GPG Key ID: DCC23B5715498507
11 changed files with 63 additions and 91 deletions

View File

@ -10,10 +10,10 @@ import com.google.common.collect.ImmutableSet
import com.google.gson.JsonElement import com.google.gson.JsonElement
import com.google.gson.JsonObject import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive import com.google.gson.JsonPrimitive
import com.mojang.serialization.DataResult
import it.unimi.dsi.fastutil.objects.ObjectComparators import it.unimi.dsi.fastutil.objects.ObjectComparators
import net.minecraft.core.BlockPos import net.minecraft.core.BlockPos
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.NbtAccounter
import net.minecraft.network.FriendlyByteBuf import net.minecraft.network.FriendlyByteBuf
import net.minecraft.network.chat.ComponentContents import net.minecraft.network.chat.ComponentContents
import net.minecraft.network.chat.contents.TranslatableContents import net.minecraft.network.chat.contents.TranslatableContents
@ -26,6 +26,7 @@ import net.minecraft.world.item.crafting.Ingredient
import net.minecraft.world.level.BlockGetter import net.minecraft.world.level.BlockGetter
import net.minecraft.world.level.Level import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.level.block.state.BlockState
import net.minecraft.world.level.block.state.StateHolder import net.minecraft.world.level.block.state.StateHolder
import net.minecraft.world.level.block.state.properties.Property import net.minecraft.world.level.block.state.properties.Property
@ -40,7 +41,9 @@ import net.minecraftforge.registries.IForgeRegistry
import ru.dbotthepony.mc.otm.core.math.BlockRotation import ru.dbotthepony.mc.otm.core.math.BlockRotation
import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom import ru.dbotthepony.mc.otm.core.math.BlockRotationFreedom
import ru.dbotthepony.mc.otm.core.math.Vector import ru.dbotthepony.mc.otm.core.math.Vector
import ru.dbotthepony.mc.otm.core.util.readInt
import ru.dbotthepony.mc.otm.core.util.readVarIntLE import ru.dbotthepony.mc.otm.core.util.readVarIntLE
import ru.dbotthepony.mc.otm.core.util.writeInt
import ru.dbotthepony.mc.otm.core.util.writeVarIntLE import ru.dbotthepony.mc.otm.core.util.writeVarIntLE
import java.io.InputStream import java.io.InputStream
import java.io.OutputStream import java.io.OutputStream
@ -464,16 +467,3 @@ fun <A, B> lazy2(a: () -> A, b: A.() -> B): Supplier<B> {
val first = lazy(a) val first = lazy(a)
return Supplier { b.invoke(first.value) } return Supplier { b.invoke(first.value) }
} }
// 1.19.3 and earlier polyfill
fun <R> failure(message: String): DataResult<R> {
return DataResult.error { message }
}
fun <R> failure(message: Supplier<String>): DataResult<R> {
return DataResult.error(message)
}
fun <R> success(result: R): DataResult<R> {
return DataResult.success(result)
}

View File

@ -8,13 +8,11 @@ import com.mojang.serialization.DynamicOps
import net.minecraft.nbt.NbtAccounter import net.minecraft.nbt.NbtAccounter
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fluids.FluidStack
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.immutableMap import ru.dbotthepony.mc.otm.core.immutableMap
import ru.dbotthepony.mc.otm.core.math.RGBAColor import ru.dbotthepony.mc.otm.core.math.RGBAColor
import ru.dbotthepony.mc.otm.core.math.readDecimal import ru.dbotthepony.mc.otm.core.math.readDecimal
import ru.dbotthepony.mc.otm.core.math.writeDecimal import ru.dbotthepony.mc.otm.core.math.writeDecimal
import ru.dbotthepony.mc.otm.core.readItemType import ru.dbotthepony.mc.otm.core.readItemType
import ru.dbotthepony.mc.otm.core.success
import ru.dbotthepony.mc.otm.core.writeItemType import ru.dbotthepony.mc.otm.core.writeItemType
import java.io.DataInput import java.io.DataInput
import java.io.DataInputStream import java.io.DataInputStream
@ -197,11 +195,11 @@ class EnumValueCodec<V : Enum<V>>(clazz: Class<out V>) : IStreamCodec<V>, Codec<
override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<V, T>> { override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<V, T>> {
if (ops.compressMaps()) { if (ops.compressMaps()) {
return ops.getNumberValue(input) return ops.getNumberValue(input)
.flatMap { values.getOrNull(it.toInt())?.let { success(Pair(it, ops.empty())) } ?: failure { "No such enum with ordinal index $it" } } .flatMap { values.getOrNull(it.toInt())?.let { DataResult.success(Pair(it, ops.empty())) } ?: DataResult.error { "No such enum with ordinal index $it" } }
} }
return ops.getStringValue(input) return ops.getStringValue(input)
.flatMap { valuesMap[it]?.let { success(Pair(it, ops.empty())) } ?: failure { "No such enum value $it" } } .flatMap { valuesMap[it]?.let { DataResult.success(Pair(it, ops.empty())) } ?: DataResult.error { "No such enum value $it" } }
} }
companion object { companion object {

View File

@ -19,9 +19,7 @@ import net.minecraft.world.item.crafting.Ingredient
import net.minecraft.world.item.crafting.Recipe import net.minecraft.world.item.crafting.Recipe
import net.minecraft.world.item.crafting.RecipeSerializer import net.minecraft.world.item.crafting.RecipeSerializer
import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.LogManager
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.core.success
import ru.dbotthepony.mc.otm.core.util.readBinaryJsonWithCodecIndirect import ru.dbotthepony.mc.otm.core.util.readBinaryJsonWithCodecIndirect
import ru.dbotthepony.mc.otm.core.util.writeBinaryJsonWithCodec import ru.dbotthepony.mc.otm.core.util.writeBinaryJsonWithCodec
import kotlin.collections.ArrayDeque import kotlin.collections.ArrayDeque
@ -71,9 +69,9 @@ class Codec2RecipeSerializer<S : Recipe<*>>(
val read = serializer.fromNetwork(buff) val read = serializer.fromNetwork(buff)
if (read == null) if (read == null)
failure { "Unable to read parent recipe from network" } DataResult.error { "Unable to read parent recipe from network" }
else else
success(Pair(read, ops.empty())) DataResult.success(Pair(read, ops.empty()))
} }
} else { } else {
return serializer.codec().decode(ops, input) return serializer.codec().decode(ops, input)

View File

@ -5,7 +5,6 @@ import com.mojang.datafixers.util.Pair
import com.mojang.serialization.Codec import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps import com.mojang.serialization.DynamicOps
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.stream import ru.dbotthepony.mc.otm.core.stream
import java.util.function.Predicate import java.util.function.Predicate
import java.util.stream.Stream import java.util.stream.Stream
@ -33,7 +32,7 @@ class CodecList<S : Any>(codecs: Stream<Codec<S>>) : Codec<S> {
} }
} }
return failure { return DataResult.error {
"None of codecs encoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() } "None of codecs encoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() }
} }
} }
@ -51,7 +50,7 @@ class CodecList<S : Any>(codecs: Stream<Codec<S>>) : Codec<S> {
} }
} }
return failure { return DataResult.error {
"None of codecs decoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() } "None of codecs decoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() }
} }
} }
@ -84,11 +83,11 @@ class PredicatedCodecList<S : Any>(codecs: Stream<kotlin.Pair<Codec<S>, Predicat
} }
} else { } else {
val i2 = i val i2 = i
results.add(failure { "Codec #$i2 predicate tested false" }) results.add(DataResult.error { "Codec #$i2 predicate tested false" })
} }
} }
return failure { return DataResult.error {
"None of codecs encoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() } "None of codecs encoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() }
} }
} }
@ -106,7 +105,7 @@ class PredicatedCodecList<S : Any>(codecs: Stream<kotlin.Pair<Codec<S>, Predicat
} }
} }
return failure { return DataResult.error {
"None of codecs decoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() } "None of codecs decoded the input:\n " + results.joinToString(";\n ") { it.error().get().message() }
} }
} }

View File

@ -4,18 +4,17 @@ import com.mojang.datafixers.util.Pair
import com.mojang.serialization.Codec import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps import com.mojang.serialization.DynamicOps
import ru.dbotthepony.mc.otm.core.failure
class ComparableCodec<S : Comparable<S>>(val parent: Codec<S>, val min: S? = null, val max: S? = null, val minExclusive: Boolean = false, val maxExclusive: Boolean = false) : Codec<S> { class ComparableCodec<S : Comparable<S>>(val parent: Codec<S>, val min: S? = null, val max: S? = null, val minExclusive: Boolean = false, val maxExclusive: Boolean = false) : Codec<S> {
private fun <T : Any> check(input: S): DataResult<T>? { private fun <T : Any> check(input: S): DataResult<T>? {
if (min != null) { if (min != null) {
if (minExclusive) { if (minExclusive) {
if (input <= min) { if (input <= min) {
return failure { "Value $input is smaller or equal to minimal $min" } return DataResult.error { "Value $input is smaller or equal to minimal $min" }
} }
} else { } else {
if (input < min) { if (input < min) {
return failure { "Value $input is smaller than minimal $min" } return DataResult.error { "Value $input is smaller than minimal $min" }
} }
} }
} }
@ -23,11 +22,11 @@ class ComparableCodec<S : Comparable<S>>(val parent: Codec<S>, val min: S? = nul
if (max != null) { if (max != null) {
if (maxExclusive) { if (maxExclusive) {
if (input >= max) { if (input >= max) {
return failure { "Value $input is bigger or equal to maximal $max" } return DataResult.error { "Value $input is bigger or equal to maximal $max" }
} }
} else { } else {
if (input > max) { if (input > max) {
return failure { "Value $input is bigger than maximal $max" } return DataResult.error { "Value $input is bigger than maximal $max" }
} }
} }
} }

View File

@ -7,8 +7,6 @@ import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps import com.mojang.serialization.DynamicOps
import com.mojang.serialization.JsonOps import com.mojang.serialization.JsonOps
import net.minecraft.network.chat.Component import net.minecraft.network.chat.Component
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.success
object ComponentCodec : Codec<Component> { object ComponentCodec : Codec<Component> {
override fun <T : Any> encode(input: Component, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any> encode(input: Component, ops: DynamicOps<T>, prefix: T): DataResult<T> {
@ -19,9 +17,9 @@ object ComponentCodec : Codec<Component> {
val value = ops.convertTo(JsonOps.INSTANCE, input) val value = ops.convertTo(JsonOps.INSTANCE, input)
try { try {
return success(Pair(Component.Serializer.fromJson(value), ops.empty())) return DataResult.success(Pair(Component.Serializer.fromJson(value), ops.empty()))
} catch (err: JsonSyntaxException) { } catch (err: JsonSyntaxException) {
return failure { "Error decoding component: ${err.message}" } return DataResult.error { "Error decoding component: ${err.message}" }
} }
} }
} }

View File

@ -6,9 +6,7 @@ import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps import com.mojang.serialization.DynamicOps
import it.unimi.dsi.fastutil.bytes.ByteArrayList import it.unimi.dsi.fastutil.bytes.ByteArrayList
import net.minecraft.nbt.NbtOps import net.minecraft.nbt.NbtOps
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.math.Decimal import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.core.success
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.util.stream.Collector import java.util.stream.Collector
import java.util.stream.Stream import java.util.stream.Stream
@ -16,47 +14,47 @@ import java.util.stream.Stream
object DecimalCodec : Codec<Decimal> { object DecimalCodec : Codec<Decimal> {
override fun <T : Any> encode(input: Decimal, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any> encode(input: Decimal, ops: DynamicOps<T>, prefix: T): DataResult<T> {
if (ops === NbtOps.INSTANCE) { if (ops === NbtOps.INSTANCE) {
return success((ops as DynamicOps<T>).createByteList(ByteBuffer.wrap(input.toByteArray()))) return DataResult.success((ops as DynamicOps<T>).createByteList(ByteBuffer.wrap(input.toByteArray())))
} }
return success(ops.createString(input.toString())) return DataResult.success(ops.createString(input.toString()))
} }
override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Decimal, T>> { override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Decimal, T>> {
return ops.getStringValue(input).flatMap { return ops.getStringValue(input).flatMap {
try { try {
success(Pair(Decimal(it), ops.empty())) DataResult.success(Pair(Decimal(it), ops.empty()))
} catch (err: NumberFormatException) { } catch (err: NumberFormatException) {
failure { "Not a valid number for converting into Decimal: $it" } DataResult.error { "Not a valid number for converting into Decimal: $it" }
} }
}.get().map( }.get().map(
{ {
success(it) DataResult.success(it)
}, },
{ e0 -> { e0 ->
ops.getIntStream(input).flatMap { ops.getIntStream(input).flatMap {
try { try {
success(Pair(Decimal.fromByteArray( DataResult.success(Pair(Decimal.fromByteArray(
it it
.collect(::ByteArrayList, { v, a -> v.add(a.toByte()) }, ByteArrayList::addAll) .collect(::ByteArrayList, { v, a -> v.add(a.toByte()) }, ByteArrayList::addAll)
.toByteArray() .toByteArray()
), ops.empty())) ), ops.empty()))
} catch (err: NumberFormatException) { } catch (err: NumberFormatException) {
failure { "Failed to convert array of bytes into Decimal: $it" } DataResult.error { "Failed to convert array of bytes into Decimal: $it" }
} }
}.get().map( }.get().map(
{ {
success(it) DataResult.success(it)
}, },
{ e1 -> { e1 ->
ops.getNumberValue(input).flatMap { ops.getNumberValue(input).flatMap {
success(Pair(Decimal(it.toString()), ops.empty())) DataResult.success(Pair(Decimal(it.toString()), ops.empty()))
}.get().map( }.get().map(
{ {
success(it) DataResult.success(it)
}, },
{ e2 -> { e2 ->
failure { "None of attempts at decoding Decimal were successful: ${e0.message()}; ${e1.message()}; ${e2.message()}" } DataResult.error { "None of attempts at decoding Decimal were successful: ${e0.message()}; ${e1.message()}; ${e2.message()}" }
} }
) )
} }

View File

@ -11,9 +11,7 @@ import ru.dbotthepony.mc.otm.core.collect.allEqual
import ru.dbotthepony.mc.otm.core.collect.map import ru.dbotthepony.mc.otm.core.collect.map
import ru.dbotthepony.mc.otm.core.collect.toList import ru.dbotthepony.mc.otm.core.collect.toList
import ru.dbotthepony.mc.otm.core.collect.toStream import ru.dbotthepony.mc.otm.core.collect.toStream
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.stream import ru.dbotthepony.mc.otm.core.stream
import ru.dbotthepony.mc.otm.core.success
import ru.dbotthepony.mc.otm.recipe.IIngredientMatrix import ru.dbotthepony.mc.otm.recipe.IIngredientMatrix
import ru.dbotthepony.mc.otm.recipe.IngredientMatrix import ru.dbotthepony.mc.otm.recipe.IngredientMatrix
import java.util.function.Supplier import java.util.function.Supplier
@ -40,15 +38,15 @@ class IngredientMatrixCodec(ingredientCodec: Codec<Ingredient>) : Codec<IIngredi
it.group( it.group(
Codec.list(Codec.STRING) Codec.list(Codec.STRING)
.flatXmap( .flatXmap(
{ success(it) }, { DataResult.success(it) },
{ if (it.iterator().map { it.length }.allEqual()) success(it) else failure { "One or more of patten strings differ in length" } } { if (it.iterator().map { it.length }.allEqual()) DataResult.success(it) else DataResult.error { "One or more of patten strings differ in length" } }
) )
.fieldOf("pattern").forGetter(Handwritten::pattern), .fieldOf("pattern").forGetter(Handwritten::pattern),
Codec.unboundedMap( Codec.unboundedMap(
Codec.STRING Codec.STRING
.flatXmap( .flatXmap(
{ if (it.length == 1) success(it[0]) else failure { "Ingredient key must be exactly 1 symbol in length, '$it' is invalid" } }, { if (it.length == 1) DataResult.success(it[0]) else DataResult.error { "Ingredient key must be exactly 1 symbol in length, '$it' is invalid" } },
{ success(it.toString()) } { DataResult.success(it.toString()) }
), ingredientCodec).fieldOf("key").forGetter(Handwritten::key) ), ingredientCodec).fieldOf("key").forGetter(Handwritten::key)
).apply(it, ::Handwritten) ).apply(it, ::Handwritten)
} }
@ -71,11 +69,11 @@ class IngredientMatrixCodec(ingredientCodec: Codec<Ingredient>) : Codec<IIngredi
} }
if (errors.isNotEmpty()) { if (errors.isNotEmpty()) {
failure { "Failed to decode ingredient matrix: ${errors.joinToString { it.get() }}" } DataResult.error { "Failed to decode ingredient matrix: ${errors.joinToString { it.get() }}" }
} else if (ingredients.isEmpty()) { } else if (ingredients.isEmpty()) {
failure { "Ingredient list is empty" } DataResult.error { "Ingredient list is empty" }
} else if (!ingredients.iterator().map { it.size }.allEqual()) { } else if (!ingredients.iterator().map { it.size }.allEqual()) {
failure { "Ingredient list is not a matrix (one or multiple of rows are mismatched size)" } DataResult.error { "Ingredient list is not a matrix (one or multiple of rows are mismatched size)" }
} else { } else {
val result = IngredientMatrix(ingredients.first().size, ingredients.size) val result = IngredientMatrix(ingredients.first().size, ingredients.size)
@ -85,16 +83,16 @@ class IngredientMatrixCodec(ingredientCodec: Codec<Ingredient>) : Codec<IIngredi
} }
} }
success(Pair(result, ops.empty())) DataResult.success(Pair(result, ops.empty()))
} }
}, },
{ err1 -> { err1 ->
handwrittenCodec.decode(ops, input).get().map( handwrittenCodec.decode(ops, input).get().map(
{ {
success(it) DataResult.success(it)
}, },
{ {
failure { "Failed to decode ingredients as list: ${err1.message()} and as pattern/dictionary: ${it.message()}" } DataResult.error { "Failed to decode ingredients as list: ${err1.message()} and as pattern/dictionary: ${it.message()}" }
} }
).flatMap { ).flatMap {
val handwritten = it.first val handwritten = it.first
@ -102,12 +100,12 @@ class IngredientMatrixCodec(ingredientCodec: Codec<Ingredient>) : Codec<IIngredi
for ((row, pattern) in handwritten.pattern.withIndex()) { for ((row, pattern) in handwritten.pattern.withIndex()) {
for ((column, symbol) in pattern.withIndex()) { for ((column, symbol) in pattern.withIndex()) {
val ingredient = if (symbol == ' ') handwritten.key[symbol] ?: Ingredient.EMPTY else handwritten.key[symbol] ?: return@flatMap failure { "Unknown ingredient with index '$symbol'" } val ingredient = if (symbol == ' ') handwritten.key[symbol] ?: Ingredient.EMPTY else handwritten.key[symbol] ?: return@flatMap DataResult.error { "Unknown ingredient with index '$symbol'" }
result[column, row] = ingredient result[column, row] = ingredient
} }
} }
success(Pair(result, ops.empty())) DataResult.success(Pair(result, ops.empty()))
} }
} }
) )

View File

@ -5,8 +5,6 @@ import com.mojang.serialization.Codec
import com.mojang.serialization.DataResult import com.mojang.serialization.DataResult
import com.mojang.serialization.DynamicOps import com.mojang.serialization.DynamicOps
import net.minecraft.nbt.NbtOps import net.minecraft.nbt.NbtOps
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.success
import java.util.UUID import java.util.UUID
import java.util.stream.LongStream import java.util.stream.LongStream
@ -15,10 +13,10 @@ import java.util.stream.LongStream
object UUIDCodec : Codec<UUID> { object UUIDCodec : Codec<UUID> {
override fun <T : Any> encode(input: UUID, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any> encode(input: UUID, ops: DynamicOps<T>, prefix: T): DataResult<T> {
if (ops === NbtOps.INSTANCE) { if (ops === NbtOps.INSTANCE) {
return success((ops as DynamicOps<T>).createLongList(LongStream.of(input.mostSignificantBits, input.leastSignificantBits))) return DataResult.success((ops as DynamicOps<T>).createLongList(LongStream.of(input.mostSignificantBits, input.leastSignificantBits)))
} }
return success(ops.createString(input.toString())) return DataResult.success(ops.createString(input.toString()))
} }
override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<UUID, T>> { override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<UUID, T>> {
@ -27,25 +25,25 @@ object UUIDCodec : Codec<UUID> {
if (l.size == 4) { if (l.size == 4) {
// 4 int // 4 int
success(Pair(UUID((l[0] shl 32) or l[1], (l[2] shl 32) or l[3]), ops.empty())) DataResult.success(Pair(UUID((l[0] shl 32) or l[1], (l[2] shl 32) or l[3]), ops.empty()))
} else if (l.size == 2) { } else if (l.size == 2) {
success(Pair(UUID(l[0], l[1]), ops.empty())) DataResult.success(Pair(UUID(l[0], l[1]), ops.empty()))
} else { } else {
failure { "Can't construct UUID from ${l.size} elements" } DataResult.error { "Can't construct UUID from ${l.size} elements" }
} }
}.get().map( }.get().map(
{ {
success(it) DataResult.success(it)
}, },
{ e0 -> { e0 ->
ops.getStringValue(input).map { ops.getStringValue(input).map {
Pair(UUID.fromString(it), ops.empty()) Pair(UUID.fromString(it), ops.empty())
}.get().map( }.get().map(
{ {
success(it) DataResult.success(it)
}, },
{ {
failure { "Unable to deserialize UUID: ${e0.message()}; ${it.message()}" } DataResult.error { "Unable to deserialize UUID: ${e0.message()}; ${it.message()}" }
} }
) )
} }

View File

@ -11,9 +11,7 @@ import net.minecraft.resources.ResourceLocation
import net.minecraft.tags.TagKey import net.minecraft.tags.TagKey
import net.minecraft.world.item.Item import net.minecraft.world.item.Item
import net.minecraftforge.registries.ForgeRegistries import net.minecraftforge.registries.ForgeRegistries
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.math.Decimal import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.core.success
import ru.dbotthepony.mc.otm.data.DecimalCodec import ru.dbotthepony.mc.otm.data.DecimalCodec
import ru.dbotthepony.mc.otm.data.PredicatedCodecList import ru.dbotthepony.mc.otm.data.PredicatedCodecList
import java.util.Optional import java.util.Optional
@ -105,19 +103,19 @@ class ComputeAction(
val pair = this to this val pair = this to this
override fun <T : Any> encode(input: Constant, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any> encode(input: Constant, ops: DynamicOps<T>, prefix: T): DataResult<T> {
return success(ops.createString(symbol + input.matter.toString())) return DataResult.success(ops.createString(symbol + input.matter.toString()))
} }
override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Constant, T>> { override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Constant, T>> {
return ops.getStringValue(input).flatMap { return ops.getStringValue(input).flatMap {
if (it[0] == symbol) { if (it[0] == symbol) {
try { try {
success(Pair(Constant(Decimal(it.substring(1).trim()), it.substring(1).trim().toDouble(), fn, fn), ops.empty())) DataResult.success(Pair(Constant(Decimal(it.substring(1).trim()), it.substring(1).trim().toDouble(), fn, fn), ops.empty()))
} catch (err: NumberFormatException) { } catch (err: NumberFormatException) {
failure { "Not a number: ${it.substring(1).trim()} (input string: $it)" } DataResult.error { "Not a number: ${it.substring(1).trim()} (input string: $it)" }
} }
} else { } else {
failure { "Input string does not match expected operand: expected $symbol, got ${it[0]} (for input $it)" } DataResult.error { "Input string does not match expected operand: expected $symbol, got ${it[0]} (for input $it)" }
} }
} }
} }
@ -129,15 +127,15 @@ class ComputeAction(
private object PlainStringConstantCodec : Codec<Constant>, Predicate<Constant> { private object PlainStringConstantCodec : Codec<Constant>, Predicate<Constant> {
override fun <T : Any> encode(input: Constant, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any> encode(input: Constant, ops: DynamicOps<T>, prefix: T): DataResult<T> {
return success(ops.createString(input.matter.toString())) return DataResult.success(ops.createString(input.matter.toString()))
} }
override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Constant, T>> { override fun <T : Any> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<Constant, T>> {
val result = ops.getNumberValue(input).flatMap { val result = ops.getNumberValue(input).flatMap {
try { try {
success(Pair(Constant(Decimal(it.toString()), it.toDouble(), IMatterFunction.PLUS, IMatterFunction.PLUS), ops.empty())) DataResult.success(Pair(Constant(Decimal(it.toString()), it.toDouble(), IMatterFunction.PLUS, IMatterFunction.PLUS), ops.empty()))
} catch (err: NumberFormatException) { } catch (err: NumberFormatException) {
failure { "Not a number: $it" } DataResult.error { "Not a number: $it" }
} }
} }
@ -146,9 +144,9 @@ class ComputeAction(
return ops.getStringValue(input).flatMap { return ops.getStringValue(input).flatMap {
try { try {
success(Pair(Constant(Decimal(it), it.toDouble(), IMatterFunction.PLUS, IMatterFunction.PLUS), ops.empty())) DataResult.success(Pair(Constant(Decimal(it), it.toDouble(), IMatterFunction.PLUS, IMatterFunction.PLUS), ops.empty()))
} catch (err: NumberFormatException) { } catch (err: NumberFormatException) {
failure { "Not a number: $it" } DataResult.error { "Not a number: $it" }
} }
} }
} }

View File

@ -22,9 +22,7 @@ import net.minecraft.server.PlayerAdvancements
import net.minecraft.server.level.ServerPlayer import net.minecraft.server.level.ServerPlayer
import ru.dbotthepony.mc.otm.core.collect.filter import ru.dbotthepony.mc.otm.core.collect.filter
import ru.dbotthepony.mc.otm.core.collect.toImmutableList import ru.dbotthepony.mc.otm.core.collect.toImmutableList
import ru.dbotthepony.mc.otm.core.failure
import ru.dbotthepony.mc.otm.core.set import ru.dbotthepony.mc.otm.core.set
import ru.dbotthepony.mc.otm.core.success
import ru.dbotthepony.mc.otm.core.toJsonStrict import ru.dbotthepony.mc.otm.core.toJsonStrict
import java.util.Optional import java.util.Optional
import java.util.function.Predicate import java.util.function.Predicate
@ -87,16 +85,16 @@ abstract class MCriterionTrigger<T : MCriterionTrigger<T>.AbstractInstance>(val
@JvmStatic @JvmStatic
protected val predicateCodec: Codec<ContextAwarePredicate> = object : Codec<ContextAwarePredicate> { protected val predicateCodec: Codec<ContextAwarePredicate> = object : Codec<ContextAwarePredicate> {
override fun <T : Any?> encode(input: ContextAwarePredicate, ops: DynamicOps<T>, prefix: T): DataResult<T> { override fun <T : Any?> encode(input: ContextAwarePredicate, ops: DynamicOps<T>, prefix: T): DataResult<T> {
return success(JsonOps.INSTANCE.convertTo(ops, input.toJson())) return DataResult.success(JsonOps.INSTANCE.convertTo(ops, input.toJson()))
} }
override fun <T : Any?> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<ContextAwarePredicate, T>> { override fun <T : Any?> decode(ops: DynamicOps<T>, input: T): DataResult<Pair<ContextAwarePredicate, T>> {
val context = deserializationContext.get().lastOrNull() ?: return failure { "Not current deserializing trigger instance" } val context = deserializationContext.get().lastOrNull() ?: return DataResult.error { "Not current deserializing trigger instance" }
return try { return try {
success(Pair.of(EntityPredicate.fromJson(JsonObject().also { it["a"] = ops.convertTo(JsonOps.INSTANCE, input) }, "a", context).get(), ops.empty())) DataResult.success(Pair.of(EntityPredicate.fromJson(JsonObject().also { it["a"] = ops.convertTo(JsonOps.INSTANCE, input) }, "a", context).get(), ops.empty()))
} catch (err: Exception) { } catch (err: Exception) {
failure { "Failed to deserialize ContextAwarePredicate: " + err.message } DataResult.error { "Failed to deserialize ContextAwarePredicate: " + err.message }
} }
} }
} }