Skip to content

Commit

Permalink
throw exception when tryng to add tag of different type to non-empty …
Browse files Browse the repository at this point in the history
…untyped listtag
  • Loading branch information
Querz committed Sep 30, 2019
1 parent b80ee75 commit b56ad64
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/main/java/net/querz/nbt/ListTag.java
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,16 @@ public void add(T t) {

public void add(int index, T t) {
Objects.requireNonNull(t);
getValue().add(index, t);
if (typeClass == null || typeClass == EndTag.class) {
typeClass = t.getClass();
} else if (typeClass != t.getClass()) {
throw new ClassCastException(
String.format("cannot add %s to ListTag<%s>",
t.getClass().getSimpleName(),
typeClass.getSimpleName()));
}
getValue().add(index, t);

}

public void addAll(Collection<T> t) {
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/net/querz/nbt/ListTagTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,18 @@ public void testCasting() {
assertEquals(lb, lg);
//only allow casting once from untyped list to typed list
assertThrowsRuntimeException(lg::asShortTagList, ClassCastException.class);

//adding generic Tags to an empty list
@SuppressWarnings("unchecked")
ListTag<Tag<?>> u = (ListTag<Tag<?>>) TagFactory.fromID(9);
assertEquals(EndTag.class, u.getTypeClass());
assertThrowsNoRuntimeException(() -> u.add(new StringTag()));
assertEquals(StringTag.class, u.getTypeClass());
assertThrowsRuntimeException(() -> u.add(new ByteTag()), ClassCastException.class);
assertThrowsNoRuntimeException(() -> u.add(new StringTag()));
assertEquals(2, u.size());


}

public void testCompareTo() {
Expand Down

0 comments on commit b56ad64

Please sign in to comment.