personthecat.catlib.serialization.codec.StrictOptionalCodec Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of catlib-quilt Show documentation
Show all versions of catlib-quilt Show documentation
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 com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
@SuppressWarnings("unused")
public class StrictOptionalCodec extends MapCodec> {
private final Codec codec;
private final MapCodec map;
private final String key;
public StrictOptionalCodec(final Codec codec, final String key) {
this.codec = codec;
this.map = codec.fieldOf(key);
this.key = key;
}
public Codec type() {
return this.codec;
}
public MapCodec wrapped() {
return this.map;
}
public String key() {
return this.key;
}
public RecordCodecBuilder> wrapGetter(final Function getter) {
return this.forGetter(o -> Optional.ofNullable(getter.apply(o)));
}
@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(Optional.empty());
}
return this.map.decode(ops, input).map(Optional::ofNullable);
}
@Override
public RecordBuilder encode(final Optional input, final DynamicOps ops, final RecordBuilder prefix) {
if (input.isPresent()) {
return this.map.encode(input.get(), ops, prefix);
}
return prefix;
}
@Override
public String toString() {
return "StrictOptionalCodec[" + this.key + " -> " + this.codec + "]";
}
}