diff --git a/src/main/java/io/wispforest/owo/mixin/ItemStackMixin.java b/src/main/java/io/wispforest/owo/mixin/ItemStackMixin.java index 560108be..3adbaaa0 100644 --- a/src/main/java/io/wispforest/owo/mixin/ItemStackMixin.java +++ b/src/main/java/io/wispforest/owo/mixin/ItemStackMixin.java @@ -1,5 +1,6 @@ package io.wispforest.owo.mixin; +import io.wispforest.owo.serialization.SerializationAttribute; import io.wispforest.owo.serialization.util.MapCarrier; import io.wispforest.owo.serialization.endec.KeyedEndec; import io.wispforest.owo.serialization.format.forwarding.ForwardingDeserializer; @@ -26,14 +27,12 @@ public abstract class ItemStackMixin implements MapCarrier { @Override public T getWithErrors(@NotNull KeyedEndec key) { if (!this.has(key)) return key.defaultValue(); - return key.endec() - .decodeFully(e -> ForwardingDeserializer.humanReadable(NbtDeserializer.of(e)), this.nbt.get(key.key())); + return key.endec().decodeFully(e -> NbtDeserializer.of(e).withAttributes(SerializationAttribute.HUMAN_READABLE), this.nbt.get(key.key())); } @Override public void put(@NotNull KeyedEndec key, @NotNull T value) { - this.getOrCreateNbt() - .put(key.key(), key.endec().encodeFully(() -> ForwardingSerializer.humanReadable(NbtSerializer.of()), value)); + this.getOrCreateNbt().put(key.key(), key.endec().encodeFully(() -> NbtSerializer.of().withAttributes(SerializationAttribute.HUMAN_READABLE), value)); } @Override diff --git a/src/main/java/io/wispforest/owo/mixin/NbtCompoundMixin.java b/src/main/java/io/wispforest/owo/mixin/NbtCompoundMixin.java index f616aaa0..9c262375 100644 --- a/src/main/java/io/wispforest/owo/mixin/NbtCompoundMixin.java +++ b/src/main/java/io/wispforest/owo/mixin/NbtCompoundMixin.java @@ -1,5 +1,6 @@ package io.wispforest.owo.mixin; +import io.wispforest.owo.serialization.SerializationAttribute; import io.wispforest.owo.serialization.util.MapCarrier; import io.wispforest.owo.serialization.endec.KeyedEndec; import io.wispforest.owo.serialization.format.forwarding.ForwardingDeserializer; @@ -29,13 +30,12 @@ public abstract class NbtCompoundMixin implements MapCarrier { @Override public T getWithErrors(@NotNull KeyedEndec key) { if (!this.has(key)) return key.defaultValue(); - return key.endec() - .decodeFully(e -> ForwardingDeserializer.humanReadable(NbtDeserializer.of(e)), this.get(key.key())); + return key.endec().decodeFully(e -> NbtDeserializer.of(e).withAttributes(SerializationAttribute.HUMAN_READABLE), this.get(key.key())); } @Override public void put(@NotNull KeyedEndec key, @NotNull T value) { - this.put(key.key(), key.endec().encodeFully(() -> ForwardingSerializer.humanReadable(NbtSerializer.of()), value)); + this.put(key.key(), key.endec().encodeFully(() -> NbtSerializer.of().withAttributes(SerializationAttribute.HUMAN_READABLE), value)); } @Override diff --git a/src/main/java/io/wispforest/owo/mixin/PacketByteBufMixin.java b/src/main/java/io/wispforest/owo/mixin/PacketByteBufMixin.java index d916a6f8..d1620a97 100644 --- a/src/main/java/io/wispforest/owo/mixin/PacketByteBufMixin.java +++ b/src/main/java/io/wispforest/owo/mixin/PacketByteBufMixin.java @@ -12,11 +12,11 @@ public class PacketByteBufMixin implements EndecBuffer { @Override public void write(Endec endec, T value) { - endec.encodeFully(() -> new ByteBufSerializer<>((PacketByteBuf) (Object) this), value); + endec.encodeFully(() -> ByteBufSerializer.of((PacketByteBuf) (Object) this), value); } @Override public T read(Endec endec) { - return endec.decodeFully(ByteBufDeserializer::new, (PacketByteBuf) (Object) this); + return endec.decodeFully(ByteBufDeserializer::of, (PacketByteBuf) (Object) this); } } diff --git a/src/main/java/io/wispforest/owo/network/OwoHandshake.java b/src/main/java/io/wispforest/owo/network/OwoHandshake.java index 8ce03f2b..69578d92 100644 --- a/src/main/java/io/wispforest/owo/network/OwoHandshake.java +++ b/src/main/java/io/wispforest/owo/network/OwoHandshake.java @@ -255,7 +255,7 @@ private static Pair, Set> findCollisions(Set REQUIRED_CHANNELS = new HashMap<>(); static final Map OPTIONAL_CHANNELS = new HashMap<>(); - private final Map, IndexedSerializer> serializersByClass = new HashMap<>(); - final Int2ObjectMap> serializersByIndex = new Int2ObjectOpenHashMap<>(); + private final Map, IndexedEndec> endecsByClass = new HashMap<>(); + final Int2ObjectMap> endecsByIndex = new Int2ObjectOpenHashMap<>(); private final List> clientHandlers = new ArrayList<>(); private final List> serverHandlers = new ArrayList<>(); - private final Reference2IntMap> deferredClientSerializers = new Reference2IntOpenHashMap<>(); + private final Reference2IntMap> deferredClientEndecs = new Reference2IntOpenHashMap<>(); final Identifier packetId; private final String ownerClassName; @@ -115,7 +113,7 @@ private OwoNetChannel(Identifier id, String ownerClassName, boolean required) { throw new IllegalStateException("Channel with id '" + id + "' was already registered from class '" + REGISTERED_CHANNELS.get(id).ownerClassName + "'"); } - deferredClientSerializers.defaultReturnValue(-1); + deferredClientEndecs.defaultReturnValue(-1); this.packetId = id; this.ownerClassName = ownerClassName; @@ -128,14 +126,14 @@ private OwoNetChannel(Identifier id, String ownerClassName, boolean required) { ServerPlayNetworking.registerGlobalReceiver(packetId, (server, player, handler, buf, responseSender) -> { int handlerIndex = buf.readVarInt(); - final Record message = serializersByIndex.get(handlerIndex).endec.decodeFully(ByteBufDeserializer::new, buf); + final Record message = buf.read(endecsByIndex.get(handlerIndex).endec); server.execute(() -> serverHandlers.get(handlerIndex).handle(message, new ServerAccess(player))); }); if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { ClientPlayNetworking.registerGlobalReceiver(packetId, (client, handler, buf, responseSender) -> { int handlerIndex = buf.readVarInt(); - final Record message = serializersByIndex.get(-handlerIndex).endec.decodeFully(ByteBufDeserializer::new, buf); + final Record message = buf.read(endecsByIndex.get(-handlerIndex).endec); client.execute(() -> clientHandlers.get(handlerIndex).handle(message, new ClientAccess(handler))); }); } @@ -153,8 +151,8 @@ private OwoNetChannel(Identifier id, String ownerClassName, boolean required) { /** * Registers a handler on the client for the specified message class. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * This also ensures the required endec is available. If an exception + * about a missing endec is thrown, register one * * @param messageClass The type of packet data to send and serialize * @param handler The handler that will receive the deserialized @@ -168,8 +166,8 @@ public void registerClientbound(Class messageClass, Channe /** * Registers a message class on the client with deferred handler registration. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * This also ensures the required endec is available. If an exception + * about a missing endec is thrown, register one * * @param messageClass The type of packet data to send and serialize * @see #serverHandle(PlayerEntity) @@ -182,8 +180,8 @@ public void registerClientboundDeferred(Class messageClass /** * Registers a handler on the server for the specified message class. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * This also ensures the required endec is available. If an exception + * about a missing endec is thrown, register one * * @param messageClass The type of packet data to send and serialize * @param handler The handler that will receive the deserialized @@ -196,12 +194,10 @@ public void registerServerbound(Class messageClass, Channe //-- /** - * Registers a handler on the client for the specified message class. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * Registers a handler on the client for the specified message class * * @param messageClass The type of packet data to send and serialize - * @param endec The alternative Endec to Serialize the given Record + * @param endec The endec to serialize messages with * @param handler The handler that will receive the deserialized * @see #serverHandle(PlayerEntity) * @see #serverHandle(MinecraftServer) @@ -212,12 +208,10 @@ public void registerClientbound(Class messageClass, Struct } /** - * Registers a message class on the client with deferred handler registration. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * Registers a message class on the client with deferred handler registration * * @param messageClass The type of packet data to send and serialize - * @param endec The alternative Endec to Serialize the given Record + * @param endec The endec to serialize messages with * @see #serverHandle(PlayerEntity) * @see #serverHandle(MinecraftServer) * @see #serverHandle(ServerWorld, BlockPos) @@ -227,12 +221,10 @@ public void registerClientboundDeferred(Class messageClass } /** - * Registers a handler on the server for the specified message class. - * This also ensures the required serializer is available. If an exception - * about a missing type adapter is thrown, register one + * Registers a handler on the server for the specified message class * * @param messageClass The type of packet data to send and serialize - * @param endec The alternative Endec to Serialize the given Record + * @param endec The endec to serialize messages with * @param handler The handler that will receive the deserialized * @see #clientHandle() */ @@ -244,7 +236,7 @@ public void registerServerbound(Class messageClass, Struct @SuppressWarnings("unchecked") private void registerClientbound(Class messageClass, ChannelHandler handler, Supplier> endec) { - int deferredIndex = deferredClientSerializers.removeInt(messageClass); + int deferredIndex = deferredClientEndecs.removeInt(messageClass); if (deferredIndex != -1) { OwoFreezer.checkRegister("Network handlers"); @@ -253,22 +245,22 @@ private void registerClientbound(Class messageClass, Chan } int index = this.clientHandlers.size(); - this.createSerializer(messageClass, index, EnvType.CLIENT, endec); + this.createEndec(messageClass, index, EnvType.CLIENT, endec); this.clientHandlers.add((ChannelHandler) handler); } private void registerClientboundDeferred(Class messageClass, Supplier> endec) { int index = this.clientHandlers.size(); - this.createSerializer(messageClass, index, EnvType.CLIENT, endec); + this.createEndec(messageClass, index, EnvType.CLIENT, endec); this.clientHandlers.add(null); - this.deferredClientSerializers.put(messageClass, index); + this.deferredClientEndecs.put(messageClass, index); } @SuppressWarnings("unchecked") private void registerServerbound(Class messageClass, ChannelHandler handler, Supplier> endec) { int index = this.serverHandlers.size(); - this.createSerializer(messageClass, index, EnvType.SERVER, endec); + this.createEndec(messageClass, index, EnvType.SERVER, endec); this.serverHandlers.add((ChannelHandler) handler); } @@ -400,17 +392,17 @@ private ServerHandle getServerHandle() { return serverHandle; } - private void createSerializer(Class messageClass, int handlerIndex, EnvType target, Supplier> supplier) { + private void createEndec(Class messageClass, int handlerIndex, EnvType target, Supplier> supplier) { OwoFreezer.checkRegister("Network handlers"); - var serializer = serializersByClass.get(messageClass); - if (serializer == null) { - final var indexedSerializer = IndexedSerializer.create(messageClass, supplier.get(), handlerIndex, target); - serializersByClass.put(messageClass, indexedSerializer); - serializersByIndex.put(target == EnvType.CLIENT ? -handlerIndex : handlerIndex, indexedSerializer); - } else if (serializer.handlerIndex(target) == -1) { - serializer.setHandlerIndex(handlerIndex, target); - serializersByIndex.put(target == EnvType.CLIENT ? -handlerIndex : handlerIndex, serializer); + var endec = endecsByClass.get(messageClass); + if (endec == null) { + final var indexedEndec = IndexedEndec.create(messageClass, supplier.get(), handlerIndex, target); + endecsByClass.put(messageClass, indexedEndec); + endecsByIndex.put(target == EnvType.CLIENT ? -handlerIndex : handlerIndex, indexedEndec); + } else if (endec.handlerIndex(target) == -1) { + endec.setHandlerIndex(handlerIndex, target); + endecsByIndex.put(target == EnvType.CLIENT ? -handlerIndex : handlerIndex, endec); } else { throw new IllegalStateException("Message class '" + messageClass.getName() + "' is already registered for target environment " + target); } @@ -422,17 +414,19 @@ private PacketByteBuf encode(R message, EnvType target) { final var messageClass = message.getClass(); - if (!this.serializersByClass.containsKey(messageClass)) { + if (!this.endecsByClass.containsKey(messageClass)) { throw new NetworkException("Message class '" + messageClass + "' is not registered"); } - final IndexedSerializer serializer = (IndexedSerializer) this.serializersByClass.get(messageClass); - if (serializer.handlerIndex(target) == -1) { - throw new NetworkException("Message class '" + messageClass + "' has not handler registered for target environment " + target); + final IndexedEndec endec = (IndexedEndec) this.endecsByClass.get(messageClass); + if (endec.handlerIndex(target) == -1) { + throw new NetworkException("Message class '" + messageClass + "' has no handler registered for target environment " + target); } - buffer.writeVarInt(serializer.handlerIndex(target)); - return serializer.endec.encodeFully(() -> new ByteBufSerializer<>(buffer), message); + buffer.writeVarInt(endec.handlerIndex(target)); + buffer.write(endec.endec, message); + + return buffer; } public class ClientHandle { @@ -537,8 +531,8 @@ public interface EnvironmentAccess

{ private void verify() { if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) { - if (!this.deferredClientSerializers.isEmpty()) { - throw new NetworkException("Some deferred client handlers for channel " + packetId + " haven't been registered: " + deferredClientSerializers.keySet().stream().map(Class::getName).collect(Collectors.joining(", "))); + if (!this.deferredClientEndecs.isEmpty()) { + throw new NetworkException("Some deferred client handlers for channel " + packetId + " haven't been registered: " + deferredClientEndecs.keySet().stream().map(Class::getName).collect(Collectors.joining(", "))); } } } @@ -551,23 +545,23 @@ private void verify() { }); } - static final class IndexedSerializer { + static final class IndexedEndec { private int clientHandlerIndex = -1; private int serverHandlerIndex = -1; private final Class recordClass; private final StructEndec endec; - private IndexedSerializer(Class recordClass, StructEndec endec) { + private IndexedEndec(Class recordClass, StructEndec endec) { this.endec = endec; this.recordClass = recordClass; } - public static IndexedSerializer create(Class rClass, StructEndec endec, int index, EnvType target) { - return new IndexedSerializer<>(rClass, endec).setHandlerIndex(index, target); + public static IndexedEndec create(Class rClass, StructEndec endec, int index, EnvType target) { + return new IndexedEndec<>(rClass, endec).setHandlerIndex(index, target); } - public IndexedSerializer setHandlerIndex(int index, EnvType target) { + public IndexedEndec setHandlerIndex(int index, EnvType target) { switch (target) { case CLIENT -> this.clientHandlerIndex = index; case SERVER -> this.serverHandlerIndex = index; diff --git a/src/main/java/io/wispforest/owo/serialization/Deserializer.java b/src/main/java/io/wispforest/owo/serialization/Deserializer.java index 05bbfcd0..8284af8d 100644 --- a/src/main/java/io/wispforest/owo/serialization/Deserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/Deserializer.java @@ -1,5 +1,6 @@ package io.wispforest.owo.serialization; +import io.wispforest.owo.serialization.format.forwarding.ForwardingDeserializer; import org.jetbrains.annotations.Nullable; import java.util.Iterator; @@ -9,6 +10,11 @@ public interface Deserializer { + default Deserializer withAttributes(SerializationAttribute... assumedAttributes) { + if (assumedAttributes.length == 0) return this; + return ForwardingDeserializer.of(this, assumedAttributes); + } + Set attributes(); byte readByte(); diff --git a/src/main/java/io/wispforest/owo/serialization/Endec.java b/src/main/java/io/wispforest/owo/serialization/Endec.java index 1d9fa4a9..cca934fe 100644 --- a/src/main/java/io/wispforest/owo/serialization/Endec.java +++ b/src/main/java/io/wispforest/owo/serialization/Endec.java @@ -157,6 +157,26 @@ static Endec> map(Endec keyEndec, Endec valueEndec) { ).listOf().xmap(entries -> Map.ofEntries(entries.toArray(Map.Entry[]::new)), kvMap -> List.copyOf(kvMap.entrySet())); } + /** + * Create a new endec which serializes a map from keys encoded as strings using + * {@code keyToString} and decoded using {@code stringToKey} to values serialized + * using {@code valueEndec} + */ + static Endec> map(Function keyToString, Function stringToKey, Endec valueEndec) { + return of((serializer, map) -> { + try (var mapState = serializer.map(valueEndec, map.size())) { + map.forEach((k, v) -> mapState.entry(keyToString.apply(k), v)); + } + }, deserializer -> { + var mapState = deserializer.map(valueEndec); + + var map = new HashMap(mapState.estimatedSize()); + mapState.forEachRemaining(entry -> map.put(stringToKey.apply(entry.getKey()), entry.getValue())); + + return map; + }); + } + /** * Create a new endec which serializes the enum constants of {@code enumClass} *

@@ -225,14 +245,14 @@ static Endec dispatchedStruct(Function> va * stored in a map: *

{@code
      * public final class Harald implements Herbert {
-     *      public static final Endec = StructEndecBuilder.of(...);
+     *      public static final StructEndec = StructEndecBuilder.of(...);
      *
      *      private final int haraldOMeter;
      *      ...
      * }
      *
      * public final class Albrecht implements Herbert {
-     *     public static final Endec = StructEndecBuilder.of(...);
+     *     public static final StructEndec = StructEndecBuilder.of(...);
      *
      *     private final List dadJokes;
      *      ...
@@ -249,7 +269,7 @@ static  Endec dispatchedStruct(Function> va
      * Endec.dispatchedStruct(HERBERT_REGISTRY::get, Herbert::id, BuiltInEndecs.IDENTIFIER, "type")
      * }
* - * If now encode an instance of {@code Albrecht} to JSON using this endec, we'll get the following result: + * If we now encode an instance of {@code Albrecht} to JSON using this endec, we'll get the following result: *
{@code
      * {
      *      "type": "herbert:albrecht",
@@ -408,7 +428,7 @@ default Codec codec(SerializationAttribute... assumedAttributes) {
             @Override
             public  DataResult> decode(DynamicOps ops, D input) {
                 try {
-                    return DataResult.success(new Pair<>(Endec.this.decode(new LenientEdmDeserializer(ops.convertTo(EdmOps.INSTANCE, input), assumedAttributes)), input));
+                    return DataResult.success(new Pair<>(Endec.this.decode(LenientEdmDeserializer.of(ops.convertTo(EdmOps.INSTANCE, input)).withAttributes(assumedAttributes)), input));
                 } catch (Exception e) {
                     return DataResult.error(e::getMessage);
                 }
@@ -417,7 +437,7 @@ public  DataResult> decode(DynamicOps ops, D input) {
             @Override
             public  DataResult encode(T input, DynamicOps ops, D prefix) {
                 try {
-                    return DataResult.success(EdmOps.INSTANCE.convertTo(ops, Endec.this.encodeFully(() -> new EdmSerializer(assumedAttributes), input)));
+                    return DataResult.success(EdmOps.INSTANCE.convertTo(ops, Endec.this.encodeFully(() -> EdmSerializer.of().withAttributes(assumedAttributes), input)));
                 } catch (Exception e) {
                     return DataResult.error(e::getMessage);
                 }
diff --git a/src/main/java/io/wispforest/owo/serialization/Serializer.java b/src/main/java/io/wispforest/owo/serialization/Serializer.java
index 9d6fc1aa..4b211b32 100644
--- a/src/main/java/io/wispforest/owo/serialization/Serializer.java
+++ b/src/main/java/io/wispforest/owo/serialization/Serializer.java
@@ -1,5 +1,6 @@
 package io.wispforest.owo.serialization;
 
+import io.wispforest.owo.serialization.format.forwarding.ForwardingSerializer;
 import io.wispforest.owo.serialization.util.Endable;
 
 import java.util.Optional;
@@ -7,6 +8,11 @@
 
 public interface Serializer {
 
+    default Serializer withAttributes(SerializationAttribute... assumedAttributes) {
+        if (assumedAttributes.length == 0) return this;
+        return ForwardingSerializer.of(this, assumedAttributes);
+    }
+
     Set attributes();
 
     void writeByte(byte value);
diff --git a/src/main/java/io/wispforest/owo/serialization/StructEndec.java b/src/main/java/io/wispforest/owo/serialization/StructEndec.java
index e44a2033..9824ba05 100644
--- a/src/main/java/io/wispforest/owo/serialization/StructEndec.java
+++ b/src/main/java/io/wispforest/owo/serialization/StructEndec.java
@@ -12,7 +12,7 @@
 /**
  * Marker and template interface for all endecs which serialize structs
  * 

- * Every such endec should extend this interface to profit from the implementation of {@link #mapCodec()} + * Every such endec should extend this interface to profit from the implementation of {@link #mapCodec(SerializationAttribute...)} * and composability which allows {@link Endec#dispatchedStruct(Function, Function, Endec, String)} to work */ public interface StructEndec extends Endec { @@ -33,7 +33,7 @@ default T decode(Deserializer deserializer) { return this.decodeStruct(deserializer.struct()); } - default MapCodec mapCodec() { + default MapCodec mapCodec(SerializationAttribute... assumedAttributes) { return new MapCodec<>() { @Override public Stream keys(DynamicOps ops) { @@ -54,7 +54,7 @@ public DataResult decode(DynamicOps ops, MapLike input) { ); }); - return DataResult.success(StructEndec.this.decode(new LenientEdmDeserializer(EdmElement.wrapMap(map)))); + return DataResult.success(StructEndec.this.decode(LenientEdmDeserializer.of(EdmElement.wrapMap(map)).withAttributes(assumedAttributes))); } catch (Exception e) { return DataResult.error(e::getMessage); } @@ -63,7 +63,7 @@ public DataResult decode(DynamicOps ops, MapLike input) { @Override public RecordBuilder encode(T input, DynamicOps ops, RecordBuilder prefix) { try { - var element = StructEndec.this.encodeFully(EdmSerializer::new, input).>>cast(); + var element = StructEndec.this.encodeFully(() -> EdmSerializer.of().withAttributes(assumedAttributes), input).>>cast(); var result = prefix; for (var entry : element.entrySet()) { diff --git a/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufDeserializer.java index 8b551e20..9637b1db 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufDeserializer.java @@ -18,10 +18,14 @@ public class ByteBufDeserializer implements Deserializer { private final ByteBuf buffer; - public ByteBufDeserializer(ByteBuf buffer) { + protected ByteBufDeserializer(ByteBuf buffer) { this.buffer = buffer; } + public static ByteBufDeserializer of(ByteBuf buffer) { + return new ByteBufDeserializer(buffer); + } + // --- @Override diff --git a/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufSerializer.java index c4bb10f8..1e56a1ba 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/bytebuf/ByteBufSerializer.java @@ -17,12 +17,16 @@ public class ByteBufSerializer implements Serializer { private final B buffer; - public ByteBufSerializer(B buffer) { + protected ByteBufSerializer(B buffer) { this.buffer = buffer; } + public static ByteBufSerializer of(B buffer) { + return new ByteBufSerializer<>(buffer); + } + public static ByteBufSerializer packet() { - return new ByteBufSerializer<>(PacketByteBufs.create()); + return of(PacketByteBufs.create()); } // --- diff --git a/src/main/java/io/wispforest/owo/serialization/format/data/DataInputDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/data/DataInputDeserializer.java index 2b28931c..1422c328 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/data/DataInputDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/data/DataInputDeserializer.java @@ -11,35 +11,27 @@ import java.util.Set; import java.util.function.Function; -public class DataInputDeserializer implements Deserializer { +public class DataInputDeserializer implements Deserializer { - protected final D input; + protected final DataInput input; - public DataInputDeserializer(D input) { + protected DataInputDeserializer(DataInput input) { this.input = input; } - @Override - public Set attributes() { - return Set.of(); + public static DataInputDeserializer of(DataInput input) { + return new DataInputDeserializer(input); } - @Override - public Optional readOptional(Endec endec) { - return this.readBoolean() - ? Optional.of(endec.decode(this)) - : Optional.empty(); - } + // --- @Override - public boolean readBoolean() { - try { - return this.input.readBoolean(); - } catch (IOException e) { - throw new RuntimeException(e); - } + public Set attributes() { + return Set.of(); } + // --- + @Override public byte readByte() { try { @@ -94,27 +86,7 @@ public double readDouble() { } } - @Override - public String readString() { - try { - return this.input.readUTF(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public byte[] readBytes() { - var result = new byte[this.readVarInt()]; - - try { - this.input.readFully(result); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return result; - } + // --- @Override public int readVarInt() { @@ -158,11 +130,55 @@ public long readVarLong() { } } + // --- + @Override - public V tryRead(Function, V> reader) { + public boolean readBoolean() { + try { + return this.input.readBoolean(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public String readString() { + try { + return this.input.readUTF(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public byte[] readBytes() { + var result = new byte[this.readVarInt()]; + + try { + this.input.readFully(result); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return result; + } + + @Override + public Optional readOptional(Endec endec) { + return this.readBoolean() + ? Optional.of(endec.decode(this)) + : Optional.empty(); + } + + // --- + + @Override + public V tryRead(Function, V> reader) { throw new UnsupportedOperationException("As DataInput cannot be rewound, tryRead(...) cannot be supported"); } + // --- + @Override public Deserializer.Sequence sequence(Endec elementEndec) { return new Sequence<>(elementEndec, this.readVarInt()); @@ -178,6 +194,8 @@ public Struct struct() { return new Sequence<>(null, 0); } + // --- + private class Sequence implements Deserializer.Sequence, Struct { private final Endec valueEndec; diff --git a/src/main/java/io/wispforest/owo/serialization/format/data/DataOutputSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/data/DataOutputSerializer.java index c76187f1..b230a3fd 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/data/DataOutputSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/data/DataOutputSerializer.java @@ -13,13 +13,12 @@ public class DataOutputSerializer implements Serializer protected final D output; - public DataOutputSerializer(D output) { + protected DataOutputSerializer(D output) { this.output = output; } - @Override - public Set attributes() { - return null; + public static DataOutputSerializer of(D output) { + return new DataOutputSerializer<>(output); } protected void write(Writer writer) { @@ -30,17 +29,15 @@ protected void write(Writer writer) { } } - @Override - public void writeOptional(Endec endec, Optional optional) { - this.writeBoolean(optional.isPresent()); - optional.ifPresent(value -> endec.encode(this, value)); - } + // --- @Override - public void writeBoolean(boolean value) { - this.write(() -> this.output.writeBoolean(value)); + public Set attributes() { + return null; } + // --- + @Override public void writeByte(byte value) { this.write(() -> this.output.writeByte(value)); @@ -71,18 +68,7 @@ public void writeDouble(double value) { this.write(() -> this.output.writeDouble(value)); } - @Override - public void writeString(String value) { - this.write(() -> this.output.writeUTF(value)); - } - - @Override - public void writeBytes(byte[] bytes) { - this.write(() -> { - this.writeVarInt(bytes.length); - this.output.write(bytes); - }); - } + // --- @Override public void writeVarInt(int value) { @@ -112,11 +98,34 @@ public void writeVarLong(long value) { } } + // --- + @Override - public D result() { - return this.output; + public void writeBoolean(boolean value) { + this.write(() -> this.output.writeBoolean(value)); + } + + @Override + public void writeString(String value) { + this.write(() -> this.output.writeUTF(value)); + } + + @Override + public void writeBytes(byte[] bytes) { + this.write(() -> { + this.writeVarInt(bytes.length); + this.output.write(bytes); + }); } + @Override + public void writeOptional(Endec endec, Optional optional) { + this.writeBoolean(optional.isPresent()); + optional.ifPresent(value -> endec.encode(this, value)); + } + + // --- + @Override public Map map(Endec valueEndec, int size) { this.writeVarInt(size); @@ -134,6 +143,15 @@ public Struct struct() { return new Sequence<>(null); } + // --- + + @Override + public D result() { + return this.output; + } + + // --- + protected class Sequence implements Serializer.Sequence, Serializer.Struct, Serializer.Map { protected final Endec valueEndec; diff --git a/src/main/java/io/wispforest/owo/serialization/format/edm/EdmDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/edm/EdmDeserializer.java index 068132b1..9f1581e9 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/edm/EdmDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/edm/EdmDeserializer.java @@ -1,30 +1,28 @@ package io.wispforest.owo.serialization.format.edm; -import com.google.common.collect.ImmutableSet; import io.wispforest.owo.serialization.*; import io.wispforest.owo.serialization.util.RecursiveDeserializer; import org.jetbrains.annotations.Nullable; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import java.util.*; public class EdmDeserializer extends RecursiveDeserializer> implements SelfDescribedDeserializer> { - private final Set attributes; + private static final Set ATTRIBUTES = EnumSet.of( + SerializationAttribute.SELF_DESCRIBING + ); - public EdmDeserializer(EdmElement serialized, SerializationAttribute... extraAttributes) { + protected EdmDeserializer(EdmElement serialized) { super(serialized); - this.attributes = ImmutableSet.builder() - .add(SerializationAttribute.SELF_DESCRIBING) - .add(extraAttributes) - .build(); + } + + public static EdmDeserializer of(EdmElement serialized) { + return new EdmDeserializer(serialized); } @Override public Set attributes() { - return this.attributes; + return ATTRIBUTES; } // --- diff --git a/src/main/java/io/wispforest/owo/serialization/format/edm/EdmSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/edm/EdmSerializer.java index bccdefbe..7a24fff4 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/edm/EdmSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/edm/EdmSerializer.java @@ -10,19 +10,23 @@ public class EdmSerializer extends RecursiveSerializer> { - private final Set attributes; + private static final Set ATTRIBUTES = EnumSet.of( + SerializationAttribute.SELF_DESCRIBING + ); - public EdmSerializer(SerializationAttribute... extraAttributes) { + protected EdmSerializer() { super(null); - this.attributes = ImmutableSet.builder() - .add(SerializationAttribute.SELF_DESCRIBING) - .add(extraAttributes) - .build(); } + public static EdmSerializer of() { + return new EdmSerializer(); + } + + // --- + @Override public Set attributes() { - return this.attributes; + return ATTRIBUTES; } // --- diff --git a/src/main/java/io/wispforest/owo/serialization/format/edm/LenientEdmDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/edm/LenientEdmDeserializer.java index e2c1a331..93a20a04 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/edm/LenientEdmDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/edm/LenientEdmDeserializer.java @@ -7,8 +7,12 @@ public class LenientEdmDeserializer extends EdmDeserializer { - public LenientEdmDeserializer(EdmElement serialized, SerializationAttribute... extraAttributes) { - super(serialized, extraAttributes); + protected LenientEdmDeserializer(EdmElement serialized) { + super(serialized); + } + + public static LenientEdmDeserializer of(EdmElement serialized) { + return new LenientEdmDeserializer(serialized); } // --- diff --git a/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingDeserializer.java index cd1859e3..d6e27016 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingDeserializer.java @@ -10,40 +10,26 @@ public class ForwardingDeserializer implements Deserializer { private final Set attributes; - private final Deserializer wrappedSerializer; + private final Deserializer delegate; - protected ForwardingDeserializer(Deserializer wrappedSerializer, boolean humanReadable) { - this.wrappedSerializer = wrappedSerializer; - - var set = ImmutableSet.builder(); - - if (this.wrappedSerializer.attributes().contains(SerializationAttribute.SELF_DESCRIBING)) { - set.add(SerializationAttribute.SELF_DESCRIBING); - } - - if (humanReadable) { - set.add(SerializationAttribute.HUMAN_READABLE); - } - - this.attributes = set.build(); - } - - public static ForwardingDeserializer of(Deserializer deserializer) { - return create(deserializer, false); + protected ForwardingDeserializer(Deserializer delegate, Set attributes) { + this.delegate = delegate; + this.attributes = attributes; } - public static ForwardingDeserializer humanReadable(Deserializer deserializer) { - return create(deserializer, true); - } + public static ForwardingDeserializer of(Deserializer delegate, SerializationAttribute... assumedAttributes) { + var attributes = ImmutableSet.builder() + .addAll(delegate.attributes()) + .add(assumedAttributes) + .build(); - private static ForwardingDeserializer create(Deserializer deserializer, boolean humanReadable) { - return (deserializer instanceof SelfDescribedDeserializer selfDescribedDeserializer) - ? new ForwardingSelfDescribedDeserializer<>(selfDescribedDeserializer, humanReadable) - : new ForwardingDeserializer<>(deserializer, humanReadable); + return (delegate instanceof SelfDescribedDeserializer selfDescribedDeserializer) + ? new ForwardingSelfDescribedDeserializer<>(selfDescribedDeserializer, attributes) + : new ForwardingDeserializer<>(delegate, attributes); } public Deserializer delegate() { - return this.wrappedSerializer; + return this.delegate; } //-- @@ -55,87 +41,87 @@ public Set attributes() { @Override public byte readByte() { - return this.wrappedSerializer.readByte(); + return this.delegate.readByte(); } @Override public short readShort() { - return this.wrappedSerializer.readShort(); + return this.delegate.readShort(); } @Override public int readInt() { - return this.wrappedSerializer.readInt(); + return this.delegate.readInt(); } @Override public long readLong() { - return this.wrappedSerializer.readLong(); + return this.delegate.readLong(); } @Override public float readFloat() { - return this.wrappedSerializer.readFloat(); + return this.delegate.readFloat(); } @Override public double readDouble() { - return this.wrappedSerializer.readDouble(); + return this.delegate.readDouble(); } @Override public int readVarInt() { - return this.wrappedSerializer.readVarInt(); + return this.delegate.readVarInt(); } @Override public long readVarLong() { - return this.wrappedSerializer.readVarLong(); + return this.delegate.readVarLong(); } @Override public boolean readBoolean() { - return this.wrappedSerializer.readBoolean(); + return this.delegate.readBoolean(); } @Override public String readString() { - return this.wrappedSerializer.readString(); + return this.delegate.readString(); } @Override public byte[] readBytes() { - return this.wrappedSerializer.readBytes(); + return this.delegate.readBytes(); } @Override public Optional readOptional(Endec endec) { - return this.wrappedSerializer.readOptional(endec); + return this.delegate.readOptional(endec); } @Override public Sequence sequence(Endec elementEndec) { - return this.wrappedSerializer.sequence(elementEndec); + return this.delegate.sequence(elementEndec); } @Override public Map map(Endec valueEndec) { - return this.wrappedSerializer.map(valueEndec); + return this.delegate.map(valueEndec); } @Override public Struct struct() { - return this.wrappedSerializer.struct(); + return this.delegate.struct(); } @Override public V tryRead(Function, V> reader) { - return this.wrappedSerializer.tryRead(reader); + return this.delegate.tryRead(reader); } - public static class ForwardingSelfDescribedDeserializer extends ForwardingDeserializer implements SelfDescribedDeserializer { - private ForwardingSelfDescribedDeserializer(SelfDescribedDeserializer wrappedSerializer, boolean humanReadable) { - super(wrappedSerializer, humanReadable); + private static class ForwardingSelfDescribedDeserializer extends ForwardingDeserializer implements SelfDescribedDeserializer { + private ForwardingSelfDescribedDeserializer(Deserializer delegate, Set attributes) { + super(delegate, attributes); } @Override diff --git a/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingSerializer.java index 038de6bb..fe5c3a63 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/forwarding/ForwardingSerializer.java @@ -11,32 +11,25 @@ public class ForwardingSerializer implements Serializer { private final Set attributes; - private final Serializer innerSerializer; + private final Serializer delegate; - protected ForwardingSerializer(Serializer wrappedSerializer, boolean humanReadable) { - this.innerSerializer = wrappedSerializer; - - var set = ImmutableSet.builder(); - - if (this.innerSerializer.attributes().contains(SerializationAttribute.SELF_DESCRIBING)) { - set.add(SerializationAttribute.SELF_DESCRIBING); - } - - if (humanReadable) set.add(SerializationAttribute.HUMAN_READABLE); - - this.attributes = set.build(); + protected ForwardingSerializer(Serializer delegate, Set attributes) { + this.delegate = delegate; + this.attributes = attributes; } public Serializer delegate() { - return this.innerSerializer; - } - - public static ForwardingSerializer of(Serializer serializer) { - return new ForwardingSerializer<>(serializer, false); + return this.delegate; } - public static ForwardingSerializer humanReadable(Serializer serializer) { - return new ForwardingSerializer<>(serializer, true); + public static ForwardingSerializer of(Serializer delegate, SerializationAttribute... assumedAttributes) { + return new ForwardingSerializer<>( + delegate, + ImmutableSet.builder() + .addAll(delegate.attributes()) + .add(assumedAttributes) + .build() + ); } //-- @@ -48,81 +41,81 @@ public Set attributes() { @Override public void writeByte(byte value) { - this.innerSerializer.writeByte(value); + this.delegate.writeByte(value); } @Override public void writeShort(short value) { - this.innerSerializer.writeShort(value); + this.delegate.writeShort(value); } @Override public void writeInt(int value) { - this.innerSerializer.writeInt(value); + this.delegate.writeInt(value); } @Override public void writeLong(long value) { - this.innerSerializer.writeLong(value); + this.delegate.writeLong(value); } @Override public void writeFloat(float value) { - this.innerSerializer.writeFloat(value); + this.delegate.writeFloat(value); } @Override public void writeDouble(double value) { - this.innerSerializer.writeDouble(value); + this.delegate.writeDouble(value); } @Override public void writeVarInt(int value) { - this.innerSerializer.writeVarInt(value); + this.delegate.writeVarInt(value); } @Override public void writeVarLong(long value) { - this.innerSerializer.writeVarLong(value); + this.delegate.writeVarLong(value); } @Override public void writeBoolean(boolean value) { - this.innerSerializer.writeBoolean(value); + this.delegate.writeBoolean(value); } @Override public void writeString(String value) { - this.innerSerializer.writeString(value); + this.delegate.writeString(value); } @Override public void writeBytes(byte[] bytes) { - this.innerSerializer.writeBytes(bytes); + this.delegate.writeBytes(bytes); } @Override public void writeOptional(Endec endec, Optional optional) { - this.innerSerializer.writeOptional(endec, optional); + this.delegate.writeOptional(endec, optional); } @Override public Sequence sequence(Endec elementEndec, int size) { - return this.innerSerializer.sequence(elementEndec, size); + return this.delegate.sequence(elementEndec, size); } @Override public Map map(Endec valueEndec, int size) { - return this.innerSerializer.map(valueEndec, size); + return this.delegate.map(valueEndec, size); } @Override public Struct struct() { - return this.innerSerializer.struct(); + return this.delegate.struct(); } @Override public T result() { - return this.innerSerializer.result(); + return this.delegate.result(); } } diff --git a/src/main/java/io/wispforest/owo/serialization/format/json/JsonDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/json/JsonDeserializer.java index adeaf6d7..b1d931bb 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/json/JsonDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/json/JsonDeserializer.java @@ -20,16 +20,16 @@ public class JsonDeserializer extends RecursiveDeserializer impleme SerializationAttribute.HUMAN_READABLE ); - public JsonDeserializer(JsonElement serialized) { + protected JsonDeserializer(JsonElement serialized) { super(serialized); } - // --- - public static JsonDeserializer of(JsonElement serialized) { return new JsonDeserializer(serialized); } + // --- + @Override public Set attributes() { return ATTRIBUTES; diff --git a/src/main/java/io/wispforest/owo/serialization/format/json/JsonSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/json/JsonSerializer.java index 57064da7..e890cd15 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/json/JsonSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/json/JsonSerializer.java @@ -15,21 +15,19 @@ public class JsonSerializer extends RecursiveSerializer { private static final Set ATTRIBUTES = EnumSet.allOf(SerializationAttribute.class); private JsonElement prefix; - private JsonSerializer(JsonElement prefix) { + protected JsonSerializer(JsonElement prefix) { super(null); this.prefix = prefix; } - //-- - - public static JsonSerializer of() { - return new JsonSerializer(null); - } - public static JsonSerializer of(JsonElement prefix) { return new JsonSerializer(prefix); } + public static JsonSerializer of() { + return of(null); + } + // --- @Override diff --git a/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtDeserializer.java b/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtDeserializer.java index ba917d6e..a0863c59 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtDeserializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtDeserializer.java @@ -13,10 +13,14 @@ public class NbtDeserializer extends RecursiveDeserializer implement SerializationAttribute.SELF_DESCRIBING ); - private NbtDeserializer(NbtElement element) { + protected NbtDeserializer(NbtElement element) { super(element); } + public static NbtDeserializer of(NbtElement element) { + return new NbtDeserializer(element); + } + private N getAs(NbtElement element, Class clazz) { if (clazz.isInstance(element)) { return clazz.cast(element); @@ -27,10 +31,6 @@ private N getAs(NbtElement element, Class clazz) { // --- - public static NbtDeserializer of(NbtElement element) { - return new NbtDeserializer(element); - } - @Override public Set attributes() { return ATTRIBUTES; diff --git a/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtSerializer.java b/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtSerializer.java index 868c30e4..83482057 100644 --- a/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/format/nbt/NbtSerializer.java @@ -20,21 +20,19 @@ public class NbtSerializer extends RecursiveSerializer { protected NbtElement prefix; - public NbtSerializer(NbtElement prefix) { + protected NbtSerializer(NbtElement prefix) { super(NbtEnd.INSTANCE); this.prefix = prefix; } - // --- - - public static NbtSerializer of() { - return new NbtSerializer(null); - } - public static NbtSerializer of(NbtElement prefix) { return new NbtSerializer(prefix); } + public static NbtSerializer of() { + return of(null); + } + // --- @Override diff --git a/src/main/java/io/wispforest/owo/serialization/util/EndecRecipeSerializer.java b/src/main/java/io/wispforest/owo/serialization/util/EndecRecipeSerializer.java index 7f754d04..e67d620a 100644 --- a/src/main/java/io/wispforest/owo/serialization/util/EndecRecipeSerializer.java +++ b/src/main/java/io/wispforest/owo/serialization/util/EndecRecipeSerializer.java @@ -2,6 +2,7 @@ import com.mojang.serialization.Codec; import io.wispforest.owo.serialization.Endec; +import io.wispforest.owo.serialization.SerializationAttribute; import io.wispforest.owo.serialization.StructEndec; import net.minecraft.network.PacketByteBuf; import net.minecraft.recipe.Recipe; @@ -16,7 +17,7 @@ public abstract class EndecRecipeSerializer> implements Reci protected EndecRecipeSerializer(StructEndec endec, Endec networkEndec) { this.endec = endec; this.networkEndec = networkEndec; - this.codec = this.endec.mapCodec().codec(); + this.codec = this.endec.mapCodec(SerializationAttribute.HUMAN_READABLE).codec(); } protected EndecRecipeSerializer(StructEndec endec) { diff --git a/src/testmod/java/io/wispforest/uwu/FabledBananasClass.java b/src/testmod/java/io/wispforest/uwu/FabledBananasClass.java new file mode 100644 index 00000000..94258046 --- /dev/null +++ b/src/testmod/java/io/wispforest/uwu/FabledBananasClass.java @@ -0,0 +1,59 @@ +package io.wispforest.uwu; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import io.wispforest.owo.serialization.Endec; +import io.wispforest.owo.serialization.endec.BuiltInEndecs; +import io.wispforest.owo.serialization.endec.StructEndecBuilder; +import io.wispforest.owo.serialization.format.json.JsonDeserializer; +import io.wispforest.owo.serialization.format.json.JsonSerializer; +import net.minecraft.item.Item; +import net.minecraft.registry.Registries; +import net.minecraft.util.Identifier; +import net.minecraft.util.math.BlockPos; + +import java.util.List; +import java.util.Map; + +public class FabledBananasClass { + + public static final Endec ENDEC = StructEndecBuilder.of( + Endec.INT.fieldOf("banana_amount", FabledBananasClass::bananaAmount), + BuiltInEndecs.ofRegistry(Registries.ITEM).fieldOf("banana_item", FabledBananasClass::bananaItem), + BuiltInEndecs.BLOCK_POS.listOf().fieldOf("banana_positions", FabledBananasClass::bananaPositions), + FabledBananasClass::new + ); + + private final int bananaAmount; + private final Item bananaItem; + private final List bananaPositions; + + public FabledBananasClass(int bananaAmount, Item bananaItem, List bananaPositions) { + this.bananaAmount = bananaAmount; + this.bananaItem = bananaItem; + this.bananaPositions = bananaPositions; + } + + public int bananaAmount() {return this.bananaAmount;} + public Item bananaItem() {return this.bananaItem;} + public List bananaPositions() {return this.bananaPositions;} + + public static void main(String[] args) { + var pos = new BlockPos(1, 2, 3); + JsonElement result = BuiltInEndecs.BLOCK_POS.encodeFully(JsonSerializer::of, pos); + + System.out.println(result); + BlockPos decoded = BuiltInEndecs.BLOCK_POS.decodeFully(JsonDeserializer::of, result); + + + Endec> endec = Endec.map(Identifier::toString, Identifier::new, Endec.INT); + System.out.println(endec.encodeFully(JsonSerializer::of, Map.of(new Identifier("a"), 6, new Identifier("b"), 9)).toString()); + System.out.println(endec.decodeFully(JsonDeserializer::of, new Gson().fromJson("{\"a:b\":24,\"c\":17}", JsonObject.class))); + + Endec> mappy = Endec.map(BuiltInEndecs.BLOCK_POS, BuiltInEndecs.IDENTIFIER); + System.out.println(mappy.encodeFully(JsonSerializer::of, Map.of(BlockPos.ORIGIN, new Identifier("a"), new BlockPos(69, 420, 489), new Identifier("bruh:l"))).toString()); + System.out.println(mappy.decodeFully(JsonDeserializer::of, new Gson().fromJson("[{\"k\":[69,420,489],\"v\":\"bruh:l\"},{\"k\":[0,0,0],\"v\":\"minecraft:a\"}]", JsonArray.class))); + } +} diff --git a/src/testmod/java/io/wispforest/uwu/Uwu.java b/src/testmod/java/io/wispforest/uwu/Uwu.java index 89ff7144..3e867730 100644 --- a/src/testmod/java/io/wispforest/uwu/Uwu.java +++ b/src/testmod/java/io/wispforest/uwu/Uwu.java @@ -190,7 +190,7 @@ public void onInitialize() { var serializer = ByteBufSerializer.packet(); stackEndec.encode(serializer, stacknite); - System.out.println(stackEndec.decode(new ByteBufDeserializer(serializer.result()))); + System.out.println(serializer.result().read(stackEndec)); System.out.println(BuiltInEndecs.BLOCK_POS.codec().encodeStart(NbtOps.INSTANCE, new BlockPos(34, 35, 69)).result().get()); FieldRegistrationHandler.register(UwuItems.class, "uwu", true); @@ -459,10 +459,9 @@ public void onInitialize() { try { iterations("Endec", (buf) -> { ItemStack stack = source.getPlayer().getStackInHand(Hand.MAIN_HAND); + buf.write(BuiltInEndecs.ITEM_STACK, stack); - BuiltInEndecs.ITEM_STACK.encode(new ByteBufSerializer<>(buf), stack); - - var stackFromByte = BuiltInEndecs.ITEM_STACK.decodeFully(ByteBufDeserializer::new, buf); + var stackFromByte = buf.read(BuiltInEndecs.ITEM_STACK); }); } catch (Exception exception){ LOGGER.info(exception.getMessage()); diff --git a/src/testmod/java/io/wispforest/uwu/network/UwuNetworkTest.java b/src/testmod/java/io/wispforest/uwu/network/UwuNetworkTest.java index bac7850a..2fe0a557 100644 --- a/src/testmod/java/io/wispforest/uwu/network/UwuNetworkTest.java +++ b/src/testmod/java/io/wispforest/uwu/network/UwuNetworkTest.java @@ -38,7 +38,7 @@ public static void main(String[] args) { testEquals(endec, sameendec); testSerialization(test, testRecord -> { - return endec.decodeFully(ByteBufDeserializer::new, endec.encodeFully(ByteBufSerializer::packet, testRecord)); + return endec.decodeFully(ByteBufDeserializer::of, endec.encodeFully(ByteBufSerializer::packet, testRecord)); }); //-- @@ -52,7 +52,7 @@ public static void main(String[] args) { ); testSerialization(test, testRecord -> { - return builtendec.decodeFully(ByteBufDeserializer::new, builtendec.encodeFully(ByteBufSerializer::packet, testRecord)); + return builtendec.decodeFully(ByteBufDeserializer::of, builtendec.encodeFully(ByteBufSerializer::packet, testRecord)); }); } diff --git a/src/testmod/java/io/wispforest/uwu/recipe/EndecRecipeSerializer.java b/src/testmod/java/io/wispforest/uwu/recipe/EndecRecipeSerializer.java index cf24dd85..8afca3d5 100644 --- a/src/testmod/java/io/wispforest/uwu/recipe/EndecRecipeSerializer.java +++ b/src/testmod/java/io/wispforest/uwu/recipe/EndecRecipeSerializer.java @@ -26,11 +26,11 @@ public Codec codec() { @Override public void write(PacketByteBuf buf, T recipe) { - this.endec.encode(new ByteBufSerializer<>(buf), recipe); + buf.write(this.endec, recipe); } @Override public T read(PacketByteBuf buf) { - return this.endec.decode(new ByteBufDeserializer(buf)); + return buf.read(this.endec); } }