Merge with trunk
[prosody.git] / util / serialization.lua
1 -- Prosody IM
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 local next = next;
17
18 local debug_traceback = debug.traceback;
19 local log = require "util.logger".init("serialization");
20 module "serialization"
21
22 local indent = function(i)
23         return string_rep("\t", i);
24 end
25 local function basicSerialize (o)
26         if type(o) == "number" or type(o) == "boolean" then
27                 return tostring(o);
28         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
29                 return (("%q"):format(tostring(o)):gsub("\\\n", "\\n"));
30         end
31 end
32 local function _simplesave(o, ind, t, func)
33         if type(o) == "number" then
34                 func(t, tostring(o));
35         elseif type(o) == "string" then
36                 func(t, (("%q"):format(o):gsub("\\\n", "\\n")));
37         elseif type(o) == "table" then
38                 if next(o) then
39                         func(t, "{\n");
40                         for k,v in pairs(o) do
41                                 func(t, indent(ind));
42                                 func(t, "[");
43                                 func(t, basicSerialize(k));
44                                 func(t, "] = ");
45                                 if ind == 0 then
46                                         _simplesave(v, 0, t, func);
47                                 else
48                                         _simplesave(v, ind+1, t, func);
49                                 end
50                                 func(t, ";\n");
51                         end
52                         func(t, indent(ind-1));
53                         func(t, "}");
54                 else
55                         func(t, "{}");
56                 end
57         elseif type(o) == "boolean" then
58                 func(t, (o and "true" or "false"));
59         else
60                 log("error", "cannot serialize a %s: %s", type(o), debug_traceback())
61                 func(t, "nil");
62         end
63 end
64
65 function append(t, o)
66         _simplesave(o, 1, t, t.write or t_insert);
67         return t;
68 end
69
70 function serialize(o)
71         return t_concat(append({}, o));
72 end
73
74 function deserialize(str)
75         error("Not implemented");
76 end
77
78 return _M;