package net.minestom.server.tag; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.minestom.server.item.ItemStack; import net.minestom.server.utils.Utils; import org.jglrxavpok.hephaistos.nbt.*; import java.util.function.Function; /** * Basic serializers for {@link Tag tags}. */ final class Serializers { static final Entry BYTE = new Entry<>(NBTType.TAG_Byte, NBTByte::getValue, NBT::Byte); static final Entry BOOLEAN = new Entry<>(NBTType.TAG_Byte, NBTByte::asBoolean, NBT::Boolean); static final Entry SHORT = new Entry<>(NBTType.TAG_Short, NBTShort::getValue, NBT::Short); static final Entry INT = new Entry<>(NBTType.TAG_Int, NBTInt::getValue, NBT::Int); static final Entry LONG = new Entry<>(NBTType.TAG_Long, NBTLong::getValue, NBT::Long); static final Entry FLOAT = new Entry<>(NBTType.TAG_Float, NBTFloat::getValue, NBT::Float); static final Entry DOUBLE = new Entry<>(NBTType.TAG_Double, NBTDouble::getValue, NBT::Double); static final Entry STRING = new Entry<>(NBTType.TAG_String, NBTString::getValue, NBT::String); static final Entry NBT_ENTRY = new Entry<>(null, Function.identity(), Function.identity()); static final Entry UUID = new Entry<>(NBTType.TAG_Int_Array, intArray -> Utils.intArrayToUuid(intArray.getValue().copyArray()), uuid -> NBT.IntArray(Utils.uuidToIntArray(uuid))); static final Entry ITEM = new Entry<>(NBTType.TAG_Compound, ItemStack::fromItemNBT, ItemStack::toItemNBT); static final Entry COMPONENT = new Entry<>(NBTType.TAG_String, input -> GsonComponentSerializer.gson().deserialize(input.getValue()), component -> NBT.String(GsonComponentSerializer.gson().serialize(component))); static Entry fromTagSerializer(TagSerializer serializer) { return new Serializers.Entry<>(NBTType.TAG_Compound, (NBTCompound compound) -> { if (compound.isEmpty()) return null; return serializer.read(TagHandler.fromCompound(compound)); }, (value) -> { if (value == null) return NBTCompound.EMPTY; TagHandler handler = TagHandler.newHandler(); serializer.write(handler, value); return handler.asCompound(); }); } record Entry(NBTType nbtType, Function reader, Function writer, boolean isPath) { Entry(NBTType nbtType, Function reader, Function writer) { this(nbtType, reader, writer, false); } T read(N nbt) { return reader.apply(nbt); } N write(T value) { return writer.apply(value); } } }