aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/isxander/yacl3/config/v3/CodecConfigEntryImpl.java
blob: 855fd2256571ec935e3cd6fd17c6a259bf170096 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package dev.isxander.yacl3.config.v3;

import com.mojang.serialization.*;
import dev.isxander.yacl3.impl.utils.YACLConstants;
import org.jetbrains.annotations.ApiStatus;

import java.util.Optional;

@ApiStatus.Experimental
public class CodecConfigEntryImpl<T> extends AbstractConfigEntry<T> {
    private final MapCodec<T> mapCodec;

    public CodecConfigEntryImpl(String fieldName, T defaultValue, Codec<T> codec) {
        super(fieldName, defaultValue);
        this.mapCodec = codec.fieldOf(this.fieldName());
    }

    @Override
    public <R> RecordBuilder<R> encode(DynamicOps<R> ops, RecordBuilder<R> recordBuilder) {
        return mapCodec.encode(get(), ops, recordBuilder);
    }

    @Override
    public <R> boolean decode(R encoded, DynamicOps<R> ops) {
        DataResult<T> result = mapCodec.decoder().parse(ops, encoded);

        //? if >1.20.4 {
        Optional<DataResult.Error<T>> error = result.error();
         //?} else {
        /*Optional<DataResult.PartialResult<T>> error = result.error();
        *///?}
        if (error.isPresent()) {
            YACLConstants.LOGGER.error("Failed to decode entry {}: {}", this.fieldName(), error.get().message());
            return false;
        }

        T value = result.result().orElseThrow();
        this.set(value);

        return true;
    }
}