Skip to content

Commit 58734bf

Browse files
committed
Add NBT tag byte size calculation API
1 parent 4bb7204 commit 58734bf

8 files changed

Lines changed: 203 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
- New API `NBTCodec#writeRegion(Path, ChunkRegion)` and `NBTCodec#writeRegion(Path, ChunkRegion, ExternalChunkAccessor)`
66
for writing chunk regions to files.
7+
- New API `NBTCodec#byteSize(Tag)` and `NBTCodec#contentByteSize(Tag)` for calculating the encoded byte size of NBT
8+
tags.
9+
- New API `ArrayTag#getElementType()` for getting the element type of array tags.
710

811
## 0.1.0 (2026-03-16)
912

‎src/main/java/org/glavo/nbt/internal/TextUtils.java‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,53 @@ public static boolean startsWithIgnoreCase(CharSequence cs, int beginIndex, int
5050
return true;
5151
}
5252

53+
public static long mutf8Length(String value) {
54+
long length = 0L;
55+
for (int i = 0; i < value.length(); i++) {
56+
char ch = value.charAt(i);
57+
if (ch >= 0x800) {
58+
length += 3L;
59+
} else if (ch >= 0x80 || ch == 0) {
60+
length += 2;
61+
} else {
62+
length += 1;
63+
}
64+
}
65+
return length;
66+
}
67+
68+
public static long utf8Length(String value) {
69+
long length = 0L;
70+
71+
for (int i = 0; i < value.length(); i++) {
72+
char c = value.charAt(i);
73+
if (c < 0x80) {
74+
length += 1L;
75+
} else if (c < 0x800) {
76+
length += 2L;
77+
} else if (Character.isSurrogate(c)) {
78+
int uc = -1;
79+
char c2;
80+
if (Character.isHighSurrogate(c)
81+
&& i < value.length() - 1
82+
&& Character.isLowSurrogate(c2 = value.charAt(i + 1))) {
83+
uc = Character.toCodePoint(c, c2);
84+
}
85+
if (uc < 0) {
86+
length += 1L;
87+
} else {
88+
length += 4L;
89+
// skip the second surrogate
90+
i++;
91+
}
92+
} else {
93+
length += 3L;
94+
}
95+
}
96+
97+
return length;
98+
}
99+
53100
private TextUtils() {
54101
}
55102
}

‎src/main/java/org/glavo/nbt/io/NBTCodec.java‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,14 @@
1616
package org.glavo.nbt.io;
1717

1818
import org.glavo.nbt.chunk.ChunkRegion;
19+
import org.glavo.nbt.internal.TextUtils;
1920
import org.glavo.nbt.internal.input.InputSource;
2021
import org.glavo.nbt.internal.input.NBTInput;
2122
import org.glavo.nbt.internal.input.RawDataReader;
2223
import org.glavo.nbt.internal.output.NBTOutput;
2324
import org.glavo.nbt.internal.output.OutputTarget;
2425
import org.glavo.nbt.internal.output.RawDataWriter;
25-
import org.glavo.nbt.tag.Tag;
26-
import org.glavo.nbt.tag.TagType;
26+
import org.glavo.nbt.tag.*;
2727
import org.jetbrains.annotations.Contract;
2828
import org.jetbrains.annotations.Nullable;
2929

@@ -201,6 +201,82 @@ public NBTCodec withExternalChunkAccessorFactory(Function<Path, ExternalChunkAcc
201201
return factory == this.externalChunkAccessorFactory ? this : new NBTCodec(edition, factory);
202202
}
203203

