serialization.lua

changeset 0
11a0cbd6c216
equal deleted inserted replaced
-1:000000000000 0:11a0cbd6c216
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 module "serialization"
18
19 local indent = function(i)
20 return string_rep("\t", i);
21 end
22 local function basicSerialize (o)
23 if type(o) == "number" or type(o) == "boolean" then
24 return tostring(o);
25 else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
26 return (("%q"):format(tostring(o)):gsub("\\\n", "\\n"));
27 end
28 end
29 local function _simplesave(o, ind, t, func)
30 if type(o) == "number" then
31 func(t, tostring(o));
32 elseif type(o) == "string" then
33 func(t, (("%q"):format(o):gsub("\\\n", "\\n")));
34 elseif type(o) == "table" then
35 func(t, "{\n");
36 for k,v in pairs(o) do
37 func(t, indent(ind));
38 func(t, "[");
39 func(t, basicSerialize(k));
40 func(t, "] = ");
41 if ind == 0 then
42 _simplesave(v, 0, t, func);
43 else
44 _simplesave(v, ind+1, t, func);
45 end
46 func(t, ",\n");
47 end
48 func(t, indent(ind-1));
49 func(t, "}");
50 elseif type(o) == "boolean" then
51 func(t, (o and "true" or "false"));
52 else
53 error("cannot serialize a " .. type(o))
54 end
55 end
56
57 function append(t, o)
58 _simplesave(o, 1, t, t.write or t_insert);
59 return t;
60 end
61
62 function serialize(o)
63 return t_concat(append({}, o));
64 end
65
66 function deserialize(str)
67 error("Not implemented");
68 end
69
70 return _M;

mercurial