serialize.lua 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. --- Lua module to serialize values as Lua code.
  2. -- From: https://github.com/appgurueu/modlib/blob/master/luon.lua
  3. -- License: MIT
  4. local next, rawget, pairs, pcall, error, type, setfenv, loadstring
  5. = next, rawget, pairs, pcall, error, type, setfenv, loadstring
  6. local table_concat, string_dump, string_format, string_match, math_huge
  7. = table.concat, string.dump, string.format, string.match, math.huge
  8. -- Recursively counts occurences of objects (non-primitives including strings) in a table.
  9. local function count_objects(value)
  10. local counts = {}
  11. if value == nil then
  12. -- Early return for nil; tables can't contain nil
  13. return counts
  14. end
  15. local function count_values(val)
  16. local type_ = type(val)
  17. if type_ == "boolean" or type_ == "number" then
  18. return
  19. end
  20. local count = counts[val]
  21. counts[val] = (count or 0) + 1
  22. if type_ == "table" then
  23. if not count then
  24. for k, v in pairs(val) do
  25. count_values(k)
  26. count_values(v)
  27. end
  28. end
  29. elseif type_ ~= "string" and type_ ~= "function" then
  30. error("unsupported type: " .. type_)
  31. end
  32. end
  33. count_values(value)
  34. return counts
  35. end
  36. -- Build a "set" of Lua keywords. These can't be used as short key names.
  37. -- See https://www.lua.org/manual/5.1/manual.html#2.1
  38. local keywords = {}
  39. for _, keyword in pairs({
  40. "and", "break", "do", "else", "elseif",
  41. "end", "false", "for", "function", "if",
  42. "in", "local", "nil", "not", "or",
  43. "repeat", "return", "then", "true", "until", "while",
  44. "goto" -- LuaJIT, Lua 5.2+
  45. }) do
  46. keywords[keyword] = true
  47. end
  48. local function quote(string)
  49. return string_format("%q", string)
  50. end
  51. local function dump_func(func)
  52. return string_format("loadstring(%q)", string_dump(func))
  53. end
  54. -- Serializes Lua nil, booleans, numbers, strings, tables and even functions
  55. -- Tables are referenced by reference, strings are referenced by value. Supports circular tables.
  56. local function serialize(value, write)
  57. local reference, refnum = "r1", 1
  58. -- [object] = reference string
  59. local references = {}
  60. -- Circular tables that must be filled using `table[key] = value` statements
  61. local to_fill = {}
  62. for object, count in pairs(count_objects(value)) do
  63. local type_ = type(object)
  64. -- Object must appear more than once. If it is a string, the reference has to be shorter than the string.
  65. if count >= 2 and (type_ ~= "string" or #reference + 2 < #object) then
  66. write(reference)
  67. write("=")
  68. if type_ == "table" then
  69. write("{}")
  70. elseif type_ == "function" then
  71. write(dump_func(object))
  72. elseif type_ == "string" then
  73. write(quote(object))
  74. end
  75. write(";")
  76. references[object] = reference
  77. if type_ == "table" then
  78. to_fill[object] = reference
  79. end
  80. refnum = refnum + 1
  81. reference = ("r%X"):format(refnum)
  82. end
  83. end
  84. -- Used to decide whether we should do "key=..."
  85. local function use_short_key(key)
  86. return not references[key] and type(key) == "string" and (not keywords[key]) and string_match(key, "^[%a_][%a%d_]*$")
  87. end
  88. local function dump(value)
  89. -- Primitive types
  90. if value == nil then
  91. return write("nil")
  92. end
  93. if value == true then
  94. return write("true")
  95. end
  96. if value == false then
  97. return write("false")
  98. end
  99. local type_ = type(value)
  100. if type_ == "number" then
  101. return write(string_format("%.17g", value))
  102. end
  103. -- Reference types: table, function and string
  104. local ref = references[value]
  105. if ref then
  106. return write(ref)
  107. end
  108. if type_ == "string" then
  109. return write(quote(value))
  110. end
  111. if type_ == "function" then
  112. return write(dump_func(value))
  113. end
  114. if type_ == "table" then
  115. write("{")
  116. -- First write list keys:
  117. -- Don't use the table length #value here as it may horribly fail
  118. -- for tables which use large integers as keys in the hash part;
  119. -- stop at the first "hole" (nil value) instead
  120. local len = 0
  121. local first = true -- whether this is the first entry, which may not have a leading comma
  122. while true do
  123. local v = rawget(value, len + 1) -- use rawget to avoid metatables like the vector metatable
  124. if v == nil then break end
  125. if first then first = false else write(",") end
  126. dump(v)
  127. len = len + 1
  128. end
  129. -- Now write map keys ([key] = value)
  130. for k, v in next, value do
  131. -- We have written all non-float keys in [1, len] already
  132. if type(k) ~= "number" or k % 1 ~= 0 or k < 1 or k > len then
  133. if first then first = false else write(",") end
  134. if use_short_key(k) then
  135. write(k)
  136. else
  137. write("[")
  138. dump(k)
  139. write("]")
  140. end
  141. write("=")
  142. dump(v)
  143. end
  144. end
  145. write("}")
  146. return
  147. end
  148. end
  149. -- Write the statements to fill circular tables
  150. for table, ref in pairs(to_fill) do
  151. for k, v in pairs(table) do
  152. write(ref)
  153. if use_short_key(k) then
  154. write(".")
  155. write(k)
  156. else
  157. write("[")
  158. dump(k)
  159. write("]")
  160. end
  161. write("=")
  162. dump(v)
  163. write(";")
  164. end
  165. end
  166. write("return ")
  167. dump(value)
  168. end
  169. function core.serialize(value)
  170. local rope = {}
  171. serialize(value, function(text)
  172. -- Faster than table.insert(rope, text) on PUC Lua 5.1
  173. rope[#rope + 1] = text
  174. end)
  175. return table_concat(rope)
  176. end
  177. local function dummy_func() end
  178. local nan = (0/0)^1 -- +nan
  179. function core.deserialize(str, safe)
  180. local func, err = loadstring(str)
  181. if not func then return nil, err end
  182. -- math.huge is serialized to inf, NaNs are serialized to nan by Lua
  183. local env = {inf = math_huge, nan = nan}
  184. if safe then
  185. env.loadstring = dummy_func
  186. else
  187. env.loadstring = function(str, ...)
  188. local func, err = loadstring(str, ...)
  189. if func then
  190. setfenv(func, env)
  191. return func
  192. end
  193. return nil, err
  194. end
  195. end
  196. setfenv(func, env)
  197. local success, value_or_err = pcall(func)
  198. if success then
  199. return value_or_err
  200. end
  201. return nil, value_or_err
  202. end