File: number.lua

package info (click to toggle)
lua-json 1.3.4-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 688 kB
  • sloc: makefile: 71; php: 3
file content (58 lines) | stat: -rw-r--r-- 1,232 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
--[[
	Licensed according to the included 'LICENSE' document
	Author: Thomas Harning Jr <harningt@gmail.com>
]]
local tostring = tostring
local assert = assert
local jsonutil = require("json.util")
local huge = require("math").huge

local _ENV = nil

local defaultOptions = {
	nan = true,
	inf = true
}

local modeOptions = {}
modeOptions.strict = {
	nan = false,
	inf = false
}

local function mergeOptions(options, mode)
	jsonutil.doOptionMerge(options, false, 'number', defaultOptions, mode and modeOptions[mode])
end


local function encodeNumber(number, options)
	if number ~= number then
		assert(options.nan, "Invalid number: NaN not enabled")
		return "NaN"
	end
	if number == huge then
		assert(options.inf, "Invalid number: Infinity not enabled")
		return "Infinity"
	end
	if number == -huge then
		assert(options.inf, "Invalid number: Infinity not enabled")
		return "-Infinity"
	end
	return tostring(number)
end

local function getEncoder(options)
	options = options and jsonutil.merge({}, defaultOptions, options) or defaultOptions
	return {
		number = function(number, state)
			return encodeNumber(number, options)
		end
	}
end

local number = {
	mergeOptions = mergeOptions,
	getEncoder = getEncoder
}

return number