Added check to prevent sparse arrays > 100 getting through

pull/28/head
Milind Gupta 2023-11-24 21:41:40 -08:00
parent f521e4ac03
commit 75127d2c7d
1 changed files with 34 additions and 33 deletions

View File

@ -57,18 +57,19 @@ end
local function encode_table(val, stack) local function encode_table(val, stack)
local res = {} local res = {}
stack = stack or {} stack = stack or {}
-- Circular reference? -- Circular reference?
if stack[val] then error("circular reference") end if stack[val] then error("circular reference") end
stack[val] = true stack[val] = true
-- Check whether to treat as a array or object -- Check whether to treat as a array or object
local array = true local array = true
local length = 0 local length = 0
local nLen = 0 local nLen = 0
for k,v in pairs(val) do local count = 0
for k,v in pairs(val) do
if (type(k) ~= "number" or k<=0) and not (k == "n" and type(v) == "number") then if (type(k) ~= "number" or k<=0) and not (k == "n" and type(v) == "number") then
array = nil array = nil
break -- Treat as object break -- Treat as object
@ -79,33 +80,33 @@ local function encode_table(val, stack)
if k == "n" and type(v) == "number" then if k == "n" and type(v) == "number" then
nLen = v nLen = v
end end
count = count + 1
end end
end end
if array then if nLen > length then
if nLen > length then length = nLen
length = nLen end
if array and not (length > 100 and count ~= length) then -- Check Array detected but sparse > 100 length then treat as object
-- Encode
for i=1,length do
table.insert(res, encode(val[i], stack))
end end
-- Encode stack[val] = nil
for i=1,length do return "[" .. table.concat(res, ",") .. "]"
table.insert(res, encode(val[i], stack)) else
end -- Treat as an object
stack[val] = nil for k, v in pairs(val) do
return "[" .. table.concat(res, ",") .. "]" --[[
if type(k) ~= "string" then
else error("invalid table: mixed or invalid key types")
-- Treat as an object end
for k, v in pairs(val) do ]]
--[[ table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
if type(k) ~= "string" then end
error("invalid table: mixed or invalid key types") stack[val] = nil
end return "{" .. table.concat(res, ",") .. "}"
]] end
table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
end
stack[val] = nil
return "{" .. table.concat(res, ",") .. "}"
end
end end