|
| 1 | +package net.errorcraft.codecium.mixin.mojang.serialization.codecs; |
| 2 | + |
| 3 | +import com.llamalad7.mixinextras.injector.ModifyReturnValue; |
| 4 | +import com.llamalad7.mixinextras.sugar.Local; |
| 5 | +import com.mojang.datafixers.util.Pair; |
| 6 | +import com.mojang.datafixers.util.Unit; |
| 7 | +import com.mojang.serialization.Codec; |
| 8 | +import com.mojang.serialization.DataResult; |
| 9 | +import com.mojang.serialization.DynamicOps; |
| 10 | +import com.mojang.serialization.codecs.DispatchedMapCodec; |
| 11 | +import net.errorcraft.codecium.util.StringUtil; |
| 12 | +import org.spongepowered.asm.mixin.Final; |
| 13 | +import org.spongepowered.asm.mixin.Mixin; |
| 14 | +import org.spongepowered.asm.mixin.Shadow; |
| 15 | +import org.spongepowered.asm.mixin.injection.At; |
| 16 | +import org.spongepowered.asm.mixin.injection.ModifyArg; |
| 17 | + |
| 18 | +import java.util.Optional; |
| 19 | +import java.util.function.Supplier; |
| 20 | +import java.util.function.UnaryOperator; |
| 21 | + |
| 22 | +@Mixin(value = DispatchedMapCodec.class, remap = false) |
| 23 | +public class DispatchedMapCodecExtender<K, V> { |
| 24 | + @Shadow |
| 25 | + @Final |
| 26 | + private Codec<K> keyCodec; |
| 27 | + |
| 28 | + @ModifyArg( |
| 29 | + method = "parseEntry", |
| 30 | + at = @At( |
| 31 | + value = "INVOKE", |
| 32 | + target = "Lcom/mojang/serialization/DataResult;error(Ljava/util/function/Supplier;)Lcom/mojang/serialization/DataResult;" |
| 33 | + ) |
| 34 | + ) |
| 35 | + @SuppressWarnings({ "OptionalUsedAsFieldOrParameterType", "OptionalGetWithoutIsPresent" }) |
| 36 | + private <T> Supplier<String> duplicateFieldUseBetterErrorMessage(Supplier<String> message, @Local(argsOnly = true) final DynamicOps<T> ops, @Local(argsOnly = true) final Pair<T, T> pair, @Local final Optional<Pair<K, V>> entry) { |
| 37 | + return () -> "Duplicate field " + this.keyCodec.encodeStart(ops, entry.get().getFirst()).getOrThrow() + ": " + pair.getFirst(); |
| 38 | + } |
| 39 | + |
| 40 | + @ModifyReturnValue( |
| 41 | + method = "parseEntry", |
| 42 | + at = @At("TAIL") |
| 43 | + ) |
| 44 | + private <T> DataResult<Unit> duplicateFieldUseBetterErrorMessage(DataResult<Unit> original, @Local(argsOnly = true) final Pair<T, T> input) { |
| 45 | + return original.mapError(message -> "For field " + input.getFirst() + ": " + message); |
| 46 | + } |
| 47 | + |
| 48 | + @ModifyArg( |
| 49 | + method = "lambda$decode$5", |
| 50 | + at = @At( |
| 51 | + value = "INVOKE", |
| 52 | + target = "Lcom/mojang/serialization/DataResult;mapError(Ljava/util/function/UnaryOperator;)Lcom/mojang/serialization/DataResult;" |
| 53 | + ) |
| 54 | + ) |
| 55 | + private UnaryOperator<String> mapErrorsUseBetterErrorMessage(UnaryOperator<String> function) { |
| 56 | + return message -> "Map has errors:\n" + StringUtil.indent(message); |
| 57 | + } |
| 58 | +} |
0 commit comments