2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local string_rep = string.rep;
11 local tostring = tostring;
12 local t_insert = table.insert;
13 local t_concat = table.concat;
18 local loadstring = loadstring;
21 local debug_traceback = debug.traceback;
22 local log = require "util.logger".init("serialization");
23 local envload = require"util.envload".envload;
25 module "serialization"
27 local indent = function(i)
28 return string_rep("\t", i);
30 local function basicSerialize (o)
31 if type(o) == "number" or type(o) == "boolean" then
32 -- no need to check for NaN, as that's not a valid table index
33 if o == 1/0 then return "(1/0)";
34 elseif o == -1/0 then return "(-1/0)";
35 else return tostring(o); end
36 else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
37 return (("%q"):format(tostring(o)):gsub("\\\n", "\\n"));
40 local function _simplesave(o, ind, t, func)
41 if type(o) == "number" then
42 if o ~= o then func(t, "(0/0)");
43 elseif o == 1/0 then func(t, "(1/0)");
44 elseif o == -1/0 then func(t, "(-1/0)");
45 else func(t, tostring(o)); end
46 elseif type(o) == "string" then
47 func(t, (("%q"):format(o):gsub("\\\n", "\\n")));
48 elseif type(o) == "table" then
49 if next(o) ~= nil then
51 for k,v in pairs(o) do
54 func(t, basicSerialize(k));
57 _simplesave(v, 0, t, func);
59 _simplesave(v, ind+1, t, func);
63 func(t, indent(ind-1));
68 elseif type(o) == "boolean" then
69 func(t, (o and "true" or "false"));
71 log("error", "cannot serialize a %s: %s", type(o), debug_traceback())
77 _simplesave(o, 1, t, t.write or t_insert);
82 return t_concat(append({}, o));
85 function deserialize(str)
86 if type(str) ~= "string" then return nil; end
88 local f, err = envload(str, "@data", {});
89 if not f then return nil, err; end
90 local success, ret = pcall(f);
91 if not success then return nil, ret; end