Shared change: codecs/compress/Deflate gains Deflate.peek(buf, off, len, n) (the first n inflated bytes of a gzip / zlib / raw stream, for sniffing gzip-wrapped NBT) through a backward-compatible prefix flag on Inflate.raw; gunzip's header parsing moved into a local helper both use. Co-Authored-By: Claude Opus 5.5 <[email protected]>
153 lines
7.8 KiB
Python
153 lines
7.8 KiB
Python
# codecs/text/Nbt + data/nbt + data/snbt fixtures: random NBT trees (every tag type, nested lists / compounds, long
|
|
# extremes, BMP strings) written by Python's nbtlib (through nix) in Java big-endian and Bedrock little-endian, raw /
|
|
# gzip / zlib / with the Bedrock level.dat header, with nbtlib's SNBT text (indented and compact) and a canonical
|
|
# dump of the typed values; plus Bedrock network (varint) NBT from a small encoder here (nbtlib has none).
|
|
# tests/gen/nbt.luau { cases = { { name, raw, little, gzip, zlib, header, canon, snbt, compact, root } },
|
|
# net = { { data, canon } } }
|
|
# canon: b<n> s<n> i<n> l<n> f<hex f32 BE> d<hex f64 BE> S<len>:<utf8> B<hex> I[a,b] L[a,b]
|
|
# [<elemtype>|a,b] {<len>:<key>=<v>;...} (tests/codecs/nbt.luau computes the same text)
|
|
|
|
BODY = r'''
|
|
import nbtlib, pickle, random, struct, sys, io, gzip, zlib
|
|
from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray
|
|
import numpy as np
|
|
rng = random.Random(7)
|
|
NAMES = {"Byte": "byte", "Short": "short", "Int": "int", "Long": "long", "Float": "float", "Double": "double",
|
|
"ByteArray": "byteArray", "String": "string", "List": "list", "Compound": "compound", "IntArray": "intArray",
|
|
"LongArray": "longArray", "End": "end"}
|
|
ALPH = "abcXYZ019_-.+ :\"'\\\n\t{}[],;é中ü"
|
|
def rstr(n=None):
|
|
n = rng.choice([0, 1, 4, 12, 40]) if n is None else n
|
|
return "".join(rng.choice(ALPH) for _ in range(n))
|
|
def rkey():
|
|
return rng.choice(["", "a", "Name", "x y", "id", "Data", rstr(rng.randrange(1, 8))])
|
|
def scalar(kind):
|
|
if kind == "byte": return Byte(rng.choice([-128, -1, 0, 1, 127, rng.randrange(-128, 128)]))
|
|
if kind == "short": return Short(rng.choice([-32768, 32767, rng.randrange(-32768, 32768)]))
|
|
if kind == "int": return Int(rng.choice([-2**31, 2**31 - 1, 0, rng.randrange(-2**31, 2**31)]))
|
|
if kind == "long": return Long(rng.choice([-2**63, 2**63 - 1, 2**53, -2**53 - 1, 1, rng.randrange(-2**63, 2**63), rng.randrange(-2**40, 2**40)]))
|
|
if kind == "float": return Float(struct.unpack(">f", struct.pack(">f", rng.choice([0.0, -0.0, 1.5, 0.1, 3.4e38, 1e-40, rng.uniform(-1e6, 1e6)])))[0])
|
|
if kind == "double": return Double(rng.choice([0.0, 1.0, -2.5, 0.1, 1e300, 5e-324, 1e15, 1e16, 123456789.123, rng.uniform(-1e9, 1e9)]))
|
|
if kind == "string": return String(rstr())
|
|
if kind == "byteArray": return ByteArray([rng.randrange(-128, 128) for _ in range(rng.choice([0, 1, 5, 300]))])
|
|
if kind == "intArray": return IntArray([rng.randrange(-2**31, 2**31) for _ in range(rng.choice([0, 1, 4, 50]))])
|
|
if kind == "longArray": return LongArray([rng.choice([-2**63, 2**63 - 1, rng.randrange(-2**63, 2**63), rng.randrange(-100, 100)]) for _ in range(rng.choice([0, 1, 3, 40]))])
|
|
KINDS = ["byte", "short", "int", "long", "float", "double", "string", "byteArray", "intArray", "longArray"]
|
|
CLS = {"byte": Byte, "short": Short, "int": Int, "long": Long, "float": Float, "double": Double, "string": String,
|
|
"byteArray": ByteArray, "intArray": IntArray, "longArray": LongArray}
|
|
def value(d):
|
|
r = rng.random()
|
|
if d >= 4 or r < 0.55:
|
|
return scalar(rng.choice(KINDS))
|
|
if r < 0.8:
|
|
k = rng.choice(KINDS + ["compound", "list"])
|
|
n = rng.choice([0, 1, 3, 8])
|
|
if k == "compound":
|
|
return List[Compound]([compound(d + 1) for _ in range(n)])
|
|
if k == "list":
|
|
return List[List]([List[Int]([Int(i) for i in range(rng.randrange(3))]) for _ in range(n)])
|
|
return List[CLS[k]]([scalar(k) for _ in range(n)])
|
|
return compound(d + 1)
|
|
def compound(d):
|
|
c = Compound()
|
|
for _ in range(rng.choice([0, 1, 3, 6, 10])):
|
|
c[rkey()] = value(d)
|
|
return c
|
|
def canon(t):
|
|
n = type(t).__name__
|
|
if n.startswith("List"): n = "List"
|
|
if n == "Byte": return "b%d" % int(t)
|
|
if n == "Short": return "s%d" % int(t)
|
|
if n == "Int": return "i%d" % int(t)
|
|
if n == "Long": return "l%d" % int(t)
|
|
if n == "Float": return "f" + struct.pack(">f", float(t)).hex()
|
|
if n == "Double": return "d" + struct.pack(">d", float(t)).hex()
|
|
if n == "String":
|
|
b = str(t).encode("utf-8")
|
|
return "S%d:%s" % (len(b), str(t))
|
|
if n == "ByteArray": return "B" + np.asarray(t, dtype=np.int8).tobytes().hex()
|
|
if n == "IntArray": return "I[" + ",".join(str(int(x)) for x in t) + "]"
|
|
if n == "LongArray": return "L[" + ",".join(str(int(x)) for x in t) + "]"
|
|
if n == "List":
|
|
return "[" + NAMES[t.subtype.__name__] + "|" + ",".join(canon(x) for x in t) + "]"
|
|
if n in ("Compound", "File"):
|
|
return "{" + ";".join("%d:%s=%s" % (len(k.encode()), k, canon(v)) for k, v in t.items()) + "}"
|
|
raise TypeError(n)
|
|
def raw(root, name, order):
|
|
f = io.BytesIO()
|
|
f.write(b"\x0a")
|
|
nbtlib.tag.write_string(name, f, order)
|
|
root.write(f, byteorder=order)
|
|
return f.getvalue()
|
|
cases = []
|
|
for i in range(60):
|
|
root = compound(0)
|
|
if i == 0:
|
|
root = Compound()
|
|
name = rng.choice(["", "", "Schematic", "root", "é"])
|
|
big, little = raw(root, name, "big"), raw(root, name, "little")
|
|
# nbtlib's own file loader must read back what we hand it (a sanity check of the writer here)
|
|
back = nbtlib.File.parse(io.BytesIO(big))
|
|
assert canon(back) == canon(root)
|
|
header = struct.pack("<II", 9 + i % 3, len(little)) + little
|
|
cases.append({
|
|
"name": "tree%d" % i, "raw": big, "little": little, "gzip": gzip.compress(big, mtime=0),
|
|
"zlib": zlib.compress(big), "header": header, "version": 9 + i % 3, "root": name, "canon": canon(root),
|
|
"snbt": nbtlib.serialize_tag(root), "compact": nbtlib.serialize_tag(root, compact=True),
|
|
})
|
|
# Bedrock network NBT: an encoder from the wiki.vg description (zigzag varints for int / long / lengths)
|
|
def uvar(n):
|
|
out = bytearray()
|
|
while True:
|
|
b = n & 0x7f
|
|
n >>= 7
|
|
if n: out.append(b | 0x80)
|
|
else:
|
|
out.append(b); return bytes(out)
|
|
def zz32(v): return uvar(((v << 1) ^ (v >> 31)) & 0xffffffff)
|
|
def zz64(v): return uvar(((v << 1) ^ (v >> 63)) & 0xffffffffffffffff)
|
|
def nstr(s):
|
|
b = s.encode(); return uvar(len(b)) + b
|
|
IDS = {"end": 0, "byte": 1, "short": 2, "int": 3, "long": 4, "float": 5, "double": 6, "byteArray": 7, "string": 8,
|
|
"list": 9, "compound": 10, "intArray": 11, "longArray": 12}
|
|
def kind(t):
|
|
n = type(t).__name__
|
|
if n.startswith("List"): n = "List"
|
|
return NAMES[n]
|
|
def net(t):
|
|
k = kind(t)
|
|
if k == "byte": return struct.pack("<b", int(t))
|
|
if k == "short": return struct.pack("<h", int(t))
|
|
if k == "int": return zz32(int(t))
|
|
if k == "long": return zz64(int(t))
|
|
if k == "float": return struct.pack("<f", float(t))
|
|
if k == "double": return struct.pack("<d", float(t))
|
|
if k == "string": return nstr(str(t))
|
|
if k == "byteArray": return zz32(len(t)) + np.asarray(t, dtype=np.int8).tobytes()
|
|
if k == "intArray": return zz32(len(t)) + b"".join(zz32(int(x)) for x in t)
|
|
if k == "longArray": return zz32(len(t)) + b"".join(zz64(int(x)) for x in t)
|
|
if k == "list": return bytes([IDS[NAMES[t.subtype.__name__]]]) + zz32(len(t)) + b"".join(net(x) for x in t)
|
|
if k == "compound":
|
|
return b"".join(bytes([IDS[kind(v)]]) + nstr(key) + net(v) for key, v in t.items()) + b"\x00"
|
|
nets = []
|
|
for i in range(20):
|
|
root = compound(0)
|
|
nets.append({"data": b"\x0a" + nstr("") + net(root), "canon": canon(root)})
|
|
sys.stdout.buffer.write(pickle.dumps({"cases": cases, "net": nets}, protocol=4))
|
|
'''
|
|
|
|
|
|
def run(ctx, packages, body):
|
|
"""ctx.python with the script's stderr in the error"""
|
|
import subprocess
|
|
try:
|
|
return ctx.python(packages, body)
|
|
except subprocess.CalledProcessError as e:
|
|
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
|
|
|
|
|
|
def generate(ctx):
|
|
import pickle
|
|
out = pickle.loads(run(ctx, ["nbtlib", "numpy"], BODY))
|
|
ctx.emit("nbt", out)
|