204+
/// Returns the encoded byte size of the content of the simple value tag.
205+
private static long simpleValueContentByteSize(TagType<?> type) {
206+
if (type == TagType.BYTE) {
207+
return 1;
208+
} else if (type == TagType.SHORT) {
209+
return 2;
210+
} else if (type == TagType.INT) {
211+
return 4;
212+
} else if (type == TagType.LONG) {
213+
return 8;
214+
} else if (type == TagType.FLOAT) {
215+
return 4;
216+
} else if (type == TagType.DOUBLE) {
217+
return 8;
218+
} else {
219+
return -1L;
220+
}
221+
}
222+
223+
private long stringByteSize(String value) {
224+
return 2L + (edition == MinecraftEdition.JAVA_EDITION
225+
? TextUtils.mutf8Length(value)
226+
: TextUtils.utf8Length(value));
227+
}
228+
229+
/// Returns the encoded byte size of the content of the tag.
230+
///
231+
/// The size excludes the tag type and name.
232+
public long contentByteSize(Tag tag) {
233+
if (tag instanceof ValueTag<?> valueTag) {
234+
long size = simpleValueContentByteSize(valueTag.getType());
235+
if (size >= 0) {
236+
return size;
237+
} else if (tag instanceof StringTag stringTag) {
238+
return stringByteSize(stringTag.getValue());
239+
} else {
240+
throw new IllegalArgumentException("Unsupported tag: " + tag);
241+
}
242+
} else if (tag instanceof ListTag<?> listTag) {
243+
long size = 1 + 4; // element type + length
244+
245+
TagType<?> elementType = listTag.getElementType();
246+
if (elementType == null) {
247+
assert listTag.isEmpty() : "Non-empty list with element type END";
248+
return size;
249+
}
250+
251+
long elementSize = simpleValueContentByteSize(elementType);
252+
if (elementSize >= 0) {
253+
return size + elementSize * listTag.size();
254+
} else {
255+
for (Tag subTag : listTag) {
256+
size += contentByteSize(subTag);
257+
}
258+
return size;
259+
}
260+
} else if (tag instanceof CompoundTag compoundTag) {
261+
long size = 0L;
262+
for (Tag value : compoundTag) {
263+
size += byteSize(value);
264+
}
265+
return size + 1L;
266+
} else if (tag instanceof ArrayTag<?, ?, ?, ?> arrayTag) {
267+
long elementSize = simpleValueContentByteSize(arrayTag.getElementType());
268+
assert elementSize >= 0 : "Unsupported array element type: " + arrayTag.getElementType();
269+
return 4L + elementSize * arrayTag.size();
270+
} else {
271+
throw new IllegalArgumentException("Unsupported tag: " + tag);
272+
}
273+
}
274+
275+
/// Returns the encoded byte size of the tag.
276+
public long byteSize(Tag tag) {
277+
return 1L + stringByteSize(tag.getName()) + contentByteSize(tag);
278+
}
279+
204280
private Tag check(@Nullable Tag tag) throws IOException {
205281
if (tag == null) {
206282
throw new IOException("Unexpected TAG_END");

‎src/main/java/org/glavo/nbt/tag/ArrayTag.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ final void preUpdateSubTagName(Tag tag, String oldName, String newName) throws I
8787
@Contract(pure = true)
8888
public abstract TagType<? extends ArrayTag<E, T, A, B>> getType();
8989

90+
/// Returns the type of the elements in this array.
91+
@Contract(pure = true)
92+
public abstract TagType<T> getElementType();
93+
9094
@Override
9195
@Contract(value = "_ -> this", mutates = "this")
9296
public ArrayTag<E, T, A, B> setName(String name) throws IllegalArgumentException {

‎src/main/java/org/glavo/nbt/tag/ByteArrayTag.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ public TagType<ByteArrayTag> getType() {
5555
return TagType.BYTE_ARRAY;
5656
}
5757

58+
@Override
59+
@Contract(pure = true)
60+
public TagType<ByteTag> getElementType() {
61+
return TagType.BYTE;
62+
}
63+
5864
@Override
5965
@Contract(value = "_ -> this", mutates = "this")
6066
public ByteArrayTag setName(String name) throws IllegalArgumentException {

‎src/main/java/org/glavo/nbt/tag/IntArrayTag.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ public TagType<IntArrayTag> getType() {
6363
return TagType.INT_ARRAY;
6464
}
6565

66+
@Override
67+
@Contract(pure = true)
68+
public TagType<IntTag> getElementType() {
69+
return TagType.INT;
70+
}
71+
6672
@Override
6773
@Contract(value = "_ -> this", mutates = "this")
6874
public IntArrayTag setName(String name) throws IllegalArgumentException {

‎src/main/java/org/glavo/nbt/tag/LongArrayTag.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ public TagType<LongArrayTag> getType() {
5959
return TagType.LONG_ARRAY;
6060
}
6161

62+
@Override
63+
@Contract(pure = true)
64+
public TagType<LongTag> getElementType() {
65+
return TagType.LONG;
66+
}
67+
6268
@Override
6369
@Contract(value = "_ -> this", mutates = "this")
6470
public LongArrayTag setName(String name) throws IllegalArgumentException {

‎src/test/java/org/glavo/nbt/io/WriteTagTest.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ default void assertTagEquals(
4444
edition() == MinecraftEdition.BEDROCK_EDITION));
4545
}
4646

47+
default void assertByteSize(Tag tag) throws IOException {
48+
assertEquals(toByteArray(tag).length, NBTCodec.of(edition()).byteSize(tag));
49+
}
50+
4751
record OutputStream(MinecraftEdition edition) implements Validator {
4852
@Override
4953
public byte[] toByteArray(Tag tag) throws IOException {
@@ -160,4 +164,53 @@ void testWriteModifiedUTF8String(Validator validator) throws IOException {
160164
var actual = new StringTag(value).setName("Meow");
161165
validator.assertTagEquals(expected, actual);
162166
}
167+
168+
@ParameterizedTest
169+
@MethodSource("validators")
170+
void testByteSize(Validator validator) throws IOException {
171+
validator.assertByteSize(new ByteTag());
172+
validator.assertByteSize(new ByteTag((byte) 42));
173+
validator.assertByteSize(new ByteTag((byte) 42).setName("Meow"));
174+
validator.assertByteSize(new ShortTag());
175+
validator.assertByteSize(new ShortTag((short) 42));
176+
validator.assertByteSize(new ShortTag((short) 42).setName("Meow"));
177+
validator.assertByteSize(new IntTag());
178+
validator.assertByteSize(new IntTag(42));
179+
validator.assertByteSize(new IntTag(42).setName("Meow"));
180+
validator.assertByteSize(new LongTag());
181+
validator.assertByteSize(new LongTag(42L));
182+
validator.assertByteSize(new LongTag(42L).setName("Meow"));
183+
validator.assertByteSize(new FloatTag());
184+
validator.assertByteSize(new FloatTag(42.0f));
185+
validator.assertByteSize(new FloatTag(42.0f).setName("Meow"));
186+
validator.assertByteSize(new DoubleTag());
187+
validator.assertByteSize(new DoubleTag(42.0));
188+
validator.assertByteSize(new DoubleTag(42.0).setName("Meow"));
189+
validator.assertByteSize(new StringTag());
190+
validator.assertByteSize(new StringTag("Meow"));
191+
validator.assertByteSize(new StringTag("Meow").setName("Meow"));
192+
validator.assertByteSize(new ByteArrayTag());
193+
validator.assertByteSize(new ByteArrayTag(new byte[]{1, 2, 3}));
194+
validator.assertByteSize(new ByteArrayTag(new byte[]{1, 2, 3}).setName("Meow"));
195+
validator.assertByteSize(new IntArrayTag());
196+
validator.assertByteSize(new IntArrayTag(new int[]{1, 2, 3}));
197+
validator.assertByteSize(new IntArrayTag(new int[]{1, 2, 3}).setName("Meow"));
198+
validator.assertByteSize(new LongArrayTag());
199+
validator.assertByteSize(new LongArrayTag(new long[]{1, 2, 3}));
200+
validator.assertByteSize(new LongArrayTag(new long[]{1, 2, 3}).setName("Meow"));
201+
validator.assertByteSize(new ListTag<>());
202+
validator.assertByteSize(new ListTag<>(TagType.INT));
203+
validator.assertByteSize(new ListTag<>(TagType.INT)
204+
.addTag(new IntTag(42))
205+
.addTag(new IntTag(43))
206+
.addTag(new IntTag(44)));
207+
validator.assertByteSize(new ListTag<>()
208+
.addAnyTag(new IntTag(42))
209+
.addAnyTag(new StringTag("Meow"))
210+
.addAnyTag(new LongArrayTag(new long[]{1, 2, 3})));
211+
validator.assertByteSize(new CompoundTag());
212+
validator.assertByteSize(new CompoundTag()
213+
.addByte("int", (byte) 42)
214+
.addString("string", "Meow"));
215+
}
163216
}

0 commit comments

Comments
 (0)