Add experimental TagSerializer.COMPOUND

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2022-04-22 04:32:44 +02:00
parent 3f98bde82e
commit 057109c94e
3 changed files with 45 additions and 2 deletions

View File

@ -30,6 +30,9 @@ public interface TagSerializer<T> {
*/
void write(@NotNull TagWritable writer, @NotNull T value);
@ApiStatus.Experimental
TagSerializer<NBTCompound> COMPOUND = TagSerializerImpl.COMPOUND;
@ApiStatus.Experimental
static <T> TagSerializer<T> fromCompound(@NotNull Function<NBTCompound, T> reader,
@NotNull Function<T, NBTCompound> writer) {

View File

@ -7,18 +7,30 @@ import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import java.util.function.Function;
final class TagSerializerImpl {
public static final TagSerializer<NBTCompound> COMPOUND = new TagSerializer<>() {
@Override
public @NotNull NBTCompound read(@NotNull TagReadable reader) {
return ((TagHandler) reader).asCompound();
}
@Override
public void write(@NotNull TagWritable writer, @NotNull NBTCompound value) {
TagNbtSeparator.separate(value, entry -> writer.setTag(entry.tag(), entry.value()));
}
};
static <T> TagSerializer<T> fromCompound(Function<NBTCompound, T> readFunc, Function<T, NBTCompound> writeFunc) {
return new TagSerializer<>() {
@Override
public @Nullable T read(@NotNull TagReadable reader) {
final NBTCompound compound = ((TagHandler) reader).asCompound();
final NBTCompound compound = COMPOUND.read(reader);
return readFunc.apply(compound);
}
@Override
public void write(@NotNull TagWritable writer, @NotNull T value) {
final NBTCompound compound = writeFunc.apply(value);
TagNbtSeparator.separate(compound, entry -> writer.setTag(entry.tag(), entry.value()));
COMPOUND.write(writer, compound);
}
};
}

View File

@ -2,8 +2,12 @@ package net.minestom.server.tag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBT;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static net.minestom.server.api.TestUtils.assertEqualsSNBT;
import static org.junit.jupiter.api.Assertions.*;
@ -77,4 +81,28 @@ public class TagViewTest {
""", handler.asCompound());
}
@Test
public void compoundSerializer() {
var tag = Tag.View(TagSerializer.COMPOUND);
var handler = TagHandler.newHandler();
handler.setTag(tag, NBT.Compound(Map.of("value", NBT.String("hello"))));
assertEqualsSNBT("""
{
"value":"hello"
}
""", handler.asCompound());
handler.setTag(Tag.Integer("value"), 5);
assertEqualsSNBT("""
{
"value":5,
}
""", handler.asCompound());
handler.setTag(tag, NBTCompound.EMPTY);
assertEqualsSNBT("{}", handler.asCompound());
handler.setTag(tag, null);
assertEqualsSNBT("{}", handler.asCompound());
}
}