Omsigames

json.lua

Dec 25th, 2024 (edited)
8
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.59 KB | None | 0 0
  1. --
  2. -- json.lua
  3. --
  4. -- Copyright (c) 2018 rxi
  5. --
  6. -- Permission is hereby granted, free of charge, to any person obtaining a copy of
  7. -- this software and associated documentation files (the "Software"), to deal in
  8. -- the Software without restriction, including without limitation the rights to
  9. -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10. -- of the Software, and to permit persons to whom the Software is furnished to do
  11. -- so, subject to the following conditions:
  12. --
  13. -- The above copyright notice and this permission notice shall be included in all
  14. -- copies or substantial portions of the Software.
  15. --
  16. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. -- SOFTWARE.
  23. --
  24.  
  25. local json = {}
  26.  
  27. -------------------------------------------------------------------------------
  28. -- Encode
  29. -------------------------------------------------------------------------------
  30.  
  31. local encode
  32.  
  33. local escape_char_map = {
  34.    [ "\\" ] = "\\\\",
  35.    [ "\"" ] = "\\\"",
  36.    [ "\b" ] = "\\b",
  37.    [ "\f" ] = "\\f",
  38.    [ "\n" ] = "\\n",
  39.    [ "\r" ] = "\\r",
  40.    [ "\t" ] = "\\t",
  41. }
  42.  
  43. local escape_char_map_inv = { [ "\\/" ] = "/" }
  44. for k, v in pairs(escape_char_map) do
  45.    escape_char_map_inv[v] = k
  46. end
  47.  
  48. local function escape_char(c)
  49.    return escape_char_map[c] or string.format("\\u%04x", c:byte())
  50. end
  51.  
  52. local function encode_nil(val)
  53.    return "null"
  54. end
  55.  
  56. local function encode_table(val, stack)
  57.    local res = {}
  58.    stack = stack or {}
  59.  
  60.    -- Circular reference?
  61.    if stack[val] then error("circular reference") end
  62.  
  63.    stack[val] = true
  64.  
  65.    if val[1] ~= nil or next(val) == nil then
  66.       -- Treat as array -- check keys are valid and it is not sparse
  67.       local n = 0
  68.       for k in pairs(val) do
  69.          if type(k) ~= "number" then
  70.             error("invalid table: mixed or invalid key types")
  71.          end
  72.          n = n + 1
  73.       end
  74.       if n ~= #val then
  75.          error("invalid table: sparse array")
  76.       end
  77.       -- Encode
  78.       for i, v in ipairs(val) do
  79.          table.insert(res, encode(v, stack))
  80.       end
  81.       stack[val] = nil
  82.       return "[" .. table.concat(res, ",") .. "]"
  83.  
  84.    else
  85.       -- Treat as an object
  86.       for k, v in pairs(val) do
  87.          if type(k) ~= "string" then
  88.             error("invalid table: mixed or invalid key types")
  89.          end
  90.          table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
  91.       end
  92.       stack[val] = nil
  93.       return "{" .. table.concat(res, ",") .. "}"
  94.    end
  95. end
  96.  
  97.  
  98. local function encode_string(val)
  99.    return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
  100. end
  101.  
  102.  
  103. local function encode_number(val)
  104.    -- Check for NaN, -inf and inf
  105.    if val ~= val or val <= -math.huge or val >= math.huge then
  106.       error("unexpected number value '" .. tostring(val) .. "'")
  107.    end
  108.    return string.format("%.14g", val)
  109. end
  110.  
  111.  
  112. local type_func_map = {
  113.    [ "nil"     ] = encode_nil,
  114.    [ "table"   ] = encode_table,
  115.    [ "string"  ] = encode_string,
  116.    [ "number"  ] = encode_number,
  117.    [ "boolean" ] = tostring,
  118. }
  119.  
  120.  
  121. encode = function(val, stack)
  122.    local t = type(val)
  123.    local f = type_func_map[t]
  124.    if f then
  125.       return f(val, stack)
  126.    end
  127.    error("unexpected type '" .. t .. "'")
  128. end
  129.  
  130.  
  131. function json.encode(val)
  132.    return encode(val)
  133. end
  134.  
  135.  
  136. -------------------------------------------------------------------------------
  137. -- Decode
  138. -------------------------------------------------------------------------------
  139.  
  140. local parse
  141.  
  142. local function create_set(...)
  143.    local res = {}
  144.    for i = 1, select("#", ...) do
  145.       res[ select(i, ...) ] = true
  146.    end
  147.    return res
  148. end
  149.  
  150. local space_chars   = create_set(" ", "\t", "\r", "\n")
  151. local delim_chars   = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
  152. local escape_chars  = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
  153. local literals      = create_set("true", "false", "null")
  154.  
  155. local literal_map = {
  156.    [ "true"  ] = true,
  157.    [ "false" ] = false,
  158.    [ "null"  ] = nil,
  159. }
  160.  
  161.  
  162. local function next_char(str, idx, set, negate)
  163.    for i = idx, #str do
  164.       if set[str:sub(i, i)] ~= negate then
  165.          return i
  166.       end
  167.    end
  168.    return #str + 1
  169. end
  170.  
  171.  
  172. local function decode_error(str, idx, msg)
  173.    local line_count = 1
  174.    local col_count = 1
  175.    for i = 1, idx - 1 do
  176.       col_count = col_count + 1
  177.       if str:sub(i, i) == "\n" then
  178.          line_count = line_count + 1
  179.          col_count = 1
  180.       end
  181.    end
  182.    error( string.format("%s at line %d col %d", msg, line_count, col_count) )
  183. end
  184.  
  185.  
  186. local function codepoint_to_utf8(n)
  187.    -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
  188.    local f = math.floor
  189.    if n <= 0x7f then
  190.       return string.char(n)
  191.    elseif n <= 0x7ff then
  192.       return string.char(f(n / 64) + 192, n % 64 + 128)
  193.    elseif n <= 0xffff then
  194.       return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
  195.    elseif n <= 0x10ffff then
  196.       return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
  197.                                   f(n % 4096 / 64) + 128, n % 64 + 128)
  198.    end
  199.    error( string.format("invalid unicode codepoint '%x'", n) )
  200. end
  201.  
  202.  
  203. local function parse_unicode_escape(s)
  204.    local n1 = tonumber( s:sub(3, 6),  16 )
  205.    local n2 = tonumber( s:sub(9, 12), 16 )
  206.    -- Surrogate pair?
  207.    if n2 then
  208.       return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
  209.    else
  210.       return codepoint_to_utf8(n1)
  211.    end
  212. end
  213.  
  214.  
  215. local function parse_string(str, i)
  216.    local has_unicode_escape = false
  217.    local has_surrogate_escape = false
  218.    local has_escape = false
  219.    local last
  220.    for j = i + 1, #str do
  221.       local x = str:byte(j)
  222.  
  223.       if x < 32 then
  224.          decode_error(str, j, "control character in string")
  225.       end
  226.  
  227.       if last == 92 then -- "\\" (escape char)
  228.          if x == 117 then -- "u" (unicode escape sequence)
  229.             local hex = str:sub(j + 1, j + 5)
  230.             if not hex:find("%x%x%x%x") then
  231.                decode_error(str, j, "invalid unicode escape in string")
  232.             end
  233.             if hex:find("^[dD][89aAbB]") then
  234.                has_surrogate_escape = true
  235.             else
  236.                has_unicode_escape = true
  237.             end
  238.          else
  239.             local c = string.char(x)
  240.             if not escape_chars[c] then
  241.                decode_error(str, j, "invalid escape char '" .. c .. "' in string")
  242.             end
  243.             has_escape = true
  244.          end
  245.          last = nil
  246.  
  247.       elseif x == 34 then -- '"' (end of string)
  248.          local s = str:sub(i + 1, j - 1)
  249.          if has_surrogate_escape then
  250.             s = s:gsub("\\u[dD][89aAbB]..\\u....", parse_unicode_escape)
  251.          end
  252.          if has_unicode_escape then
  253.             s = s:gsub("\\u....", parse_unicode_escape)
  254.          end
  255.          if has_escape then
  256.             s = s:gsub("\\.", escape_char_map_inv)
  257.          end
  258.          return s, j + 1
  259.  
  260.       else
  261.          last = x
  262.       end
  263.    end
  264.    decode_error(str, i, "expected closing quote for string")
  265. end
  266.  
  267.  
  268. local function parse_number(str, i)
  269.    local x = next_char(str, i, delim_chars)
  270.    local s = str:sub(i, x - 1)
  271.    local n = tonumber(s)
  272.    if not n then
  273.       decode_error(str, i, "invalid number '" .. s .. "'")
  274.    end
  275.    return n, x
  276. end
  277.  
  278.  
  279. local function parse_literal(str, i)
  280.    local x = next_char(str, i, delim_chars)
  281.    local word = str:sub(i, x - 1)
  282.    if not literals[word] then
  283.       decode_error(str, i, "invalid literal '" .. word .. "'")
  284.    end
  285.    return literal_map[word], x
  286. end
  287.  
  288.  
  289. local function parse_array(str, i)
  290.    local res = {}
  291.    local n = 1
  292.    i = i + 1
  293.    while 1 do
  294.       local x
  295.       i = next_char(str, i, space_chars, true)
  296.       -- Empty / end of array?
  297.       if str:sub(i, i) == "]" then
  298.          i = i + 1
  299.          break
  300.       end
  301.       -- Read token
  302.       x, i = parse(str, i)
  303.       res[n] = x
  304.       n = n + 1
  305.       -- Next token
  306.       i = next_char(str, i, space_chars, true)
  307.       local chr = str:sub(i, i)
  308.       i = i + 1
  309.       if chr == "]" then break end
  310.       if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
  311.    end
  312.    return res, i
  313. end
  314.  
  315.  
  316. local function parse_object(str, i)
  317.    local res = {}
  318.    i = i + 1
  319.    while 1 do
  320.       local key, val
  321.       i = next_char(str, i, space_chars, true)
  322.       -- Empty / end of object?
  323.       if str:sub(i, i) == "}" then
  324.          i = i + 1
  325.          break
  326.       end
  327.       -- Read key
  328.       if str:sub(i, i) ~= '"' then
  329.          decode_error(str, i, "expected string for key")
  330.       end
  331.       key, i = parse(str, i)
  332.       -- Read ':' delimiter
  333.       i = next_char(str, i, space_chars, true)
  334.       if str:sub(i, i) ~= ":" then
  335.          decode_error(str, i, "expected ':' after key")
  336.       end
  337.       i = next_char(str, i + 1, space_chars, true)
  338.       -- Read value
  339.       val, i = parse(str, i)
  340.       -- Set
  341.       res[key] = val
  342.       -- Next token
  343.       i = next_char(str, i, space_chars, true)
  344.       local chr = str:sub(i, i)
  345.       i = i + 1
  346.       if chr == "}" then break end
  347.       if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
  348.    end
  349.    return res, i
  350. end
  351.  
  352.  
  353. local char_func_map = {
  354.    [ '"' ] = parse_string,
  355.    [ "0" ] = parse_number,
  356.    [ "1" ] = parse_number,
  357.    [ "2" ] = parse_number,
  358.    [ "3" ] = parse_number,
  359.    [ "4" ] = parse_number,
  360.    [ "5" ] = parse_number,
  361.    [ "6" ] = parse_number,
  362.    [ "7" ] = parse_number,
  363.    [ "8" ] = parse_number,
  364.    [ "9" ] = parse_number,
  365.    [ "-" ] = parse_number,
  366.    [ "t" ] = parse_literal,
  367.    [ "f" ] = parse_literal,
  368.    [ "n" ] = parse_literal,
  369.    [ "[" ] = parse_array,
  370.    [ "{" ] = parse_object,
  371. }
  372.  
  373.  
  374. parse = function(str, idx)
  375.    local chr = str:sub(idx, idx)
  376.    local f = char_func_map[chr]
  377.    if f then
  378.       return f(str, idx)
  379.    end
  380.    decode_error(str, idx, "unexpected character '" .. chr .. "'")
  381. end
  382.  
  383.  
  384. function json.decode(str)
  385.    if type(str) ~= "string" then
  386.       error("expected argument of type string, got " .. type(str))
  387.    end
  388.    local res, idx = parse(str, next_char(str, 1, space_chars, true))
  389.    idx = next_char(str, idx, space_chars, true)
  390.    if idx <= #str then
  391.       decode_error(str, idx, "trailing garbage")
  392.    end
  393.    return res
  394. end
  395.  
  396.  
  397. return json
Tags: ORMS
Add Comment
Please, Sign In to add comment