Skip to content

Commit 80b39fc

Browse files
committed
Implement setRootTag with parent management
1 parent 137c72d commit 80b39fc

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

src/main/java/org/glavo/nbt/chunk/Chunk.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.glavo.nbt.internal.Access;
2121
import org.glavo.nbt.internal.ChunkUtils;
2222
import org.glavo.nbt.tag.CompoundTag;
23+
import org.glavo.nbt.tag.Tag;
2324
import org.jetbrains.annotations.Contract;
2425
import org.jetbrains.annotations.Nullable;
2526

@@ -72,7 +73,27 @@ public int getLocalZ() {
7273

7374
@Contract(mutates = "this,param1")
7475
public void setRootTag(@Nullable CompoundTag rootTag) {
75-
// TODO: remove old root tag from its parent
76+
if (rootTag == this.rootTag) {
77+
return;
78+
}
79+
80+
if (this.rootTag != null) {
81+
remove(this.rootTag);
82+
}
83+
84+
if (rootTag != null) {
85+
if (rootTag.getParent() != null) {
86+
assert rootTag.getParent() != this;
87+
88+
// The root tag is already a child of another tag, so we need to remove it from its parent first.
89+
@SuppressWarnings("unchecked")
90+
var oldParent = (NBTParent<Tag>) rootTag.getParent();
91+
oldParent.remove(rootTag);
92+
}
93+
94+
Access.TAG.setParent(rootTag, this, 0);
95+
}
96+
7697
this.rootTag = rootTag;
7798
}
7899

src/main/java/org/glavo/nbt/tag/Tag.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ public int getIndex() {
121121
}
122122

123123
/// If the tag is a child of a [parent][NBTParent], returns the parent; otherwise, returns `null`.
124-
public @Nullable NBTParent<?> getParent() {
124+
public @Nullable NBTParent<? extends Tag> getParent() {
125125
return parent;
126126
}
127127

0 commit comments

Comments
 (0)