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.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 14:12:46 -05:00
1 parent d3dbba500b
commit 512cbc3dc8
15 files changed
+2745 -26

No files matched your search

+24
View File
@@ -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",
@@ -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)
+66 -24
View File
@@ -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
}
+698
View File
@@ -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
+649
View File
@@ -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
+256
View File
@@ -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 = "<name>", 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
+380
View File
@@ -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
+60
View File
@@ -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
+63
View File
@@ -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