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

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

package personthecat.catlib.serialization.codec;

import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

@SuppressWarnings("unused")
public abstract class FieldDescriptor {

    public final RecordCodecBuilder f;

    public FieldDescriptor(final RecordCodecBuilder f) {
        this.f = f;
    }

    public abstract R r(final T t);

    public static  FieldDescriptor field(final Codec type, final String name, final Function getter) {
        return passthrough(type.fieldOf(name).forGetter(getter));
    }

    public static  FieldDescriptor, T> nullable(final Codec type, final String name, final Function getter) {
        return new Nullable<>(new StrictOptionalCodec<>(type, name).wrapGetter(getter));
    }

    public static  Nullable nullable(final RecordCodecBuilder> f) {
        return new Nullable<>(f);
    }

    public static  FieldDescriptor, Optional> optional(final Codec type, final String name, final Function> getter) {
        return new Passthrough<>(new StrictOptionalCodec<>(type, name).forGetter(getter));
    }

    public static  FieldDescriptor defaulted(final Codec type, final String name, final T def, final Function getter) {
        return defaultGet(type, name, () -> def, getter);
    }

    public static  FieldDescriptor defaultGet(final Codec type, final String name, final Supplier def, final Function getter) {
        return new Passthrough<>(new DefaultedMapCodec<>(type, name, def).forGetter(getter));
    }

    public static  Passthrough passthrough(final RecordCodecBuilder f) {
        return new Passthrough<>(f);
    }

    public static class Passthrough extends FieldDescriptor {
        public Passthrough(final RecordCodecBuilder f) {
            super(f);
        }

        @Override
        public T r(final T t) {
            return t;
        }
    }

    public static class Nullable extends FieldDescriptor, T> {
        public Nullable(final RecordCodecBuilder> f) {
            super(f);
        }

        @Override
        public T r(final Optional t) {
            return t.orElse(null);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy