util/serialization.lua

changeset 546
1e65f64dfabf
child 615
4ae3e81513f3
equal deleted inserted replaced
542:c9dbfcf21846 546:1e65f64dfabf
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 local string_rep = string.rep;
21 local type = type;
22 local tostring = tostring;
23 local t_insert = table.insert;
24 local t_concat = table.concat;
25 local error = error;
26 local pairs = pairs;
27
28 module "serialization"
29
30 local indent = function(i)
31 return string_rep("\t", i);
32 end
33 local function basicSerialize (o)
34 if type(o) == "number" or type(o) == "boolean" then
35 return tostring(o);
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"));
38 end
39 end
40 local function _simplesave(o, ind, t, func)
41 if type(o) == "number" then
42 func(t, tostring(o));
43 elseif type(o) == "string" then
44 func(t, (("%q"):format(o):gsub("\\\n", "\\n")));
45 elseif type(o) == "table" then
46 func(t, "{\n");
47 for k,v in pairs(o) do
48 func(t, indent(ind));
49 func(t, "[");
50 func(t, basicSerialize(k));
51 func(t, "] = ");
52 if ind == 0 then
53 _simplesave(v, 0, t, func);
54 else
55 _simplesave(v, ind+1, t, func);
56 end
57 func(t, ",\n");
58 end
59 func(t, indent(ind-1));
60 func(t, "}");
61 elseif type(o) == "boolean" then
62 func(t, (o and "true" or "false"));
63 else
64 error("cannot serialize a " .. type(o))
65 end
66 end
67
68 function append(t, o)
69 _simplesave(o, 1, t, t.write or t_insert);
70 return t;
71 end
72
73 function serialize(o)
74 return t_concat(append({}, o));
75 end
76
77 function deserialize(str)
78 error("Not implemented");
79 end
80
81 return _M;

mercurial