Added module util.serialization
[prosody.git] / tools / serialize.lua
1 -- Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 --
19
20
21 \r
22 local indent = function(i)\r
23         return string.rep("\t", i);\r
24 end\r
25 local function basicSerialize (o)\r
26         if type(o) == "number" or type(o) == "boolean" then\r
27                 return tostring(o);\r
28         else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.\r
29                 return (string.format("%q", tostring(o)):gsub("\\\n", "\\n"));\r
30         end\r
31 end\r
32 local function _simplesave (o, ind, t)\r
33         if type(o) == "number" then\r
34                 table.insert(t, tostring(o));\r
35         elseif type(o) == "string" then\r
36                 table.insert(t, (string.format("%q", o):gsub("\\\n", "\\n")));\r
37         elseif type(o) == "table" then\r
38                 table.insert(t, "{\n");\r
39                 for k,v in pairs(o) do\r
40                         table.insert(t, indent(ind));\r
41                         table.insert(t, "[");\r
42                         table.insert(t, basicSerialize(k));\r
43                         table.insert(t, "] = ");\r
44                         _simplesave(v, ind+1, t);\r
45                         table.insert(t, ",\n");\r
46                 end\r
47                 table.insert(t, indent(ind-1));\r
48                 table.insert(t, "}");\r
49         elseif type(o) == "boolean" then\r
50                 table.insert(t, (o and "true" or "false"));\r
51         else\r
52                 error("cannot serialize a " .. type(o))\r
53         end\r
54 end\r
55 local t_concat = table.concat;\r
56 \r
57 module "serialize"\r
58 \r
59 function serialize(o)\r
60         local t = {};\r
61         _simplesave(o, 1, t);\r
62         return t_concat(t);\r
63 end\r
64 \r
65 return _M;\r