Skip to content

Commit

Permalink
Added checking and tests for trailing garbage when decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
rxi committed Mar 10, 2018
1 parent 19cc024 commit eb6e343
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
7 changes: 6 additions & 1 deletion json.lua
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,12 @@ function json.decode(str)
if type(str) ~= "string" then
error("expected argument of type string, got " .. type(str))
end
return ( parse(str, next_char(str, 1, space_chars, true)) )
local res, idx = parse(str, next_char(str, 1, space_chars, true))
idx = next_char(str, idx, space_chars, true)
if idx <= #str then
decode_error(str, idx, "trailing garbage")
end
return res
end


Expand Down
6 changes: 3 additions & 3 deletions test/test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ end)

test("literals", function()
assert( json.decode("true") == true )
assert( json.encode(true) == "true" )
assert( json.encode(true) == "true" )
assert( json.decode("false") == false )
assert( json.encode(false) == "false" )
assert( json.decode("null") == nil )
Expand Down Expand Up @@ -125,6 +125,8 @@ test("decode invalid", function()
'{]',
'[}',
'"a',
'10 xx',
'{}123'
}
for i, v in ipairs(t) do
local status = pcall(json.decode, v)
Expand Down Expand Up @@ -234,5 +236,3 @@ test("encode escape", function()
assert( res == v, fmt("'%s' was not escaped properly", k) )
end
end)


0 comments on commit eb6e343

Please sign in to comment.