From 82a5a0872fdcee785df602af987754c631b19f0e Mon Sep 17 00:00:00 2001 From: Thomas Harning Jr Date: Wed, 6 Aug 2008 01:22:11 -0400 Subject: [PATCH] decoder/tests: Added hex decode capability --- src/json/decode/number.lua | 11 +++++++++-- tests/lunit-numbers.lua | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/json/decode/number.lua b/src/json/decode/number.lua index 983d529..8405b91 100644 --- a/src/json/decode/number.lua +++ b/src/json/decode/number.lua @@ -24,12 +24,14 @@ local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits local nan = lpeg.S("Nn") * lpeg.S("Aa") * lpeg.S("Nn") local inf = (lpeg.P('-') + 0) * lpeg.S("Ii") * lpeg.P("nfinity") +local hex = (lpeg.P("0x") + lpeg.P("0X")) * lpeg.R("09","AF","af")^1 local defaultOptions = { nan = true, inf = true, frac = true, - exp = true + exp = true, + hex = false } default = {} @@ -50,7 +52,12 @@ strict = { ]] function buildMatch(options) options = util.merge({}, defaultOptions, options) - local ret = options.strict and strictInt or int + local ret + if options.hex then + ret = hex + (options.strict and strictInt or int) + else + ret = options.strict and strictInt or int + end if options.frac then ret = ret * (frac + 0) end diff --git a/tests/lunit-numbers.lua b/tests/lunit-numbers.lua index 807da9d..8c3bd8a 100644 --- a/tests/lunit-numbers.lua +++ b/tests/lunit-numbers.lua @@ -82,6 +82,39 @@ end local strict = json.decode.util.merge({}, json.decode.strict, {initialObject = false}) local strictDecoder = json.decode.getDecoder(strict) +local numberValue = json.decode.util.merge({}, json.decode.number.default, {hex = true}) + +local hex = json.decode.util.merge({}, json.decode.default, {number = numberValue}) +local hexDecoder = json.decode.getDecoder(hex) + +function test_hex() + if decode == hexDecoder then -- MUST SKIP FAIL UNTIL BETTER METHOD SETUP + return + end + assert_error(function() + decode("0x20") + end) +end + +local hexNumbers = { + 0xDEADBEEF, + 0xCAFEBABE, + 0x00000000, + 0xFFFFFFFF, + 0xCE, + 0x01 +} + +function test_hex_only() + _G["decode"] = hexDecoder + for _, v in ipairs(hexNumbers) do + assert_equal(v, decode(("0x%x"):format(v))) + assert_equal(v, decode(("0X%X"):format(v))) + assert_equal(v, decode(("0x%X"):format(v))) + assert_equal(v, decode(("0X%x"):format(v))) + end +end + local function buildStrictDecoder(f) return testutil.buildPatchedDecoder(f, strictDecoder) end @@ -90,11 +123,12 @@ local function buildFailedStrictDecoder(f) end -- SETUP CHECKS FOR SEQUENCE OF DECODERS for k, v in pairs(_M) do - if k:match("^test_") and not k:match("_gen$") then + if k:match("^test_") and not k:match("_gen$") and not k:match("_only$") then if k:match("_nostrict") then _M[k .. "_strict_gen"] = buildFailedStrictDecoder(v) else _M[k .. "_strict_gen"] = buildStrictDecoder(v) end + _M[k .. "_hex_gen"] = testutil.buildPatchedDecoder(v, hexDecoder) end end \ No newline at end of file -- 2.11.4.GIT