t8rt0t

nbt.lua

Jul 23rd, 2024 (edited)
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 28.93 KB | None | 0 0
  1. local lib,metatables = {},{}
  2. local expect,range = require("cc.expect").expect,require("cc.expect").range
  3.  
  4. local osepoch,osqe,ospe = os.epoch,os.queueEvent,os.pullEvent
  5. local nosleeptimer = osepoch("UTC") + 5000
  6. local function nosleep()
  7.     if osepoch("UTC") > nosleeptimer then
  8.         osqe("nosleep")
  9.         ospe()
  10.         nosleeptimer = osepoch("UTC") + 5000
  11.     end
  12.     -- osqe("nosleep")
  13.     -- ospe()
  14. end
  15.  
  16. local tags = {
  17.     ["END"] = 0,
  18.     BYTE = 1,
  19.     SHORT = 2,
  20.     INT = 3,
  21.     LONG = 4,
  22.     FLOAT = 5,
  23.     DOUBLE = 6,
  24.     BYTE_ARRAY = 7,
  25.     STRING = 8,
  26.     LIST = 9,
  27.     COMPOUND = 10,
  28.     INT_ARRAY = 11,
  29.     LONG_ARRAY = 12
  30. }
  31.  
  32. local END_MT = {TAG=0,__tostring=function() return "TAG_END" end}
  33. local nbt_end = {}
  34. setmetatable(nbt_end,END_MT)
  35. metatables[END_MT] = true
  36. function lib.END()
  37.     return nbt_end
  38. end
  39.    
  40.  
  41. function lib.isNBT(nbt)
  42.     return getmetatable(nbt) and metatables[getmetatable(nbt)]
  43. end
  44.  
  45. function lib.getTag(nbt)
  46.     return lib.isNBT(nbt) and getmetatable(nbt).TAG
  47. end
  48.  
  49. function lib.isNBTNumber(nbt)
  50.     return nbt ~= nbt_end and (lib.getTag(nbt) or tags.BYTE_ARRAY) < tags.BYTE_ARRAY
  51. end
  52. lib.tags = tags
  53.  
  54. local default_types = {
  55.     function() return lib.BYTE(false) end,
  56.     function() return lib.SHORT(0) end,
  57.     function() return lib.INT(0) end,
  58.     function() return lib.LONG(0) end,
  59.     function() return lib.FLOAT(0) end,
  60.     function() return lib.DOUBLE(0) end,
  61.     function() return lib.BYTE_ARRAY() end,
  62.     function() return lib.STRING("") end,
  63.     function() return lib.LIST(0) end,
  64.     function() return lib.COMPOUND() end,
  65.     function() return lib.INT_ARRAY() end,
  66.     function() return lib.LONG_ARRAY() end
  67. }
  68. default_types[0] = lib.END
  69. local function getDefaultValue(nbt_type)
  70.     expect(1,nbt_type,"number")
  71.     func = default_types[nbt_type]
  72.     return func and func() or error(nbt_type.." is not a valid nbt type")
  73. end
  74.  
  75. local function cast(tag_type,value)
  76.     nosleep()
  77.     expect(1,tag_type,"number","nil")
  78.     expect(2,value,"number","boolean","string","table")
  79.     if not tag_type then
  80.         if lib.isNBT(value) then return value end
  81.         if type(value) == "number" and math.floor(value) == value then return lib.INT(value)
  82.         elseif type(value) == "number" and math.floor(value) ~= value then return lib.DOUBLE(value)
  83.         elseif type(value) == "string" then return lib.STRING(value)
  84.         elseif type(value) == "boolean" then return lib.BYTE(value)
  85.         elseif type(value) == "table" and tostring(textutils.serialiseJSON(value)):match("^%[.*%]$") then return cast(9,value) --cast to LIST
  86.         elseif textutils.serialiseJSON(value) then return cast(10,value) --cast to COMPOUND
  87.         else return nil,"Could not find an implicit type for the value" end
  88.     end
  89.     assert(default_types[tag_type],"Invalid tag type")
  90.     if tag_type == tags.BYTE then
  91.         return (lib.tonumber(value) or type(value) == "boolean") and lib.BYTE(lib.tonumber(value) or value) or nil,"BYTE can only be cast from a number or boolean value, got "..tostring(value)
  92.     elseif tag_type == tags.SHORT then
  93.         return lib.tonumber(value) and lib.SHORT(lib.tonumber(value)) or nil,"SHORT can only be cast from a number value, got "..tostring(value)
  94.     elseif tag_type == tags.INT then
  95.         return lib.tonumber(value) and lib.INT(lib.tonumber(value)) or nil,"INT can only be cast from a number value, got "..tostring(value)
  96.     elseif tag_type == tags.LONG then
  97.         return lib.tonumber(value) and lib.LONG(lib.tonumber(value)) or nil,"LONG can only be cast from a number value, got "..tostring(value)
  98.     elseif tag_type == tags.FLOAT then
  99.         return lib.tonumber(value) and lib.FLOAT(lib.tonumber(value)) or nil,"FLOAT can only be cast from a number value, got "..tostring(value)
  100.     elseif tag_type == tags.DOUBLE then
  101.         return lib.tonumber(value) and lib.DOUBLE(lib.tonumber(value)) or nil,"DOUBLE can only be cast from a number value, got "..tostring(value)
  102.     elseif tag_type == tags.BYTE_ARRAY then
  103.         if type(value) ~= "table" then return nil,"BYTE ARRAY must be cast from a table value, got "..tostring(value) end
  104.         local byte_array = lib.BYTE_ARRAY()
  105.         for k,v in pairs(value) do
  106.             if type(k) ~= "number" then return nil,"BYTE_ARRAY must only have number keys, got "..tostring(value) end
  107.             s,err = pcall(function() byte_array[k] = v end)
  108.             if not s then return nil,err end
  109.         end
  110.         return byte_array
  111.     elseif tag_type == tags.STRING then
  112.         return type(value) == "string" and lib.STRING(value) or nil,"STRING can only be cast from a string value, got "..tostring(value)
  113.     elseif tag_type == tags.LIST then
  114.         if type(value) ~= "table" then return nil,"LIST must be cast from a table value, got "..tostring(value) end
  115.         local list
  116.         for k,v in pairs(value) do
  117.             if type(k) ~= "number" then return nil,"LIST must only have number keys, got "..tostring(value) end
  118.             if not list then
  119.                 local nbt,err = cast(nil,v)
  120.                 if nbt then list = lib.LIST(lib.getTag(nbt))
  121.                 else return nil,err end
  122.             end
  123.             s,err = pcall(function() list[k] = v end)
  124.             if not s then return nil,err end
  125.         end
  126.         return list or lib.LIST(tags.END) --return end tag list
  127.     elseif tag_type == tags.COMPOUND then
  128.         if type(value) ~= "table" then return nil,"COMPOUND must be cast from a table value, got "..tostring(value) end
  129.         local compound = lib.COMPOUND()
  130.         for k,v in pairs(value) do
  131.             if type(k) ~= "string" then return nil,"COMPOUND must only have string keys, got "..tostring(value) end
  132.             s,err = pcall(function() compound[k] = v end)
  133.             if not s then return nil,err end
  134.         end
  135.         return compound
  136.     elseif tag_type == tags.INT_ARRAY then
  137.         if type(value) ~= "table" then return nil,"INT ARRAY must be cast from a table value, got "..tostring(value) end
  138.         local int_array = lib.INT_ARRAY()
  139.         for k,v in pairs(value) do
  140.             if type(k) ~= "number" then return nil,"INT ARRAY must only have number keys" end
  141.             s,err = pcall(function() int_array[k] = v end)
  142.             if not s then return nil,err end
  143.         end
  144.         return int_array
  145.     elseif tag_type == tags.LONG_ARRAY then
  146.         if type(value) ~= "table" then return nil,"LONG ARRAY must be cast from a table value, got "..tostring(value) end
  147.         local long_array = lib.LONG_ARRAY()
  148.         for k,v in pairs(value) do
  149.             if type(k) ~= "number" then return nil,"LONG ARRAY must only have number keys" end
  150.             s,err = pcall(function() long_array[k] = v end)
  151.             if not s then return nil,err end
  152.         end
  153.         return long_array
  154.     else
  155.         return nil,"Invalid tag_type"
  156.     end
  157. end
  158.  
  159. local spack,sunpack = string.pack,string.unpack
  160.  
  161. local function clamp(nValue,nMin,nMax,bInteger)
  162.     expect(1,nValue,"number")
  163.     expect(2,nMin,"number")
  164.     expect(3,nMax,"number")
  165.     expect(4,bInteger,"boolean","nil")
  166.     v = math.min(math.max(nValue,nMin),nMax)
  167.     if bInteger then return math.floor(v) else return v end
  168. end
  169.  
  170. --Generic metatable for number functions
  171. local NBT_NUMBER = {
  172.     __tonumber = function(self) return self.value end,
  173.     __unm = function(self) return -self.value end,
  174. }
  175.  
  176. function NBT_NUMBER.__add(a,b)
  177.     if lib.isNBTNumber(a) then a = a.value end
  178.     if lib.isNBTNumber(b) then b = b.value end
  179.     return a+b
  180. end
  181. function NBT_NUMBER.__sub(a,b)
  182.     if lib.isNBTNumber(a) then a = a.value end
  183.     if lib.isNBTNumber(b) then b = b.value end
  184.     return a-b
  185. end
  186. function NBT_NUMBER.__mul(a,b)
  187.     if lib.isNBTNumber(a) then a = a.value end
  188.     if lib.isNBTNumber(b) then b = b.value end
  189.     return a*b
  190. end
  191. function NBT_NUMBER.__div(a,b)
  192.     if lib.isNBTNumber(a) then a = a.value end
  193.     if lib.isNBTNumber(b) then b = b.value end
  194.     return a/b
  195. end
  196. function NBT_NUMBER.__mod(a,b)
  197.     if lib.isNBTNumber(a) then a = a.value end
  198.     if lib.isNBTNumber(b) then b = b.value end
  199.     return a%b
  200. end
  201. function NBT_NUMBER.__pow(a,b)
  202.     if lib.isNBTNumber(a) then a = a.value end
  203.     if lib.isNBTNumber(b) then b = b.value end
  204.     return a^b
  205. end
  206. function NBT_NUMBER.__eq(a,b)
  207.     if lib.isNBTNumber(a) then a = a.value end
  208.     if lib.isNBTNumber(b) then b = b.value end
  209.     return a==b
  210. end
  211. function NBT_NUMBER.__lt(a,b)
  212.     if lib.isNBTNumber(a) then a = a.value end
  213.     if lib.isNBTNumber(b) then b = b.value end
  214.     return a<b
  215. end
  216. function NBT_NUMBER.__le(a,b)
  217.     if lib.isNBTNumber(a) then a = a.value end
  218.     if lib.isNBTNumber(b) then b = b.value end
  219.     return a<=b
  220. end
  221. --Specific metatables for each number
  222. local BYTE_MT = {__index = NBT_NUMBER,TAG=1}
  223. local SHORT_MT = {__index = NBT_NUMBER,TAG=2}
  224. local INT_MT = {__index = NBT_NUMBER,TAG=3}
  225. local LONG_MT = {__index = NBT_NUMBER,TAG=4}
  226. local FLOAT_MT = {__index = NBT_NUMBER,TAG=5}
  227. local DOUBLE_MT = {__index = NBT_NUMBER,TAG=6}
  228. metatables[BYTE_MT] = true
  229. metatables[SHORT_MT] = true
  230. metatables[INT_MT] = true
  231. metatables[FLOAT_MT] = true
  232. metatables[DOUBLE_MT] = true
  233. --why
  234. for k,v in pairs(NBT_NUMBER) do
  235.     BYTE_MT[k],SHORT_MT[k],INT_MT[k],LONG_MT[k],FLOAT_MT[k],DOUBLE_MT[k] = v,v,v,v,v,v
  236. end
  237. --Signed byte (and boolean)
  238. function lib.BYTE(value)
  239.     expect(1,value,"number","boolean")
  240.     local byte = {value=0}
  241.     if value == true then
  242.         byte.value = 1
  243.     elseif value == false then
  244.         byte.value = 0
  245.     else
  246.         byte.value = clamp(value,-128,127,true)
  247.     end
  248.     setmetatable(byte,BYTE_MT)
  249.     return byte
  250. end
  251. function BYTE_MT.__tostring(byte)
  252.     return tostring(byte.value).."b"
  253. end
  254. function BYTE_MT.__tobinary(byte)
  255.     return spack(">b",byte.value)
  256. end
  257. --Signed short
  258. function lib.SHORT(value)
  259.     expect(1,value,"number")
  260.     local short = {value=clamp(value,-32768,32767,true)}
  261.     setmetatable(short,SHORT_MT)
  262.     return short
  263. end
  264. function SHORT_MT.__tostring(short)
  265.     return tostring(short.value).."s"
  266. end
  267. function SHORT_MT.__tobinary(short)
  268.     return spack(">h",short.value)
  269. end
  270. --Signed int
  271. function lib.INT(value)
  272.     expect(1,value,"number")
  273.     local int = {value=clamp(value,-2147483648,2147483647,true)}
  274.     setmetatable(int,INT_MT)
  275.     return int
  276. end
  277. function INT_MT.__tostring(int)
  278.     return tostring(int.value)
  279. end
  280. function INT_MT.__tobinary(int)
  281.     return spack(">i4",int.value)
  282. end
  283. --Signed long (may be problematic due to lua precision issues)
  284. function lib.LONG(value)
  285.     expect(1,value,"number")
  286.     local long = {value=clamp(value,-2^63,2^63-1,true)}
  287.     setmetatable(long,LONG_MT)
  288.     return long
  289. end
  290. function LONG_MT.__tostring(long)
  291.     return tostring(long.value).."l"
  292. end
  293. function LONG_MT.__tobinary(long)
  294.     return spack(">l",long.value)
  295. end
  296. --Signed 4 byte floating point
  297. function lib.FLOAT(value)
  298.     expect(1,value,"number")
  299.     local float = {value=value}
  300.     setmetatable(float,FLOAT_MT)
  301.     return float
  302. end
  303. function FLOAT_MT.__tostring(float)
  304.     local str = tostring(float.value)
  305.     return (str.find("%.") and str or (str .. ".0")) .."f"
  306. end
  307. function FLOAT_MT.__tobinary(float)
  308.     return spack(">f",float.value)
  309. end
  310. --Signed 8 byte double floating point
  311. function lib.DOUBLE(value)
  312.     expect(1,value,"number")
  313.     local double = {value=value}
  314.     setmetatable(double,DOUBLE_MT)
  315.     return double
  316. end
  317. function DOUBLE_MT.__tostring(double)
  318.     local str = tostring(double.value)
  319.     return (str.find("%.") and str or (str .. ".0"))
  320. end
  321. function DOUBLE_MT.__tobinary(double)
  322.     return spack(">d",double.value)
  323. end
  324.  
  325. --String stuff
  326. local STRING_MT = {
  327.     __len = function(self) return #self.data end,
  328.     __tostring = function(self) return string.format("%q",self.data) end,
  329.     TAG = 8
  330. }
  331. metatables[STRING_MT] = true
  332. function STRING_MT.__concat(a,b)
  333.     if getmetatable(a) == STRING_MT then a = a.data end
  334.     if getmetatable(b) == STRING_MT then b = b.data end
  335.     return a .. b
  336. end
  337. function STRING_MT.__eq(a,b)
  338.     if getmetatable(a) == STRING_MT then a = a.data end
  339.     if getmetatable(b) == STRING_MT then b = b.data end
  340.     return a == b
  341. end
  342. function STRING_MT.__lt(a,b)
  343.     if getmetatable(a) == STRING_MT then a = a.data end
  344.     if getmetatable(b) == STRING_MT then b = b.data end
  345.     return a < b
  346. end
  347. function STRING_MT.__le(a,b)
  348.     if getmetatable(a) == STRING_MT then a = a.data end
  349.     if getmetatable(b) == STRING_MT then b = b.data end
  350.     return a <= b
  351. end
  352. function lib.STRING(str)
  353.     expect(1,str,"string")
  354.     local s = {data=str}
  355.     setmetatable(s,STRING_MT)
  356.     return s
  357. end
  358. function STRING_MT.__tobinary(str)
  359.     return spack(">H",#str)..str.data
  360. end
  361.  
  362. --Generic list metatable
  363. local NBT_LIST = {
  364.     __len = function(self) return #rawget(self,"data") end,
  365.     __index = function(self,key) return rawget(self,"data")[key] end,
  366.     __pairs = function(self) return pairs(rawget(self,"data")) end,
  367.     __ipairs = function(self) return ipairs(rawget(self,"data")) end,
  368.     __newindex = function(self,key,value)
  369.         if type(value) ~= "table" or lib.getTag(value) ~= rawget(self,"TYPE") then
  370.             value = assert(cast(rawget(self,"TYPE"),value))
  371.             --error(tostring(value).." is not the same type as the tag in this list")
  372.         end
  373.         if type(key) ~= "number" or math.floor(key) ~= key or key <= 0 then
  374.             error(tostring(key) .. " is not a valid integer index")
  375.         end
  376.         local data = rawget(self,"data")
  377.         local nbt_type = rawget(self,"TYPE")
  378.         for i=#data+1,key-1 do
  379.             data[i] = getDefaultValue(nbt_type)
  380.         end
  381.         data[key]=value
  382.     end,
  383. }
  384. --Specific metatables for each list
  385. local COMPOUND_MT = {TAG=10}
  386. local LIST_MT = {TAG=9}
  387. local BYTE_ARRAY_MT = {TAG=7}
  388. local INT_ARRAY_MT = {TAG=11}
  389. local LONG_ARRAY_MT = {TAG=12}
  390. metatables[COMPOUND_MT] = true
  391. metatables[LIST_MT] = true
  392. metatables[BYTE_ARRAY_MT] = true
  393. metatables[INT_ARRAY_MT] = true
  394. metatables[LONG_ARRAY_MT] = true
  395. --copy over functions
  396. for k,v in pairs(NBT_LIST) do
  397.     COMPOUND_MT[k],LIST_MT[k],BYTE_ARRAY_MT[k],INT_ARRAY_MT[k],LONG_ARRAY_MT[k] = v,v,v,v,v
  398. end
  399.  
  400. function lib.LIST(tag_type,data)
  401.     expect(1,tag_type,"number")
  402.     expect(2,data,"table","nil")
  403.     assert(default_types[tag_type] or tag_type == -1,"Not a valid list type!")
  404.     local list = {TYPE=tag_type,data={}}
  405.     setmetatable(list,LIST_MT)
  406.     if data then
  407.         for k,v in pairs(data) do
  408.             pcall(function() list[k] = v end)
  409.         end
  410.     end
  411.     return list
  412. end
  413. function LIST_MT.__tostring(list)
  414.     local str = "["
  415.     for k,v in ipairs(list) do
  416.         str = str .. tostring(v) .. ","
  417.     end
  418.     return str:gsub(",$","").."]"
  419. end
  420. function LIST_MT.__tobinary(list,recur)
  421.     nosleep()
  422.     recur = (tonumber(recur) or 0)+1
  423.     if recur >= 512 then error("NBT cannot be nested more than 512 times") end
  424.     local str = string.char(rawget(list,"TYPE"))..spack(">i4",#list)
  425.     for k,v in ipairs(list) do
  426.         str = str .. getmetatable(v).__tobinary(v)
  427.     end
  428.     return str
  429. end
  430. function lib.BYTE_ARRAY(data)
  431.     expect(1,data,"table","nil")
  432.     local byte_array = {TYPE=1,data={}}
  433.     setmetatable(byte_array,BYTE_ARRAY_MT)
  434.     if data then
  435.         for k,v in pairs(data) do
  436.             pcall(function() byte_array[k] = v end)
  437.         end
  438.     end
  439.     return byte_array
  440. end
  441. function BYTE_ARRAY_MT.__tostring(byte_array)
  442.     local str = "[B;"
  443.     for k,v in ipairs(byte_array) do
  444.         str = str .. tostring(v) .. ","
  445.     end
  446.     return str:gsub(",$","").."]"
  447. end
  448. function BYTE_ARRAY_MT.__tobinary(byte_array)
  449.     local str = spack(">i4",#byte_array)
  450.     for k,v in ipairs(byte_array) do
  451.         str = str .. getmetatable(v).__tobinary(v)
  452.     end
  453.     return str
  454. end
  455. function lib.INT_ARRAY(data)
  456.     expect(1,data,"table","nil")
  457.     local int_array = {TYPE=3,data={}}
  458.     setmetatable(int_array,INT_ARRAY_MT)
  459.     if data then
  460.         for k,v in pairs(data) do
  461.             pcall(function() int_array[k] = v end)
  462.         end
  463.     end
  464.     return int_array
  465. end
  466. function INT_ARRAY_MT.__tostring(int_array)
  467.     local str = "[I;"
  468.     for k,v in ipairs(int_array) do
  469.         str = str .. tostring(v) .. ","
  470.     end
  471.     return str:gsub(",$","").."]"
  472. end
  473. function INT_ARRAY_MT.__tobinary(int_array)
  474.     local str = spack(">i4",#int_array)
  475.     for k,v in ipairs(int_array) do
  476.         str = str .. getmetatable(v).__tobinary(v)
  477.     end
  478.     return str
  479. end
  480. function lib.LONG_ARRAY()
  481.     local long_array = {TYPE=4,data={}}
  482.     setmetatable(long_array,LONG_ARRAY_MT)
  483.     if data then
  484.         for k,v in pairs(data) do
  485.             pcall(function() long_array[k] = v end)
  486.         end
  487.     end
  488.     return long_array
  489. end
  490. function LONG_ARRAY_MT.__tostring(long_array)
  491.     local str = "[L;"
  492.     for k,v in ipairs(long_array) do
  493.         str = str .. tostring(v) .. ","
  494.     end
  495.     return str:gsub(",$","").."]"
  496. end
  497. function LONG_ARRAY_MT.__tobinary(long_array)
  498.     local str = spack(">i4",#long_array)
  499.     for k,v in ipairs(long_array) do
  500.         str = str .. getmetatable(v).__tobinary(v)
  501.     end
  502.     return str
  503. end
  504.  
  505. function lib.COMPOUND(data)
  506.     expect(1,data,"table","nil")
  507.     local compound = {data={}}
  508.     setmetatable(compound,COMPOUND_MT)
  509.     if data then
  510.         for k,v in pairs(data) do
  511.             pcall(function() compound[k] = v end)
  512.         end
  513.     end
  514.     return compound
  515. end
  516. function COMPOUND_MT.__tostring(compound)
  517.     local str = "{"
  518.     for k,v in pairs(compound) do
  519.         str = str .. string.format("%q",k)..":"..tostring(v)..","
  520.     end
  521.     return str:gsub(",$","").."}"
  522. end
  523. function COMPOUND_MT.__newindex(self,key,value)
  524.     if not default_types[lib.getTag(value) or -1] then
  525.         value = assert(cast(nil,value))
  526.         --error(tostring(value).." is not a nbt component!")
  527.     end
  528.     if getmetatable(key) == STRING_MT then key = key.data end
  529.     if type(key) ~= "string" then
  530.         error(tostring(key) .. " is not a string index",2)
  531.     end
  532.     rawget(self,"data")[key]=value
  533. end
  534. --I hate lua tables
  535. function COMPOUND_MT.__len(self)
  536.     local count = 0
  537.     for k,v in pairs(rawget(self,"data")) do
  538.         count = count + 1
  539.     end
  540.     return count
  541. end
  542. function COMPOUND_MT.__tobinary(compound,recur)
  543.     nosleep()
  544.     recur = (tonumber(recur) or 0)+1
  545.     if recur >= 512 then error("NBT cannot be nested more than 512 times",2) end
  546.     local str = ""
  547.     for k,v in pairs(compound) do
  548.         str = str .. string.char(lib.getTag(v))..spack(">H",#k)..k..getmetatable(v).__tobinary(v,recur)
  549.     end
  550.     return str..string.char(0)
  551. end
  552.  
  553. function lib.tobinary(nbt)
  554.     expect(1,nbt,"table")
  555.     local mt = getmetatable(nbt)
  556.     assert(mt == COMPOUND_MT,"Can only convert compound tags to binary")
  557.     return mt.__tobinary(nbt)
  558. end
  559. local function buffer(str)
  560.     local str,idx = str,1
  561.     return function(count)
  562.         if idx > #str then return "\000" end --nil end
  563.         count = tonumber(count) or 1
  564.         local s = str:sub(idx,idx+count-1)
  565.         idx = idx + count
  566.         return s
  567.     end
  568. end
  569. local function fromBinaryRaw(buf,t)
  570.     nosleep()
  571.     if t == 1 then
  572.         return lib.BYTE(sunpack(">b",buf()))
  573.     elseif t == 2 then
  574.         return lib.SHORT(sunpack(">h",buf(2)))
  575.     elseif t == 3 then
  576.         return lib.INT(sunpack(">i4",buf(4)))
  577.     elseif t == 4 then
  578.         return lib.LONG(sunpack(">l",buf(8)))
  579.     elseif t == 5 then
  580.         return lib.FLOAT(sunpack(">f",buf(4)))
  581.     elseif t == 6 then
  582.         return lib.DOUBLE(sunpack(">d",buf(8)))
  583.     elseif t == 8 then
  584.         local len = sunpack(">H",buf(2))
  585.         return lib.STRING(buf(len))
  586.     elseif t == 7 then
  587.         local len = sunpack(">i4",buf(4))
  588.         local b = lib.BYTE_ARRAY()
  589.         for i=1,len do
  590.             b[i] = sunpack(">b",buf())
  591.         end
  592.         return b
  593.     elseif t == 9 then
  594.         local id = buf():byte()
  595.         local l = lib.LIST(id)
  596.         local len = sunpack(">i4",buf(4))
  597.         for i=1,len do
  598.             l[i] = fromBinaryRaw(buf,id)
  599.         end
  600.         return l
  601.     elseif t == 10 then
  602.         local id = buf():byte()
  603.         local c = lib.COMPOUND()
  604.         while id and id ~= 0 do
  605.             local len = sunpack(">H",buf(2))
  606.             local key = buf(len)
  607.             c[key] = fromBinaryRaw(buf,id)
  608.             id = buf():byte()
  609.         end
  610.         return c
  611.     elseif t == 11 then
  612.         local len = sunpack(">i4",buf(4))
  613.         local b = lib.INT_ARRAY()
  614.         for i=1,len do
  615.             b[i] = sunpack(">i4",buf(4))
  616.         end
  617.         return b
  618.     elseif t == 12 then
  619.         local len = sunpack(">i4",buf(4))
  620.         local b = lib.LONG_ARRAY()
  621.         for i=1,len do
  622.             b[i] = sunpack(">l",buf(8))
  623.         end
  624.         return b
  625.     else
  626.         error("invalid tag "..tostring(t))
  627.     end
  628. end
  629. function lib.frombinary(str)
  630.     expect(1,str,"string")
  631.     return fromBinaryRaw(buffer(str),10)
  632. end
  633.  
  634. local function parseErr(str,pos,err)
  635.     error(err .. ' ("'..str:sub(pos-10,pos)..'"<-- here)',pos)
  636. end
  637.  
  638. local function aParseErr(value,...)
  639.     if value then return value,... else return parseErr(...) end
  640. end
  641.  
  642. local parse = {}
  643.  
  644. function parse.number(str,pos)
  645.     local sPos,ePos = str:find("%-?%d+%.?%d*",pos)
  646.     aParseErr(sPos,str,pos,"Could not serialise number")
  647.     local value = aParseErr(tonumber(str:sub(sPos,ePos)),str,ePos,"Could not serialise number")
  648.     local nextC = str:sub(ePos+1,ePos+1):lower()
  649.     if str:sub(sPos,ePos):find("%.") then --floats or doubles
  650.         if nextC == "f" then return lib.FLOAT(value),ePos+2,5
  651.         elseif not nextC:match("%a") then return lib.DOUBLE(value),ePos+1,6
  652.         else parseErr(str,ePos+1,"Number has a decimal, but isn't a float or double value") end
  653.     else
  654.         if nextC == "b" then return lib.BYTE(value),ePos+2,1
  655.         elseif nextC == "s" then return lib.SHORT(value),ePos+2,2
  656.         elseif nextC == "l" then return lib.LONG(value),ePos+2,4
  657.         elseif not nextC:match("%a") then return lib.INT(value),ePos+1,3
  658.         else parseErr(str,ePos+1,"Number has invalid character after it") end
  659.     end
  660.     parseError(str,pos,"Unknown error parsing number")
  661. end
  662.  
  663. function parse.list(str,pos,obj)
  664.     local tag_type = rawget(obj,"TYPE")
  665.     local c,o,t = ""
  666.     while true do
  667.         pos = aParseErr(str:find("%S",pos),str,pos,"Missing `]` bracket to close list or array")
  668.         c = str:sub(pos,pos)
  669.         if c == "]" then
  670.             if tag_type == -1 then rawset(obj,"TYPE",0) end
  671.             return obj,pos+1,lib.getTag(obj)
  672.         else
  673.             o,pos,t = parse.main(str,pos)
  674.             if t == tag_type then
  675.                 obj[#obj+1] = o
  676.                 pos = aParseErr(str:find("%S",pos),str,pos,"Missing `]` bracket to close list or array")
  677.                 c = str:sub(pos,pos)
  678.                 if c == ']' then return obj,pos+1,lib.getTag(obj)
  679.                 elseif c ~= "," then
  680.                     parseErr(str,pos,"Could not parse list or array, expected `,` to seperate entries")
  681.                 end
  682.                 pos = pos + 1
  683.             elseif tag_type == -1 then --Make lists type the type of their first object
  684.                 rawset(obj,"TYPE",t)
  685.                 tag_type = t
  686.                 obj[#obj+1] = o
  687.                 pos = aParseErr(str:find("%S",pos),str,pos,"Missing `]` bracket to close list or array")
  688.                 c = str:sub(pos,pos)
  689.                 if c == ']' then return obj,pos+1,lib.getTag(obj)
  690.                 elseif c ~= "," then
  691.                     parseErr(str,pos,"Could not parse list or array, expected `,` to seperate entries")
  692.                 end
  693.                 pos = pos + 1
  694.             else
  695.                 parseErr(str,pos,"Invalid entry type, list is of type "..tag_type..", but object is "..t)
  696.             end
  697.         end
  698.     end
  699. end
  700.  
  701.  
  702.  
  703. function parse.string(str,pos)
  704.     local sType = str:sub(pos,pos)
  705.     if sType == '"' or sType == "'" then
  706.         local endPos = aParseErr(str:find("[^\\]"..sType,pos),str,pos,"Missing quotes to terminate the string")
  707.         return lib.STRING(textutils.unserialise(str:sub(pos,endPos+1))),endPos+2,8
  708.     else
  709.         local endPos = aParseErr(str:find("[^%w_]",pos),str,pos,"Invalid character in key")
  710.         return lib.STRING(str:sub(pos,endPos-1)),endPos,8
  711.     end
  712.     parseErr(str,pos,"Unknown error parsing string")
  713. end
  714.  
  715. function parse.compound(str,pos)
  716.     nosleep()
  717.     local c,compound,key = "",lib.COMPOUND()
  718.     while true do
  719.         pos = aParseErr(str:find("%S",pos),str,pos,"Missing `}` bracket to close compound tag")
  720.         c = str:sub(pos,pos)
  721.         if c == "}" then return compound,pos+1,10
  722.         elseif c:match("[%a'\"]") then
  723.             key,pos = parse.string(str,pos)
  724.             pos = aParseErr(str:find("%S",pos),str,pos,"Missing `}` bracket to close compound tag")
  725.             c = str:sub(pos,pos)
  726.             if c ~= ":" then
  727.                 parseErr(str,pos,"Could not parse compound tag, expected : to seperate key and value")
  728.             end
  729.             compound[key],pos = parse.main(str,pos+1)
  730.             pos = aParseErr(str:find("%S",pos),str,pos,"Missing `}` bracket to close compound tag")
  731.             c = str:sub(pos,pos)
  732.             if c == "}" then return compound,pos+1,10
  733.             elseif c ~= "," then
  734.                 parseErr(str,pos,"Could not parse compound tag, expected `,` to seperate entries")
  735.             end
  736.             pos = pos + 1
  737.         elseif c == "" then
  738.             parseErr(str,pos,"Missing `}` bracket to close compound tag")
  739.         else
  740.             parseErr(str,pos,"Invalid character for compound tag")
  741.         end
  742.     end
  743. end
  744.  
  745.  
  746.  
  747. function parse.main(str,pos)
  748.     nosleep()
  749.     pos = aParseErr(str:find("%S",pos),str,pos,"NBT string ended too early")
  750.     local c = str:sub(pos,pos)
  751.     if c == "{" then
  752.         pos = str:find("%S",pos+1) --skip next whitespace
  753.         return parse.compound(str,pos)
  754.     elseif c == '"' or c == "'" then
  755.         return parse.string(str,pos)
  756.     elseif c:match("[%-%d]") then
  757.         return parse.number(str,pos)
  758.     elseif c == "[" then
  759.         local t = str:sub(pos+1,pos+2)
  760.         if t == "I;" then
  761.             return parse.list(str,pos+3,lib.INT_ARRAY())
  762.         elseif t == "B;" then
  763.             return parse.list(str,pos+3,lib.BYTE_ARRAY())
  764.         elseif t == "L;" then
  765.             return parse.list(str,pos+3,lib.LONG_ARRAY())
  766.         else
  767.             return parse.list(str,pos+1,lib.LIST(-1))
  768.         end
  769.     elseif c == "t" and str:sub(pos,pos+3) == "true" then
  770.         return lib.BYTE(true),pos+4,1
  771.     elseif c == "f" and str:sub(pos,pos+4) == "false" then
  772.         return lib.BYTE(false),pos+5,1
  773.     else
  774.         parseErr(str,pos,"Invalid character")
  775.     end
  776. end
  777.  
  778. function lib.fromstring(str)
  779.     return ({parse.main(str,1)})[1]
  780. end
  781.  
  782. local str_overrides = {
  783.     ["\n"] = '\\n',
  784.     ["\t"] = '\\t',
  785.     [string.char(0)] = "\\000",
  786.     ['\r'] = '\\r',
  787.     ['\a'] = '\\a',
  788.     ['\b'] = '\\b',
  789.     ['\f'] = '\\f'
  790. }
  791.  
  792. function lib.serialize(nbt,sTab,bExpandArrays,sCurrentTab)
  793.     local tag = assert(type(nbt) == "table" and lib.getTag(nbt),"Bad argument #1 (nbt expected, got "..type(nbt)..")")
  794.     expect(2,sTab,"string","nil")
  795.     expect(3,bExpandArrays,"boolean","nil")
  796.     expect(4,sCurrentTab,"string","nil")
  797.     sTab = type(sTab) == "string" and sTab or " "
  798.     sCurrentTab = sCurrentTab or ""
  799.     if tag <= 6 then
  800.         return tostring(nbt)
  801.     elseif tag == 8 then
  802.         return tostring(nbt):gsub("[\000-\x20]",function(str) return str_overrides[str] or str end)
  803.     elseif tag == 10 then
  804.         if #nbt == 0 then return "{}" end
  805.         local str = "{"
  806.         for k,v in pairs(nbt) do
  807.             str = str .. string.format("\n"..sCurrentTab..sTab.."%q:%s,",k,lib.serialize(v,sTab,bExpandArrays,sCurrentTab..sTab))
  808.         end
  809.         return str:gsub(',$','') .. "\n" .. sCurrentTab .. "}"
  810.     elseif tag == 9 then
  811.         local tag_type = rawget(nbt,"TYPE")
  812.         if #nbt == 0 then return "[]" end
  813.         if not bExpandArrays and (tag_type <= 6 or tag_type == 8) then return tostring(nbt) end
  814.         local str = "["
  815.         for k,v in ipairs(nbt) do
  816.             str = str .. string.format("\n"..sCurrentTab..sTab.."%s,",lib.serialize(v,sTab,bExpandArrays,sCurrentTab..sTab))
  817.         end
  818.         return str:gsub(',$','') .. "\n" .. sCurrentTab .. "]"  
  819.     elseif bExpandArrays then
  820.         local str = "["
  821.         if tag_type == 7 then
  822.             str = str .. "B;"
  823.         elseif tag_type == 11 then
  824.             str = str .. "I;"
  825.         elseif tag_type == 12 then
  826.             str = str .. "L;"
  827.         end
  828.         if #nbt == 0 then return str .. "]" end
  829.         for k,v in ipairs(nbt) do
  830.             str = str .. string.format("\n"..sCurrentTab..sTab.."%s,",tostring(v))
  831.         end
  832.         return str:gsub(',$','') .. "\n" .. sCurrentTab .. "]"
  833.     else
  834.         return tostring(nbt)
  835.     end
  836. end
  837. lib.serialise = serialize
  838.  
  839. function lib.tonumber(value)
  840.     return tonumber(value) or (type(value) == "table" and getmetatable(value) and (getmetatable(value).__tonumber or function()end)(value))
  841. end
  842.    
  843. lib.cast = cast
  844. return lib
Advertisement
Add Comment
Please, Sign In to add comment