Skip to content

Commit

Permalink
Fix issues with incorrectly reading optional fields for NBT
Browse files Browse the repository at this point in the history
  • Loading branch information
Dragon-Seeker committed Dec 11, 2024
1 parent 478c7f7 commit 278ca4c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.wispforest.owo.serialization.format.nbt;

record IdentityHolder<T>(T t) {
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != this.getClass()) return false;
return this.t == ((IdentityHolder<?>) obj).t;
}

@Override
public int hashCode() {
return System.identityHashCode(this.t);
}

@Override
public String toString() {
return "IdentityHolder[t=" + t + ']';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,15 @@ public byte[] readBytes(SerializationContext ctx) {
return this.getAs(this.getValue(), NbtByteArray.class).getByteArray();
}

private final Set<IdentityHolder<NbtElement>> encodedOptionals = Collections.newSetFromMap(new WeakHashMap<>());

@Override
public <V> Optional<V> readOptional(SerializationContext ctx, Endec<V> endec) {
var value = this.getValue();
if (this.encodedOptionals.contains(new IdentityHolder<>(value))) {
return Optional.of(endec.decode(ctx, this));
}

var struct = this.struct();
return struct.field("present", ctx, Endec.BOOLEAN)
? Optional.of(struct.field("value", ctx, endec))
Expand Down Expand Up @@ -239,8 +246,10 @@ public Struct(NbtCompound compound) {

return defaultValueFactory.get();
}
var element = this.compound.get(name);
if (defaultValueFactory != null) NbtDeserializer.this.encodedOptionals.add(new IdentityHolder<>(element));
return NbtDeserializer.this.frame(
() -> this.compound.get(name),
() -> element,
() -> endec.decode(ctx, NbtDeserializer.this)
);
}
Expand Down

0 comments on commit 278ca4c

Please sign in to comment.