|
| 1 | +local ngx_null = ngx.null |
| 2 | +local tostring = tostring |
| 3 | +local byte = string.byte |
| 4 | +local gsub = string.gsub |
| 5 | +local sort = table.sort |
| 6 | +local pairs = pairs |
| 7 | +local ipairs = ipairs |
| 8 | +local concat = table.concat |
| 9 | + |
| 10 | +local ok, new_tab = pcall(require, "table.new") |
| 11 | +if not ok then |
| 12 | + new_tab = function (narr, nrec) return {} end |
| 13 | +end |
| 14 | + |
| 15 | +local _M = {} |
| 16 | + |
| 17 | +local metachars = { |
| 18 | + ['\t'] = '\\t', |
| 19 | + ["\\"] = "\\\\", |
| 20 | + ['"'] = '\\"', |
| 21 | + ['\r'] = '\\r', |
| 22 | + ['\n'] = '\\n', |
| 23 | +} |
| 24 | + |
| 25 | +local function encode_str(s) |
| 26 | + -- XXX we will rewrite this when string.buffer is implemented |
| 27 | + -- in LuaJIT 2.1 because string.gsub cannot be JIT compiled. |
| 28 | + return gsub(s, '["\\\r\n\t]', metachars) |
| 29 | +end |
| 30 | + |
| 31 | +local function is_arr(t) |
| 32 | + local exp = 1 |
| 33 | + for k, _ in pairs(t) do |
| 34 | + if k ~= exp then |
| 35 | + return nil |
| 36 | + end |
| 37 | + exp = exp + 1 |
| 38 | + end |
| 39 | + return exp - 1 |
| 40 | +end |
| 41 | + |
| 42 | +local encode |
| 43 | + |
| 44 | +encode = function (v) |
| 45 | + if v == nil or v == ngx_null then |
| 46 | + return "null" |
| 47 | + end |
| 48 | + |
| 49 | + local typ = type(v) |
| 50 | + if typ == 'string' then |
| 51 | + return '"' .. encode_str(v) .. '"' |
| 52 | + end |
| 53 | + |
| 54 | + if typ == 'number' or typ == 'boolean' then |
| 55 | + return tostring(v) |
| 56 | + end |
| 57 | + |
| 58 | + if typ == 'table' then |
| 59 | + local n = is_arr(v) |
| 60 | + if n then |
| 61 | + local bits = new_tab(n, 0) |
| 62 | + for i, elem in ipairs(v) do |
| 63 | + bits[i] = encode(elem) |
| 64 | + end |
| 65 | + return "[" .. concat(bits, ",") .. "]" |
| 66 | + end |
| 67 | + |
| 68 | + local keys = {} |
| 69 | + local i = 0 |
| 70 | + for key, _ in pairs(v) do |
| 71 | + i = i + 1 |
| 72 | + keys[i] = key |
| 73 | + end |
| 74 | + sort(keys) |
| 75 | + |
| 76 | + local bits = new_tab(0, i) |
| 77 | + i = 0 |
| 78 | + for _, key in ipairs(keys) do |
| 79 | + i = i + 1 |
| 80 | + bits[i] = encode(key) .. ":" .. encode(v[key]) |
| 81 | + end |
| 82 | + return "{" .. concat(bits, ",") .. "}" |
| 83 | + end |
| 84 | + |
| 85 | + return '"<' .. typ .. '>"' |
| 86 | +end |
| 87 | +_M.encode = encode |
| 88 | + |
| 89 | +return _M |
0 commit comments