From 998177e5ab7f83d97ac9fb37f452e4a01d37f7b1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:12:46 -0500 Subject: [PATCH] ws-voxel: codecs/text/Nbt (NBT Java / Bedrock / network varint, SNBT parse + print, typed values), data/nbt, data/snbt 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. --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 24 + .../codecs/compress/Deflate/Inflate.luau | 14 +- src/Formats/codecs/compress/Deflate/init.luau | 90 ++- src/Formats/codecs/text/Nbt/Binary.luau | 698 ++++++++++++++++++ src/Formats/codecs/text/Nbt/Snbt.luau | 649 ++++++++++++++++ src/Formats/codecs/text/Nbt/Value.luau | 256 +++++++ src/Formats/codecs/text/Nbt/init.luau | 380 ++++++++++ src/Formats/data/nbt/init.luau | 60 ++ src/Formats/data/snbt/init.luau | 63 ++ tests/codecs/deflate.luau | 19 + tests/codecs/nbt.luau | 256 +++++++ tests/data/nbt.luau | 60 ++ tests/data/snbt.luau | 47 ++ tools/fixtures/nbt.py | 152 ++++ 15 files changed, 2745 insertions(+), 26 deletions(-) create mode 100644 src/Formats/codecs/text/Nbt/Binary.luau create mode 100644 src/Formats/codecs/text/Nbt/Snbt.luau create mode 100644 src/Formats/codecs/text/Nbt/Value.luau create mode 100644 src/Formats/codecs/text/Nbt/init.luau create mode 100644 src/Formats/data/nbt/init.luau create mode 100644 src/Formats/data/snbt/init.luau create mode 100644 tests/codecs/nbt.luau create mode 100644 tests/data/nbt.luau create mode 100644 tests/data/snbt.luau create mode 100644 tools/fixtures/nbt.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..51b3d3b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -62,7 +62,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | | data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | +| data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | binary: true, ordered: true, typed: true | `tests/data/nbt.luau` | | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | +| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | @@ -128,6 +130,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. + - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..b7c814e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -698,6 +698,18 @@ local list: { Entry } = { return require("@formats/data/msgpack") end, }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/nbt") + end, + }, { name = "plist", category = "data", @@ -710,6 +722,18 @@ local list: { Entry } = { return require("@formats/data/plist") end, }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/snbt") + end, + }, { name = "toml", category = "data", diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau index 449e1db..456464f 100644 --- a/src/Formats/codecs/compress/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -62,9 +62,10 @@ local function grow(out: buffer, op: number, need: number): (buffer, number) end -- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. +-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and +-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). -- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?) local out = bcreate(cap) local op = 0 local pos = start @@ -123,6 +124,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + n > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + n) @@ -295,6 +299,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex if sym < 256 then if op >= cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + 1) @@ -388,6 +395,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + len > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + len) diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index 37a529b..fd25c71 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -9,6 +9,7 @@ -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 -- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members -- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw -- -- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). local Err = require("@formats/core/Err") @@ -101,6 +102,36 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end +-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err +local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + -- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is -- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) @@ -127,30 +158,9 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): if buffer.readu8(b, p + 2) ~= 8 then return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) end - local flg = buffer.readu8(b, p + 3) - if flg >= 0x20 then - return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) - end - local q = p + 10 - if bit32.band(flg, 4) ~= 0 then -- FEXTRA - if q + 2 > e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) - end - q += 2 + buffer.readu16(b, q) - end - for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated - if bit32.band(flg, bit) ~= 0 then - while q < e and buffer.readu8(b, q) ~= 0 do - q += 1 - end - q += 1 - end - end - if bit32.band(flg, 2) ~= 0 then -- FHCRC - q += 2 - end - if q >= e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr end local out, consumed = Deflate.inflate(b, q, e - q) if not out then @@ -191,6 +201,38 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): return res, nil end +-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to +-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating +-- the rest or checking checksums: for sniffing compressed files cheaply. +function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q :: number, e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + export type CompressOptions = { level: number?, -- 0 (stored) .. 9 (best); default 6 } diff --git a/src/Formats/codecs/text/Nbt/Binary.luau b/src/Formats/codecs/text/Nbt/Binary.luau new file mode 100644 index 0000000..0ecbfd2 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Binary.luau @@ -0,0 +1,698 @@ +--!strict +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from +-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / +-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against +-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Binary = {} + +export type Options = { + endian: ("big" | "little")?, -- default "big" (Java) + varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" + nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + name: string?, -- write: the root name (default "") +} + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } + +-- ------------------------------------------------------------------------------------------------ modified UTF-8 +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) +local function fromModified(s: string): string + if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i += 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i += 6 + else + table.insert(out, string.char(c)) + i += 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s: string): string + if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i += 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) + i += 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +-- ------------------------------------------------------------------------------------------------ read +local function fail(s: State, msg: string): nil + if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s: State, n: number): boolean + if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s: State): number + if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p += 1 + return v +end + +local function varuint(s: State): number -- up to 32 bits (5 bytes) + local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + v += (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul *= 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s: State): number + if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return if v >= 32768 then v - 65536 else v +end + +local function u32raw(s: State): number + if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return if s.le then v else byteswap(v) +end + +local function i32(s: State): number + if s.net then + local n = varuint(s) + return if n % 2 == 0 then n // 2 else -(n + 1) // 2 + end + local v = u32raw(s) + return if v >= 0x80000000 then v - TWO32 else v +end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s: State): number + return i32(s) +end + +local function i64(s: State): (number, number) -- hi, lo + if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo += x % TWO32 + hi = (hi + x // TWO32) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh += 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = lo // 2 + (hi % 2) * 0x80000000 + hi = hi // 2 + if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s: State): number + local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s: State): number + local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s: State): string + local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p += n + return if s.java then fromModified(v) else v +end + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, newTag) +end + +-- the smallest encoded size of one element, to bound list lengths before allocating +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload: (State, number) -> any + +local function count(s: State, n: number, size: number): boolean + if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s: State, id: number): any + if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth -= 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p += 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p += n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then + return nil + end + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth -= 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, if s.net then 1 else 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, if s.net then 1 else 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p += n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at +function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s: State = { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = if o.nameless then "" else str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end + +-- ------------------------------------------------------------------------------------------------ write +type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } + +local function wvaruint(w: Bytes.Writer, v: number) + v %= TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v //= 128 + end + w:u8(v) +end + +local function wi32(ws: WState, v: number) + v %= TWO32 -- two's complement + if ws.net then + local sv = if v >= 0x80000000 then v - TWO32 else v + wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws: WState, v: number) + v %= 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws: WState, hi: number, lo: number) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = zl // 128 + (zh % 128) * 0x2000000 + zh //= 128 + end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws: WState, s: string): string? + local v = if ws.java then toModified(s) else s + if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) + local n = if type(v) == "boolean" then (if v then 1 else 0) else v + if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload: (WState, string, any) -> string? + +local function wlist(ws: WState, v: { any }): string? + local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt :: string]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt :: string, x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws: WState, t: string, v: any): string? + local w = ws.w + local x = if Value.isTag(v) then v.value else v + if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct :: string]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct :: string, c) + if e then + return e + end + end + w:u8(0) + ws.depth -= 1 + elseif t == "list" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth -= 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo :: number) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = buffer.len(x) // 8 + wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +-- write(value, opts?) -> buffer | nil, message +function Binary.write(v: any, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t :: string]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t :: string, v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary diff --git a/src/Formats/codecs/text/Nbt/Snbt.luau b/src/Formats/codecs/text/Nbt/Snbt.luau new file mode 100644 index 0000000..7dcc0f3 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Snbt.luau @@ -0,0 +1,649 @@ +--!strict +-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the +-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] +-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted +-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex +-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing +-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's +-- compact form (or indented); floats print as the shortest text that reads back to the same value. +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Snbt = {} + +export type ParseOptions = { maxDepth: number? } +export type PrintOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes +} + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, Value.TagMeta) +end + +-- ------------------------------------------------------------------------------------------------ parse +type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } + +local function fail(p: P, msg: string): nil + if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p: P) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e :: number) + 1 +end + +local function isUnquoted(c: number): boolean + return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p: P): string? + local q = sub(p.s, p.i, p.i) + p.i += 1 + local out = {} + while true do + local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 + local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = tonumber(hex, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +-- number text -> a value, or nil when it is not a number (then it is an unquoted string) +local INT_RANGE: { [string]: { number } } = { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t: string): any + local sign, body = string.match(t, "^([+-]?)(.+)$") + body = string.gsub(body :: string, "_", "") :: string + local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m :: string, string.lower(sfx :: string) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + -- the magnitude as (hi, lo) + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 + local x = lo * radix + d + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) + elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v -= r[3] + 1 + end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t: string): any + local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) + elseif low == "nanf" or low == "nand" then + return tag(if sfx == "f" then "float" else "double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant :: string, ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs :: string) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue: (P) -> any + +local function token(p: P): string + local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j += 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p: P): string? + ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p: P, kind: string): any + local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = if t ~= "" then number(t) else nil + local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x: any = if Value.isTag(v) then (v :: any).value else v + if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i += 1 + if c == "]" then + break + elseif c ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + else + p.i += 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in items do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p: P): any + ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i += 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k :: string] == nil then + table.insert(keys, k) + end + o[k :: string] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "}" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + break + end + end + end + p.depth -= 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e :: number) + 1 + local v = array(p, ARRAY[kind]) + p.depth -= 1 + return v + end + local items = {} + local lt: string? = nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "]" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + end + p.depth -= 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +-- parse(text, opts?) -> value | nil, message, position (1-based) +function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) + local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +-- ------------------------------------------------------------------------------------------------ print +local function shortest(v: number, single: boolean): string + if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = if single then 6 else 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = tonumber(s) :: number + if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s ..= ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s: string, q: string): string + local other = if q == '"' then "'" else '"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string + if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k: string, q: string): string + if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + +type Pr = { out: { string }, indent: string?, q: string, depth: number } + +local printValue: (Pr, any, number) -> string? + +local function scalar(v: any, q: string): string? + local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return if v then "1b" else "0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return (if type(x) == "string" then x else string.format("%d", x)) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr: Pr, head: string, items: { string }, close: string) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) + end +end + +local function sub1(pr: Pr, v: any): (string?, string?) + local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr: Pr, v: any, depth: number): string? + if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = table.create(buffer.len(v)) :: { string } + for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in v.value do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in Value.longs(v) do + items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items: { string } = {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x :: string + end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) + end + seq(pr, "{", items, "}") + end + return nil +end + +-- print(value, opts?) -> text | nil, message +function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) + local o: PrintOptions = opts or {} + local ind = o.indent + local pr: Pr = { + out = {}, + indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, + q = if o.quote == "'" then "'" else '"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v: any): string + return Snbt.print(v) or "?" +end + +return Snbt diff --git a/src/Formats/codecs/text/Nbt/Value.luau b/src/Formats/codecs/text/Nbt/Value.luau new file mode 100644 index 0000000..2c0bb17 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Value.luau @@ -0,0 +1,256 @@ +--!strict +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- Plain Luau values with typed numbers, so a decode / encode round trip is exact: +-- int -> number string -> string byteArray -> buffer +-- compound -> Types.object (key order kept) list -> array (element type in Value.listType) +-- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a +-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal +-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. +-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as +-- byte 1 / 0; a plain table with string keys as a compound. +local Types = require("@formats/Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} :: { [number]: string } +Value.IDS = {} :: { [string]: number } +for id = 0, 12 do + Value.IDS[Value.NAMES[id]] = id +end + +export type Tag = { type: string, value: any } + +local TagMeta: { [string]: any } = {} +Value.TagMeta = TagMeta +-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) +Value.print = function(v: any): string + return tostring(v.value) +end +TagMeta.__tostring = function(v: any): string + return Value.print(v) +end +TagMeta.__eq = function(a: any, b: any): boolean + if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any + +-- ------------------------------------------------------------------------------------------------ 64-bit integers +local TWO32 = 4294967296 + +-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the +-- two's complement int64) +function Value.fromHiLo(hi: number, lo: number): number | string + local s = if hi >= 0x80000000 then hi - TWO32 else hi + if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = hi // 10000 + local x = (hi - qh * 10000) * TWO32 + lo + local ql = x // 10000 + local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) + end + return (if neg then "-" else "") .. table.concat(parts) +end + +-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text +function Value.toHiLo(v: any): (number?, number?) + if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = v // TWO32 + local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +local function tag(name: string, v: any): Tag + return setmetatable({ type = name, value = v }, TagMeta) :: any +end +function Value.byte(n: number): Tag + return tag("byte", n) +end +function Value.short(n: number): Tag + return tag("short", n) +end +function Value.int(n: number): number + return n +end +-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) +function Value.long(v: number | string): Tag + if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo :: number) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +-- float(n) -> a float tag holding n rounded to single precision +function Value.float(n: number): Tag + buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n: number): Tag + return tag("double", n) +end +function Value.intArray(t: { number }?): Tag + return tag("intArray", t or {}) +end +-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) +function Value.longArray(t: { any } | buffer | nil): Tag + if type(t) == "buffer" then + return tag("longArray", t) + end + local list: { any } = (t or {}) :: any + local b = buffer.create(#list * 8) + for i, x in list do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +-- longs(longArray) -> { number | string }: the elements as long values +function Value.longs(a: Tag): { number | string } + local b: buffer = a.value + local out = table.create(buffer.len(b) // 8) :: { number | string } + for i = 0, buffer.len(b) // 8 - 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) +function Value.list(name: string, items: { any }?): { any } + local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } + return Types.object(t, keys) +end +-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) +function Value.listType(t: any): string? + return listTypes[t] +end +function Value.setListType(t: any, name: string) + listTypes[t] = name +end +function Value.isTag(v: any): boolean + return type(v) == "table" and getmetatable(v) == TagMeta +end + +-- typeOf(v) -> the tag name v writes as, or nil + why +function Value.typeOf(v: any): (string?, string?) + local tv = type(v) + if tv == "number" then + return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) +function Value.number(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value diff --git a/src/Formats/codecs/text/Nbt/init.luau b/src/Formats/codecs/text/Nbt/init.luau new file mode 100644 index 0000000..3245410 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/init.luau @@ -0,0 +1,380 @@ +--!strict +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, +-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat +-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ +-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers +-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order +-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. +-- +-- local Nbt = require("@formats/codecs/text/Nbt") +-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored +-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value +-- v.Data.Difficulty = Nbt.byte(2) +-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts +-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} +-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') +-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag +-- +-- Never throws: bad data and bad values return nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Value = require("@formats/codecs/text/Nbt/Value") +local Binary = require("@formats/codecs/text/Nbt/Binary") +local Snbt = require("@formats/codecs/text/Nbt/Snbt") + +local Nbt = {} + +export type Tag = Value.Tag +export type Info = { + name: string, -- the root tag's name + endian: "big" | "little", + varint: boolean?, -- Bedrock network NBT + compression: "gzip" | "zlib" | "none", + header: number?, -- Bedrock level.dat: the storage version from the 8-byte header +} +export type DecodeOptions = { + endian: ("big" | "little")?, -- default: detected (Java big-endian first) + varint: boolean?, -- Bedrock network NBT + nameless: boolean?, -- no root name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) +} +export type EncodeOptions = { + endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + varint: boolean?, + nameless: boolean?, + name: string?, -- the root name (default: Nbt.info(value).name, else "") + compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian + header: number?, -- write the Bedrock level.dat header with this version + level: number?, -- deflate level 0..9 (default 6) +} + +Nbt.TAG = Value.IDS -- name -> id +Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any + +-- info(value) -> how a decoded root was stored (nil for values not from decode) +function Nbt.info(v: any): Info? + return if type(v) == "table" then infos[v] else nil +end +-- setInfo(value, info): what encode uses as defaults +function Nbt.setInfo(v: any, info: Info) + if type(v) == "table" then + infos[v] = info + end +end + +-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag +function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) + local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts :: any) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag +function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local out, e = Binary.write(v, opts :: any) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic +function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) + local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = if l >= 2 then buffer.readu8(b, o) else 0 + local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 + local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + +export type Peek = { + compression: string, -- "gzip" | "zlib" | "none" + endian: "big" | "little", + header: boolean, -- a Bedrock level.dat header + rootType: string, -- "compound" (or "list") + name: string, -- the root name + firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + firstName: string?, + head: buffer, -- the first (up to 1024) uncompressed bytes +} + +local function plausibleName(b: buffer, p: number, n: number): string? + if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a +-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. +function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? + local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head: buffer + local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, if c0 == 0x1f then "gzip" else "zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p: number, endian: string, header: boolean): Peek? + if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q: number): number + local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return if endian == "big" then a * 256 + b else b * 256 + a + end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" -- an empty root compound + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java +-- or Bedrock) +function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) + local o: DecodeOptions = opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data: buffer, start: number, stop: number = b, s, e :: number + local function try(endian: string, from: number, varint: boolean?): (any, any, number?) + return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header: number? = nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info: Info = { + name = name, + endian = if o.varint or o.endian == "little" then "little" else "big", + varint = if o.varint then true else nil, + compression = comp :: any, + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file +function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = if o.varint ~= nil then o.varint else (info and info.varint) + local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = if o.header ~= nil then o.header else (info and info.header) + if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +-- parse(text, opts?) -> value | nil, Err: SNBT +function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) + local s = if type(text) == "buffer" then buffer.tostring(text) else text + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) +function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) + local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) +function Nbt.get(v: any, path: string): any + local cur = v + for part in string.gmatch(path, "[^%.]+") do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do + local i = tonumber(idx) :: number + if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt diff --git a/src/Formats/data/nbt/init.luau b/src/Formats/data/nbt/init.luau new file mode 100644 index 0000000..407aed8 --- /dev/null +++ b/src/Formats/data/nbt/init.luau @@ -0,0 +1,60 @@ +--!strict +-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and +-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and +-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / +-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression +-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. +-- Not supported: nothing in the format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +export type DecodeOptions = Nbt.DecodeOptions +export type EncodeOptions = Nbt.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function NbtFormat.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return if p.firstType and p.firstName then 0.6 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.Nbt = Nbt + +return NbtFormat diff --git a/src/Formats/data/snbt/init.luau b/src/Formats/data/snbt/init.luau new file mode 100644 index 0000000..a128f3e --- /dev/null +++ b/src/Formats/data/snbt/init.luau @@ -0,0 +1,63 @@ +--!strict +-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over +-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt +-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +export type DecodeOptions = { maxDepth: number? } +export type EncodeOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- '"' (default) or "'" +} + +-- ------------------------------------------------------------------------------------------------ sniff +function SnbtFormat.sniff(r: Bytes.Reader): number + -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat diff --git a/tests/codecs/deflate.luau b/tests/codecs/deflate.luau index d9ee80a..319dfdc 100644 --- a/tests/codecs/deflate.luau +++ b/tests/codecs/deflate.luau @@ -169,4 +169,23 @@ do end, samples, { mutations = 3, garbage = 300 }) end +-- peek: the first bytes of a gzip / zlib / raw stream without inflating the rest +do + local src = buffer.create(100000) + for i = 0, 99999 do + buffer.writeu8(src, i, (i * 7 + (i // 97)) % 251) + end + local want = buffer.readstring(src, 0, 1000) + for _, kind in { "gzip", "zlibCompress", "compress" } do + local z = assert((Deflate :: any)[kind](src)) :: buffer + local head = assert(Deflate.peek(z, nil, nil, 1000)) + t:check(buffer.len(head) <= 1000 and buffer.len(head) >= 1000 - 258, "peek " .. kind .. " size") + t:eq(buffer.tostring(head), string.sub(want, 1, buffer.len(head)), "peek " .. kind .. " bytes") + end + local small = assert(Deflate.peek(assert(Deflate.gzip(buffer.fromstring("hello"))), nil, nil, 1000)) + t:eq(buffer.tostring(small), "hello", "peek a short stream") + local _, e = Deflate.peek(buffer.fromstring("\31\139\8\0\0\0\0\0\0\3\255\255\255\255\255\255\255\255"), nil, nil, 10) + t:check(e ~= nil, "peek bad data") +end + t:done() diff --git a/tests/codecs/nbt.luau b/tests/codecs/nbt.luau new file mode 100644 index 0000000..ba602a3 --- /dev/null +++ b/tests/codecs/nbt.luau @@ -0,0 +1,256 @@ +-- codecs/text/Nbt tests: random trees written by Python's nbtlib (Java big-endian, Bedrock little-endian, gzip, zlib, +-- the level.dat header) decode to nbtlib's typed values (a canonical dump), re-encode to nbtlib's exact bytes in both +-- byte orders, nbtlib's SNBT (indented and compact) parses to the same values and our SNBT reads back exactly; +-- Bedrock network varint NBT; modified UTF-8; long extremes; SNBT grammar details; peek; errors; the fuzz pass. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local Nbt = require("@formats/codecs/text/Nbt") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("nbt") + +local function hexOf(b: buffer, o: number, n: number, rev: boolean): string + local parts = {} + for i = 0, n - 1 do + parts[i + 1] = string.format("%02x", buffer.readu8(b, if rev then o + n - 1 - i else o + i)) + end + return table.concat(parts) +end + +-- the canonical dump tools/fixtures/nbt.py writes +local function canon(v: any): string + local ty = Nbt.typeOf(v) + local x = if Nbt.isTag(v) then v.value else v + if ty == "byte" or ty == "short" or ty == "int" or ty == "long" then + local n = if type(x) == "boolean" then (if x then 1 else 0) else x + return string.sub(ty :: string, 1, 1) .. (if type(n) == "string" then n else string.format("%d", n)) + elseif ty == "float" then + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return "f" .. hexOf(b, 0, 4, true) + elseif ty == "double" then + local b = buffer.create(8) + buffer.writef64(b, 0, x) + return "d" .. hexOf(b, 0, 8, true) + elseif ty == "string" then + return "S" .. #x .. ":" .. x + elseif ty == "byteArray" then + return "B" .. hexOf(x, 0, buffer.len(x), false) + elseif ty == "intArray" then + local p = {} + for i, n in x do + p[i] = string.format("%d", n) + end + return "I[" .. table.concat(p, ",") .. "]" + elseif ty == "longArray" then + local p = {} + for i, n in Nbt.longs(v) do + p[i] = if type(n) == "string" then n else string.format("%d", n) + end + return "L[" .. table.concat(p, ",") .. "]" + elseif ty == "list" then + local p = {} + for i, e in v do + p[i] = canon(e) + end + return "[" .. (Nbt.listType(v) or "?") .. "|" .. table.concat(p, ",") .. "]" + end + local p = {} + for _, k in Types.keys(v) do + table.insert(p, #k .. ":" .. k .. "=" .. canon(v[k])) + end + return "{" .. table.concat(p, ";") .. "}" +end + +local function same(a: buffer, b: string): boolean + return buffer.tostring(a) == b +end + +-- 1. nbtlib trees +for _, c in Fx.cases do + local v, info = Nbt.decode(c.raw) + t:check(v ~= nil, c.name .. ": decode " .. tostring(info)) + t:eq(canon(v), c.canon, c.name .. ": value") + t:eq(info.name, c.root, c.name .. ": root name") + t:check(info.endian == "big" and info.compression == "none", c.name .. ": info") + local out = Nbt.encode(v) :: buffer + t:check(out and same(out, c.raw), c.name .. ": same bytes (big-endian)") + local le = Nbt.encode(v, { endian = "little" }) :: buffer + t:check(le and same(le, c.little), c.name .. ": same bytes (little-endian)") + for _, k in { "little", "gzip", "zlib", "header" } do + local w, wi = Nbt.decode(c[k]) + t:check(w ~= nil, c.name .. ": decode " .. k .. " " .. tostring(wi)) + t:eq(canon(w), c.canon, c.name .. ": " .. k .. " value") + if #c.raw > 4 then -- an empty compound with an empty name reads the same either way + t:eq(wi.endian, if k == "little" or k == "header" then "little" else "big", c.name .. ": " .. k .. " endian") + end + t:eq(wi.compression, if k == "gzip" or k == "zlib" then k else "none", c.name .. ": " .. k .. " compression") + -- written back the same way it was read + local again = Nbt.encode(w) :: buffer + local w2, wi2 = Nbt.decode(again) + t:eq(canon(w2), c.canon, c.name .. ": " .. k .. " round trip") + t:eq(wi2.compression, wi.compression, c.name .. ": " .. k .. " keeps compression") + t:eq(wi2.header, wi.header, c.name .. ": " .. k .. " keeps the header") + if k == "header" then + t:eq(wi.header, c.version, c.name .. ": header version") + t:check(same(again, c.header), c.name .. ": header same bytes") + end + end + -- SNBT: nbtlib's text parses to the same values (an empty list's type is not in the text); ours reads back + -- exactly (both forms) + local function untyped(s: string): string + return (string.gsub(s, "%[%a+|%]", "[|]")) + end + for _, k in { "snbt", "compact" } do + local s, e = Nbt.parse(c[k]) + t:check(s ~= nil, c.name .. ": parse " .. k .. " " .. tostring(e)) + t:eq(untyped(canon(s)), untyped(c.canon), c.name .. ": " .. k .. " value") + end + for _, o in { {}, { indent = 2 }, { quote = "'" } } do + local text = Nbt.print(v, o) :: string + local back, e = Nbt.parse(text) + t:check(back ~= nil, c.name .. ": our SNBT parses " .. tostring(e)) + t:eq(untyped(canon(back)), untyped(c.canon), c.name .. ": our SNBT round trip") + end +end + +-- 2. Bedrock network NBT +for i, c in Fx.net do + local v, info = Nbt.decode(c.data, { varint = true }) + t:check(v ~= nil, "net " .. i .. ": " .. tostring(info)) + t:eq(canon(v), c.canon, "net " .. i .. ": value") + t:check(same(Nbt.encode(v, { varint = true }) :: buffer, c.data), "net " .. i .. ": same bytes") +end + +-- 3. details +do + -- longs: exact past 2^53, both directions + for _, s in { "9223372036854775807", "-9223372036854775808", "9007199254740993", "-9007199254740993", "4294967296", "-1" } do + local hi, lo = Nbt.toHiLo(s) + t:check(hi ~= nil, "toHiLo " .. s) + t:eq(tostring(Nbt.fromHiLo(hi :: number, lo :: number)), s, "long text " .. s) + end + t:eq(Nbt.toHiLo("9223372036854775808"), nil, "long overflow") + t:eq(Nbt.long("12").value, 12, "small long text becomes a number") + -- modified UTF-8: NUL as C0 80 and U+1F600 as a surrogate pair in Java files, plain UTF-8 in Bedrock ones + local v = Nbt.compound({ s = "a\0b\u{1F600}" }, { "s" }) + local big = Nbt.write(v) :: buffer + t:check(string.find(buffer.tostring(big), "a\192\128b\237\160\189\237\184\128", 1, true) ~= nil, "modified UTF-8 out") + t:eq((Nbt.read(big)).s, "a\0b\u{1F600}", "modified UTF-8 in") + local little = Nbt.write(v, { endian = "little" }) :: buffer + t:check(string.find(buffer.tostring(little), "a\0b\u{1F600}", 1, true) ~= nil, "Bedrock strings are UTF-8") + -- lenient inputs: plain numbers, booleans, plain tables + local p = Nbt.read(Nbt.write({ a = 1.5, b = true, c = { 1, 2 }, d = {}, e = 2 ^ 40 }) :: buffer) + t:check(p.a.type == "double" and p.b.type == "byte" and p.b.value == 1, "plain number / boolean") + t:check(Nbt.listType(p.c) == "int" and Nbt.listType(p.d) == "end" and p.e.type == "double", "plain lists") + -- mixed lists are wrapped in compounds, as Minecraft 1.21.5 does + local m = Nbt.read(Nbt.write({ l = { 1, "x" } }) :: buffer) + t:check(Nbt.listType(m.l) == "compound" and m.l[1][""] == 1 and m.l[2][""] == "x", "heterogeneous list") + -- empty typed list keeps its type + local et = Nbt.read(Nbt.write({ l = Nbt.list("compound") }) :: buffer) + t:eq(Nbt.listType(et.l), "compound", "empty typed list") + -- tostring of tags is SNBT; == compares type and value + t:eq(tostring(Nbt.byte(3)), "3b", "tostring byte") + t:eq(tostring(Nbt.float(0.1)), "0.1f", "tostring float (shortest)") + t:check(Nbt.short(5) == Nbt.short(5) and Nbt.short(5) ~= Nbt.int(5) :: any, "tag equality") + -- get + local g = assert(Nbt.parse("{Data:{Pos:[1.0d,2.5d,3.0d],Inv:[{id:\"x\"}]}}")) + t:eq(Nbt.get(g, "Data.Pos[1]").value, 2.5, "get list element") + t:eq(Nbt.get(g, "Data.Inv[0].id"), "x", "get nested") + t:eq(Nbt.get(g, "Data.Missing.x"), nil, "get missing") +end + +-- 4. SNBT grammar +do + local cases: { { string } } = { + { "1b", "byte:1" }, { "-5S", "short:-5" }, { "7", "int:7" }, { "7i", "int:7" }, { "1_000", "int:1000" }, + { "123L", "long:123" }, { "0x1F", "int:31" }, { "0xFFub", "byte:-1" }, { "0x7Fsb", "byte:127" }, + { "0b101", "int:5" }, { "0b", "byte:0" }, { "200ub", "byte:-56" }, { "1.5", "double:1.5" }, { ".5f", "float:0.5" }, + { "2e3", "double:2000" }, { "3f", "float:3" }, { "4D", "double:4" }, { "true", "byte:1" }, { "false", "byte:0" }, + { "abc", "string:abc" }, { "1.2.3", "string:1.2.3" }, { "'it''", "" }, { "'a\\'b'", "string:a'b" }, + { '"\\u00e9\\x41\\n"', "string:\u{e9}A\n" }, { "-Infinityd", "double:-inf" }, + } + for _, c in cases do + local v = Nbt.parse(c[1]) + if c[2] == "" then + t:eq(v, nil, "snbt " .. c[1] .. " fails") + else + local ty = Nbt.typeOf(v) :: string + local x = Nbt.number(v) + local got = ty .. ":" .. (if ty == "string" then v elseif x == -math.huge then "-inf" else string.format("%.17g", x :: number)) + t:eq(got, c[2], "snbt " .. c[1]) + end + end + local a = assert(Nbt.parse("[B; 1b, -2b, 3]")) + t:check(typeof(a) == "buffer" and buffer.len(a) == 3 and buffer.readi8(a, 1) == -2, "byte array") + local ia = assert(Nbt.parse("[I;]")) + t:check(ia.type == "intArray" and #ia.value == 0, "empty int array") + local la = assert(Nbt.parse("[L; -9223372036854775808L, 5L]")) + t:eq(Nbt.longs(la)[1], "-9223372036854775808", "long array extreme") + local tc = assert(Nbt.parse("{a:1,b:[1,2,],}")) + t:check(tc.a == 1 and #tc.b == 2, "trailing commas") + t:eq(Nbt.print(assert(Nbt.parse('{"a b":1,c:"say \\"hi\\""}'))), "{\"a b\":1,c:'say \"hi\"'}", "quoting") + local _, e1 = Nbt.parse("{a:1") + t:check(e1 and e1.code == Err.CORRUPT, "unterminated compound") + local _, e2 = Nbt.parse("{a:300b}") + t:check(e2 and e2.code == Err.CORRUPT, "byte out of range") + local _, e3 = Nbt.parse(string.rep("[", 600) .. string.rep("]", 600)) + t:check(e3 and e3.code == Err.LIMIT, "depth limit") +end + +-- 5. peek +do + local c = Fx.cases[2] + for _, k in { "raw", "gzip", "zlib", "header" } do + local p = Nbt.peek(buffer.fromstring(c[k])) + t:check(p ~= nil and p.name == c.root and p.rootType == "compound", "peek " .. k) + end + t:eq(Nbt.peek(buffer.fromstring("hello world")), nil, "peek text") +end + +-- 6. errors +do + local _, e = Nbt.decode("\10\0\0\1\0\1a") + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e2 = Nbt.decode("\13\0\0") + t:check(e2 and e2.code == Err.CORRUPT, "bad root type") + local _, e3 = Nbt.decode("\10\0\0\9\0\1l\1\127\255\255\255") + t:check(e3 and e3.code == Err.TRUNCATED, "huge list length") + local deep = {} + local cur = deep + for _ = 1, 600 do + local n = {} + cur.x = n + cur = n + end + local _, e4 = Nbt.encode(deep) + t:check(e4 and e4.code == Err.ARG, "encode depth") + local _, e5 = Nbt.encode({ a = Nbt.byte(300) }) + t:check(e5 and e5.code == Err.ARG, "encode byte range") + local _, e6 = Nbt.encode({ a = function() end }) + t:check(e6 and e6.code == Err.ARG, "encode function") +end + +-- 7. fuzz +local samples = {} +for i = 1, 8 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].little) +end +table.insert(samples, Fx.cases[3].gzip) +t:fuzz("decode", function(b: buffer) + return Nbt.decode(b) +end, samples) +t:fuzz("decode varint", function(b: buffer) + return Nbt.decode(b, { varint = true }) +end, { Fx.net[1].data, Fx.net[2].data }) +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].compact) +end +t:fuzz("parse", function(b: buffer) + return Nbt.parse(buffer.tostring(b)) +end, texts) +t:done() diff --git a/tests/data/nbt.luau b/tests/data/nbt.luau new file mode 100644 index 0000000..3268473 --- /dev/null +++ b/tests/data/nbt.luau @@ -0,0 +1,60 @@ +-- data/nbt tests: the contract, nbtlib files through the api (F.load / F.save, NBT -> SNBT -> NBT), detection by +-- content and extension, exact round trips (root name, edition, compression and the Bedrock header kept), error +-- codes, and the fuzz pass. The engine itself: tests/codecs/nbt.luau; SNBT files: tests/data/snbt.luau. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local NbtF = require("@formats/data/nbt") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/nbt") + +t:eq(NbtF.name, "nbt", "name") +t:eq(SnbtF.name, "snbt", "snbt name") +t:check(NbtF.caps.decode and NbtF.caps.encode and SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = F.load(c.gzip, { name = "level.dat" }) + t:check(v ~= nil, c.name .. ": F.load gzip") + local text = assert(F.saveString(v, { format = "snbt" })) + local back = assert(F.load(text, { format = "snbt" })) + t:eq(Nbt.print(back), Nbt.print(v), c.name .. ": NBT -> SNBT -> value") + local again = assert(F.save(v, nil, { format = "nbt" })) :: buffer + t:eq(buffer.readu8(again, 0), 0x1f, c.name .. ": saved gzip like the source") + t:eq(Nbt.print(F.load(again, { format = "nbt" })), Nbt.print(v), c.name .. ": saved file reads back") + t:eq(Nbt.info(F.load(again, { format = "nbt" })).name, c.root, c.name .. ": root name kept") + local raw = assert(F.save(v, nil, { format = "nbt", compression = "none" })) :: buffer + t:eq(buffer.tostring(raw), c.raw, c.name .. ": uncompressed = nbtlib's bytes") + local le = assert(F.load(c.header, { format = "nbt" })) + t:eq(buffer.tostring(assert(F.save(le, nil, { format = "nbt" })) :: buffer), c.header, c.name .. ": Bedrock level.dat same bytes") +end + +-- detection +do + local c = Fx.cases[3] + t:eq(F.detect(c.gzip, { name = "level.dat" }), "nbt", "detect gzip .dat") + t:eq(F.detect(c.raw, { name = "x.nbt" }), "nbt", "detect raw .nbt") +end + +-- errors +do + local _, e = NbtF.decode(Bytes.reader(buffer.fromstring("\10\0\0\1"))) + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e3 = NbtF.encode(nil :: any) + t:check(e3 and e3.code == Err.ARG, "encode nil") +end + +local samples = {} +for i = 1, 6 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].header) +end +t:fuzz("decode", function(b: buffer) + return NbtF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/snbt.luau b/tests/data/snbt.luau new file mode 100644 index 0000000..9b88fee --- /dev/null +++ b/tests/data/snbt.luau @@ -0,0 +1,47 @@ +-- data/snbt tests: the contract, nbtlib's SNBT text (indented and compact) through the api, conversion to and from +-- binary NBT (F.convert), detection against JSON, options (indent, quote), error codes, and the fuzz pass. The +-- grammar itself: tests/codecs/nbt.luau. Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/snbt") + +t:eq(SnbtF.name, "snbt", "name") +t:check(SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = assert(F.load(c.snbt, { format = "snbt" })) + local bin = assert(F.convert(c.compact, "nbt", { format = "snbt", compression = "none" })) :: buffer + t:eq(Nbt.print(assert(Nbt.decode(bin))), Nbt.print(v), c.name .. ": SNBT -> NBT") + local text = assert(F.convert(c.raw, "snbt", { format = "nbt" })) :: buffer + t:eq(Nbt.print(assert(Nbt.parse(text))), Nbt.print(v), c.name .. ": NBT -> SNBT") + local pretty = assert(F.saveString(v, { format = "snbt", indent = "\t" })) + t:eq(Nbt.print(assert(F.load(pretty, { format = "snbt" }))), Nbt.print(v), c.name .. ": indented") +end + +do + t:eq(F.detect("{DataVersion:3465,size:[I;1,2,3]}"), "snbt", "detect snbt") + t:eq(F.detect('{"a": 1}'), "json", "json is not snbt") + t:eq(F.detect('{"a": 1b}'), "snbt", "typed number") + t:eq(F.detect(Fx.cases[3].compact, { name = "x.snbt" }), "snbt", "detect .snbt") + t:eq(F.saveString(Nbt.parse("{a:'x'}"), { format = "snbt", quote = "'" }), "{a:'x'}", "quote option") + local _, e = SnbtF.decode(Bytes.reader(buffer.fromstring("{a:"))) + t:check(e and e.code == Err.CORRUPT, "corrupt") + local _, e2 = SnbtF.encode({ a = function() end } :: any) + t:check(e2 and e2.code == Err.ARG, "encode a function") +end + +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].snbt) +end +t:fuzz("decode", function(b: buffer) + return SnbtF.decode(Bytes.reader(b)) +end, texts) +t:done() diff --git a/tools/fixtures/nbt.py b/tools/fixtures/nbt.py new file mode 100644 index 0000000..4bb2364 --- /dev/null +++ b/tools/fixtures/nbt.py @@ -0,0 +1,152 @@ +# 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 s i l f d S: B I[a,b] L[a,b] +# [|a,b] {:=;...} (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(">= 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("