codecs/text: comments to specs only

This commit is contained in:
4DBug committed 2026-11-01 01:59:16 -05:00
1 parent f626fb4295
commit 492d6662df
12 files changed
+97 -294

No files matched your search

+9 -17
View File
@@ -1,9 +1,7 @@
--!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).
-- Java big-endian (modified UTF-8 strings), Bedrock little-endian (UTF-8), and Bedrock network NBT (little-endian,
-- zigzag varint int / long, varint lengths).
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Value = require("@rosetta/codecs/text/Nbt/Value")
@@ -11,11 +9,11 @@ local Value = require("@rosetta/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 "")
endian: ("big" | "little")?,
varint: boolean?,
nameless: boolean?,
maxDepth: number?,
name: string?,
}
local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16
@@ -27,7 +25,6 @@ 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
@@ -89,7 +86,6 @@ end
Binary.fromModified = fromModified
Binary.toModified = toModified
-- ------------------------------------------------------------------------------------------------ read
local function fail(s: State, msg: string): nil
if not s.err then
s.err = msg
@@ -170,7 +166,7 @@ local function len(s: State): number
return i32(s)
end
local function i64(s: State): (number, number) -- hi, lo
local function i64(s: State): (number, number)
if s.net then
local lo, hi, sh = 0, 0, 0
while true do
@@ -248,7 +244,6 @@ 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 }
@@ -393,7 +388,6 @@ payload = function(s: State, id: number): any
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
@@ -425,7 +419,6 @@ function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (an
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)
@@ -438,7 +431,7 @@ local function wvaruint(w: Bytes.Writer, v: number)
end
local function wi32(ws: WState, v: number)
v %= TWO32 -- two's complement
v %= TWO32
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)
@@ -671,7 +664,6 @@ wpayload = function(ws: WState, t: string, v: any): string?
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
+4 -15
View File
@@ -1,11 +1,6 @@
--!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.
-- codecs/text/Nbt/Snbt: stringified NBT, parse and print, from the Minecraft wiki "NBT format" SNBT section (1.21.5).
-- Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes.
local Types = require("@rosetta/Types")
local Value = require("@rosetta/codecs/text/Nbt/Value")
@@ -13,8 +8,8 @@ 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
indent: (number | string)?,
quote: string?,
}
local byte, sub, find = string.byte, string.sub, string.find
@@ -24,7 +19,6 @@ 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
@@ -85,7 +79,6 @@ local function quoted(p: P): string?
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 },
@@ -135,7 +128,6 @@ local function integer(t: string): any
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)
@@ -437,7 +429,6 @@ parseValue = function(p: P): any
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)
@@ -451,7 +442,6 @@ function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?)
return v, nil, nil
end
-- ------------------------------------------------------------------------------------------------ print
local function shortest(v: number, single: boolean): string
if v ~= v then
return "NaN"
@@ -625,7 +615,6 @@ printValue = function(pr: Pr, v: any, depth: number): string?
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
+2 -22
View File
@@ -1,13 +1,7 @@
--!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.
-- long values are numbers when |v| <= 2^53, else their exact decimal text; longArray values are buffers of
-- little-endian two's complement int64s.
local Types = require("@rosetta/Types")
local Value = {}
@@ -37,7 +31,6 @@ 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
@@ -67,11 +60,8 @@ 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
@@ -94,7 +84,6 @@ function Value.fromHiLo(hi: number, lo: number): number | string
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
@@ -127,7 +116,6 @@ function Value.toHiLo(v: any): (number?, number?)
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ constructors
local function tag(name: string, v: any): Tag
return setmetatable({ type = name, value = v }, TagMeta) :: any
end
@@ -140,7 +128,6 @@ 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)
@@ -151,7 +138,6 @@ function Value.long(v: number | string): Tag
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))
@@ -162,7 +148,6 @@ 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)
@@ -176,7 +161,6 @@ function Value.longArray(t: { any } | buffer | nil): Tag
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 }
@@ -185,7 +169,6 @@ function Value.longs(a: Tag): { number | string }
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
@@ -194,7 +177,6 @@ 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
@@ -205,7 +187,6 @@ 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
@@ -236,7 +217,6 @@ function Value.typeOf(v: any): (string?, string?)
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
+26 -55
View File
@@ -1,22 +1,6 @@
--!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("@rosetta/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.
-- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT").
-- Files may be gzip or zlib compressed; a Bedrock level.dat has an 8-byte header.
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -29,31 +13,31 @@ local Nbt = {}
export type Tag = Value.Tag
export type Info = {
name: string, -- the root tag's name
name: string,
endian: "big" | "little",
varint: boolean?, -- Bedrock network NBT
varint: boolean?,
compression: "gzip" | "zlib" | "none",
header: number?, -- Bedrock level.dat: the storage version from the 8-byte header
header: number?,
}
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"
endian: ("big" | "little")?,
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)
maxDepth: number?,
maxBytes: number?,
}
export type EncodeOptions = {
endian: ("big" | "little")?,
varint: boolean?,
nameless: boolean?,
name: string?,
compression: ("gzip" | "zlib" | "none")?,
header: number?,
level: number?,
}
Nbt.TAG = Value.IDS -- name -> id
Nbt.TAG_NAMES = Value.NAMES -- id -> name
Nbt.TAG = Value.IDS
Nbt.TAG_NAMES = Value.NAMES
Nbt.byte = Value.byte
Nbt.short = Value.short
Nbt.int = Value.int
@@ -74,18 +58,15 @@ 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
@@ -98,7 +79,6 @@ function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts:
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
@@ -107,7 +87,6 @@ function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
@@ -135,14 +114,14 @@ function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxB
end
export type Peek = {
compression: string, -- "gzip" | "zlib" | "none"
compression: string,
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
header: boolean,
rootType: string,
name: string,
firstType: string?,
firstName: string?,
head: buffer, -- the first (up to 1024) uncompressed bytes
head: buffer,
}
local function plausibleName(b: buffer, p: number, n: number): string?
@@ -156,8 +135,6 @@ local function plausibleName(b: buffer, p: number, n: number): string?
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)
@@ -204,7 +181,7 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek?
return nil
end
if ft == 0 then
res.firstType = "end" -- an empty root compound
res.firstType = "end"
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
@@ -224,8 +201,6 @@ function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek?
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)
@@ -291,7 +266,6 @@ function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?,
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)
@@ -325,7 +299,6 @@ function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?)
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
@@ -338,7 +311,6 @@ function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.E
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
@@ -347,7 +319,6 @@ function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?)
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