Add Raw Byte ItemStack Serialization

Serializes using NBT which is safer for server data migrations than bukkits format.
This commit is contained in:
Mariell Hoversholm 2020-04-30 16:56:54 +02:00
parent 167f0e69c8
commit f749992207

View File

@ -480,6 +480,53 @@ public final class CraftMagicNumbers implements UnsafeValues {
public com.destroystokyo.paper.util.VersionFetcher getVersionFetcher() {
return new com.destroystokyo.paper.PaperVersionFetcher();
}
@Override
public byte[] serializeItem(ItemStack item) {
Preconditions.checkNotNull(item, "null cannot be serialized");
Preconditions.checkArgument(item.getType() != Material.AIR, "air cannot be serialized");
return serializeNbtToBytes((net.minecraft.nbt.CompoundTag) (item instanceof CraftItemStack ? ((CraftItemStack) item).handle : CraftItemStack.asNMSCopy(item)).save(MinecraftServer.getServer().registryAccess()));
}
@Override
public ItemStack deserializeItem(byte[] data) {
Preconditions.checkNotNull(data, "null cannot be deserialized");
Preconditions.checkArgument(data.length > 0, "cannot deserialize nothing");
net.minecraft.nbt.CompoundTag compound = deserializeNbtFromBytes(data);
final int dataVersion = compound.getInt("DataVersion");
compound = (net.minecraft.nbt.CompoundTag) MinecraftServer.getServer().fixerUpper.update(References.ITEM_STACK, new Dynamic<>(NbtOps.INSTANCE, compound), dataVersion, this.getDataVersion()).getValue();
return CraftItemStack.asCraftMirror(net.minecraft.world.item.ItemStack.parse(MinecraftServer.getServer().registryAccess(), compound).orElseThrow());
}
private byte[] serializeNbtToBytes(CompoundTag compound) {
compound.putInt("DataVersion", getDataVersion());
java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream();
try {
net.minecraft.nbt.NbtIo.writeCompressed(
compound,
outputStream
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return outputStream.toByteArray();
}
private net.minecraft.nbt.CompoundTag deserializeNbtFromBytes(byte[] data) {
net.minecraft.nbt.CompoundTag compound;
try {
compound = net.minecraft.nbt.NbtIo.readCompressed(
new java.io.ByteArrayInputStream(data), net.minecraft.nbt.NbtAccounter.unlimitedHeap()
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
int dataVersion = compound.getInt("DataVersion");
Preconditions.checkArgument(dataVersion <= getDataVersion(), "Newer version! Server downgrades are not supported!");
return compound;
}
// Paper end
/**