From cca1c798d20ff8c26344028add94c2fd1acf6b79 Mon Sep 17 00:00:00 2001 From: Guldoman Date: Wed, 18 Oct 2023 06:45:52 +0200 Subject: [PATCH] Improve `common.serialize` (#1640) * Make `common.serialize` more locale-independent * Handle inf/nan numbers in `common.serialize` --- data/core/common.lua | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/data/core/common.lua b/data/core/common.lua index 272f0d5d..a887c307 100644 --- a/data/core/common.lua +++ b/data/core/common.lua @@ -378,12 +378,15 @@ function common.bench(name, fn, ...) return res end +-- From gvx/Ser +local oddvals = {[tostring(1/0)] = "1/0", [tostring(-1/0)] = "-1/0", [tostring(-(0/0))] = "-(0/0)", [tostring(0/0)] = "0/0"} local function serialize(val, pretty, indent_str, escape, sort, limit, level) local space = pretty and " " or "" local indent = pretty and string.rep(indent_str, level) or "" local newline = pretty and "\n" or "" - if type(val) == "string" then + local ty = type(val) + if ty == "string" then local out = string.format("%q", val) if escape then out = string.gsub(out, "\\\n", "\\n") @@ -395,7 +398,7 @@ local function serialize(val, pretty, indent_str, escape, sort, limit, level) out = string.gsub(out, "\\13", "\\r") end return out - elseif type(val) == "table" then + elseif ty == "table" then -- early exit if level >= limit then return tostring(val) end local next_indent = pretty and (indent .. indent_str) or "" @@ -410,6 +413,12 @@ local function serialize(val, pretty, indent_str, escape, sort, limit, level) if sort then table.sort(t) end return "{" .. newline .. table.concat(t, "," .. newline) .. newline .. indent .. "}" end + if ty == "number" then + -- tostring is locale-dependent, so we need to replace an eventual `,` with `.` + local res, _ = tostring(val):gsub(",", ".") + -- handle inf/nan + return oddvals[res] or res + end return tostring(val) end