diff options
author | Kim Alvefur <zash@zash.se> | 2018-10-12 00:13:24 +0200 |
---|---|---|
committer | Kim Alvefur <zash@zash.se> | 2018-10-12 00:13:24 +0200 |
commit | a8b392165a21991c75ca25c8fb6e773943c88963 (patch) | |
tree | 4f5e21721be10dfd4d8f4737a132ed6ddf0dcf28 | |
parent | 86117bb2a23c3deaa2e733f390bb6ebdb49cb33b (diff) | |
download | prosody-a8b392165a21991c75ca25c8fb6e773943c88963.tar.gz prosody-a8b392165a21991c75ca25c8fb6e773943c88963.zip |
util.serialization: Simpler metatable pre-processing
It was too difficult to describe what it did.
-rw-r--r-- | spec/util_serialization_spec.lua | 8 | ||||
-rw-r--r-- | util/serialization.lua | 26 |
2 files changed, 20 insertions, 14 deletions
diff --git a/spec/util_serialization_spec.lua b/spec/util_serialization_spec.lua index 52075bc2..d22cf738 100644 --- a/spec/util_serialization_spec.lua +++ b/spec/util_serialization_spec.lua @@ -44,6 +44,14 @@ describe("util.serialization", function () test({foo={[100]={{"bar"},{baz=1}}}}); test({["goto"] = {["function"]={["do"]="keywords"}}}); end); + + it("can serialize with metatables", function () + local s = serialization.new({ freeze = true }); + local t = setmetatable({ a = "hi" }, { __freeze = function (t) return { t.a } end }); + local rt = serialization.deserialize(s(t)); + assert.same({"hi"}, rt); + end); + end); end); diff --git a/util/serialization.lua b/util/serialization.lua index f7f129b2..852b41da 100644 --- a/util/serialization.lua +++ b/util/serialization.lua @@ -139,25 +139,23 @@ local function new(opt) end o[t] = true; - if freeze then + + if freeze == true then -- opportunity to do pre-serialization local mt = getmetatable(t); - local fr = (type(freeze) == "table" and freeze[mt]); - local mf = mt and mt.__freeze; - local tag; - if type(fr) == "string" then - tag = fr; - fr = mf; - elseif mt then - tag = mt.__type; - end - if type(fr) == "function" then - t = fr(t); - if type(tag) == "string" then - o[l], l = tag, l + 1; + if type(mt) == "table" then + local tag = mt.__name; + local fr = mt.__freeze; + + if type(fr) == "function" then + t = fr(t); + if type(tag) == "string" then + o[l], l = tag, l + 1; + end end end end + o[l], l = tstart, l + 1; local indent = s_rep(indentwith, d); local numkey = 1; |