58 lines
2.2 KiB
Luau
58 lines
2.2 KiB
Luau
--!strict
|
|
-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT
|
|
-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info).
|
|
-- Not supported: none.
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Nbt = require("@rosetta/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
|
|
NbtFormat.Nbt = Nbt
|
|
|
|
return NbtFormat
|