Files
rosetta/src/Formats/codecs/text/Nbt/init.luau
T
4DBug 998177e5ab 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.
2026-10-31 14:12:46 -05:00

381 lines
13 KiB
Luau

--!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