All Downloads are FREE. Search and download functionalities are using the official Maven repository.

personthecat.catlib.serialization.codec.DefaultedMapCodec Maven / Gradle / Ivy

Go to download

Utilities for serialization, commands, noise generation, IO, and some new data types.

The newest version!
package personthecat.catlib.serialization.codec;

import com.mojang.serialization.*;

import java.util.function.Supplier;
import java.util.stream.Stream;

@SuppressWarnings("unused")
public class DefaultedMapCodec extends MapCodec {
    private final Codec codec;
    private final MapCodec map;
    private final String key;
    private final Supplier def;

    public DefaultedMapCodec(final Codec codec, final String key, final Supplier def) {
        this.codec = codec;
        this.map = codec.fieldOf(key);
        this.key = key;
        this.def = def;
    }

    public Codec getType() {
        return this.codec;
    }

    public MapCodec wrapped() {
        return this.map;
    }

    public String key() {
        return this.key;
    }

    public A defaultValue() {
        return this.def.get();
    }

    @Override
    public  Stream keys(final DynamicOps ops) {
        return this.map.keys(ops);
    }

    @Override
    public  DataResult decode(final DynamicOps ops, final MapLike input) {
        if (input.get(this.key) == null) {
            return DataResult.success(this.defaultValue());
        }
        return this.map.decode(ops, input);
    }

    @Override
    public  RecordBuilder encode(final A input, final DynamicOps ops, final RecordBuilder prefix) {
        return this.map.encode(input, ops, prefix);
    }

    @Override
    public String toString() {
        return "DefaultedMapCodec[" + this.key + " -> " + this.codec + "]";
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy