util/serialization: Fixed serialization formatting
[prosody.git] / util / serialization.lua
1 -- Prosody IM v0.4
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local string_rep = string.rep;
10 local type = type;
11 local tostring = tostring;
12 local t_insert = table.insert;
13 local t_concat = table.concat;
14 local error = error;
15 local pairs = pairs;
16
17 local debug_traceback = debug.traceback;
18 local log = require "util.logger".init("serialization");
19 module "serialization"
20
21 local indent = function(i)
22         return string_rep("\t", i);
23 end
24 local function basicSerialize (o)
25         if type(o) == "number" or type(o) == "boolean" then
26                 return tostring(o);
27         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
28                 return (("%q"):format(tostring(o)):gsub("\\\n", "\\n"));
29         end
30 end
31 local function _simplesave(o, ind, t, func)
32         if type(o) == "number" then
33                 func(t, tostring(o));
34         elseif type(o) == "string" then
35                 func(t, (("%q"):format(o):gsub("\\\n", "\\n")));
36         elseif type(o) == "table" then
37                 func(t, "{\n");
38                 for k,v in pairs(o) do
39                         func(t, indent(ind));
40                         func(t, "[");
41                         func(t, basicSerialize(k));
42                         func(t, "] = ");
43                         if ind == 0 then
44                                 _simplesave(v, 0, t, func);
45                         else
46                                 _simplesave(v, ind+1, t, func);
47                         end
48                         func(t, ",\n");
49                 end
50                 func(t, indent(ind-1));
51                 func(t, "}");
52         elseif type(o) == "boolean" then
53                 func(t, (o and "true" or "false"));
54         else
55                 log("error", "cannot serialize a %s: %s", type(o), debug_traceback())
56                 func(t, "nil");
57         end
58 end
59
60 function append(t, o)
61         _simplesave(o, 1, t, t.write or t_insert);
62         return t;
63 end
64
65 function serialize(o)
66         return t_concat(append({}, o));
67 end
68
69 function deserialize(str)
70         error("Not implemented");
71 end
72
73 return _M;