marshal.nim 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module contains procs for `serialization`:idx: and `deserialization`:idx:
  10. ## of arbitrary Nim data structures. The serialization format uses `JSON`:idx:.
  11. ##
  12. ## **Restriction:** For objects, their type is **not** serialized. This means
  13. ## essentially that it does not work if the object has some other runtime
  14. ## type than its compiletime type.
  15. ##
  16. ##
  17. ## Basic usage
  18. ## ===========
  19. ##
  20. runnableExamples:
  21. type
  22. A = object of RootObj
  23. B = object of A
  24. f: int
  25. let a: ref A = new(B)
  26. assert $$a[] == "{}" # not "{f: 0}"
  27. # unmarshal
  28. let c = to[B]("""{"f": 2}""")
  29. assert typeof(c) is B
  30. assert c.f == 2
  31. # marshal
  32. assert $$c == """{"f": 2}"""
  33. ## **Note:** The `to` and `$$` operations are available at compile-time!
  34. ##
  35. ##
  36. ## See also
  37. ## ========
  38. ## * `streams module <streams.html>`_
  39. ## * `json module <json.html>`_
  40. const unsupportedPlatform =
  41. when defined(js): "javascript"
  42. elif defined(nimscript): "nimscript"
  43. else: ""
  44. when unsupportedPlatform != "":
  45. {.error: "marshal module is not supported in " & unsupportedPlatform & """.
  46. Please use alternative packages for serialization.
  47. It is possible to reimplement this module using generics and type traits.
  48. Please contribute a new implementation.""".}
  49. import streams, typeinfo, json, intsets, tables, unicode
  50. proc ptrToInt(x: pointer): int {.inline.} =
  51. result = cast[int](x) # don't skip alignment
  52. proc storeAny(s: Stream, a: Any, stored: var IntSet) =
  53. case a.kind
  54. of akNone: assert false
  55. of akBool: s.write($getBool(a))
  56. of akChar:
  57. let ch = getChar(a)
  58. if ch < '\128':
  59. s.write(escapeJson($ch))
  60. else:
  61. s.write($int(ch))
  62. of akArray, akSequence:
  63. s.write("[")
  64. for i in 0 .. a.len-1:
  65. if i > 0: s.write(", ")
  66. storeAny(s, a[i], stored)
  67. s.write("]")
  68. of akObject, akTuple:
  69. s.write("{")
  70. var i = 0
  71. for key, val in fields(a):
  72. if i > 0: s.write(", ")
  73. s.write(escapeJson(key))
  74. s.write(": ")
  75. storeAny(s, val, stored)
  76. inc(i)
  77. s.write("}")
  78. of akSet:
  79. s.write("[")
  80. var i = 0
  81. for e in elements(a):
  82. if i > 0: s.write(", ")
  83. s.write($e)
  84. inc(i)
  85. s.write("]")
  86. of akRange: storeAny(s, skipRange(a), stored)
  87. of akEnum: s.write(getEnumField(a).escapeJson)
  88. of akPtr, akRef:
  89. var x = a.getPointer
  90. if isNil(x): s.write("null")
  91. elif stored.containsOrIncl(x.ptrToInt):
  92. # already stored, so we simply write out the pointer as an int:
  93. s.write($x.ptrToInt)
  94. else:
  95. # else as a [value, key] pair:
  96. # (reversed order for convenient x[0] access!)
  97. s.write("[")
  98. s.write($x.ptrToInt)
  99. s.write(", ")
  100. storeAny(s, a[], stored)
  101. s.write("]")
  102. of akProc, akPointer, akCString: s.write($a.getPointer.ptrToInt)
  103. of akString:
  104. var x = getString(a)
  105. if x.validateUtf8() == -1: s.write(escapeJson(x))
  106. else:
  107. s.write("[")
  108. var i = 0
  109. for c in x:
  110. if i > 0: s.write(", ")
  111. s.write($ord(c))
  112. inc(i)
  113. s.write("]")
  114. of akInt..akInt64, akUInt..akUInt64: s.write($getBiggestInt(a))
  115. of akFloat..akFloat128: s.write($getBiggestFloat(a))
  116. proc loadAny(p: var JsonParser, a: Any, t: var Table[BiggestInt, pointer]) =
  117. case a.kind
  118. of akNone: assert false
  119. of akBool:
  120. case p.kind
  121. of jsonFalse: setBiggestInt(a, 0)
  122. of jsonTrue: setBiggestInt(a, 1)
  123. else: raiseParseErr(p, "'true' or 'false' expected for a bool")
  124. next(p)
  125. of akChar:
  126. if p.kind == jsonString:
  127. var x = p.str
  128. if x.len == 1:
  129. setBiggestInt(a, ord(x[0]))
  130. next(p)
  131. return
  132. elif p.kind == jsonInt:
  133. setBiggestInt(a, getInt(p))
  134. next(p)
  135. return
  136. raiseParseErr(p, "string of length 1 expected for a char")
  137. of akEnum:
  138. if p.kind == jsonString:
  139. setBiggestInt(a, getEnumOrdinal(a, p.str))
  140. next(p)
  141. return
  142. raiseParseErr(p, "string expected for an enum")
  143. of akArray:
  144. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for an array")
  145. next(p)
  146. var i = 0
  147. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  148. loadAny(p, a[i], t)
  149. inc(i)
  150. if p.kind == jsonArrayEnd: next(p)
  151. else: raiseParseErr(p, "']' end of array expected")
  152. of akSequence:
  153. case p.kind
  154. of jsonNull:
  155. setPointer(a, nil)
  156. next(p)
  157. of jsonArrayStart:
  158. next(p)
  159. invokeNewSeq(a, 0)
  160. var i = 0
  161. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  162. extendSeq(a)
  163. loadAny(p, a[i], t)
  164. inc(i)
  165. if p.kind == jsonArrayEnd: next(p)
  166. else: raiseParseErr(p, "")
  167. else:
  168. raiseParseErr(p, "'[' expected for a seq")
  169. of akObject, akTuple:
  170. if a.kind == akObject: setObjectRuntimeType(a)
  171. if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
  172. next(p)
  173. while p.kind != jsonObjectEnd and p.kind != jsonEof:
  174. if p.kind != jsonString:
  175. raiseParseErr(p, "string expected for a field name")
  176. var fieldName = p.str
  177. next(p)
  178. loadAny(p, a[fieldName], t)
  179. if p.kind == jsonObjectEnd: next(p)
  180. else: raiseParseErr(p, "'}' end of object expected")
  181. of akSet:
  182. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
  183. next(p)
  184. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  185. if p.kind != jsonInt: raiseParseErr(p, "int expected for a set")
  186. inclSetElement(a, p.getInt.int)
  187. next(p)
  188. if p.kind == jsonArrayEnd: next(p)
  189. else: raiseParseErr(p, "']' end of array expected")
  190. of akPtr, akRef:
  191. case p.kind
  192. of jsonNull:
  193. setPointer(a, nil)
  194. next(p)
  195. of jsonInt:
  196. setPointer(a, t.getOrDefault(p.getInt))
  197. next(p)
  198. of jsonArrayStart:
  199. next(p)
  200. if a.kind == akRef: invokeNew(a)
  201. else: setPointer(a, alloc0(a.baseTypeSize))
  202. if p.kind == jsonInt:
  203. t[p.getInt] = getPointer(a)
  204. next(p)
  205. else: raiseParseErr(p, "index for ref type expected")
  206. loadAny(p, a[], t)
  207. if p.kind == jsonArrayEnd: next(p)
  208. else: raiseParseErr(p, "']' end of ref-address pair expected")
  209. else: raiseParseErr(p, "int for pointer type expected")
  210. of akProc, akPointer, akCString:
  211. case p.kind
  212. of jsonNull:
  213. setPointer(a, nil)
  214. next(p)
  215. of jsonInt:
  216. setPointer(a, cast[pointer](p.getInt.int))
  217. next(p)
  218. else: raiseParseErr(p, "int for pointer type expected")
  219. of akString:
  220. case p.kind
  221. of jsonNull:
  222. setPointer(a, nil)
  223. next(p)
  224. of jsonString:
  225. setString(a, p.str)
  226. next(p)
  227. of jsonArrayStart:
  228. next(p)
  229. var str = ""
  230. while p.kind == jsonInt:
  231. let code = p.getInt()
  232. if code < 0 or code > 255:
  233. raiseParseErr(p, "invalid charcode: " & $code)
  234. str.add(chr(code))
  235. next(p)
  236. if p.kind == jsonArrayEnd: next(p)
  237. else: raiseParseErr(p, "an array of charcodes expected for string")
  238. setString(a, str)
  239. else: raiseParseErr(p, "string expected")
  240. of akInt..akInt64, akUInt..akUInt64:
  241. if p.kind == jsonInt:
  242. setBiggestInt(a, getInt(p))
  243. next(p)
  244. return
  245. raiseParseErr(p, "int expected")
  246. of akFloat..akFloat128:
  247. if p.kind == jsonFloat:
  248. setBiggestFloat(a, getFloat(p))
  249. next(p)
  250. return
  251. raiseParseErr(p, "float expected")
  252. of akRange: loadAny(p, a.skipRange, t)
  253. proc loadAny(s: Stream, a: Any, t: var Table[BiggestInt, pointer]) =
  254. var p: JsonParser
  255. open(p, s, "unknown file")
  256. next(p)
  257. loadAny(p, a, t)
  258. close(p)
  259. proc load*[T](s: Stream, data: var T) =
  260. ## Loads `data` from the stream `s`. Raises `IOError` in case of an error.
  261. runnableExamples:
  262. import std/streams
  263. var s = newStringStream("[1, 3, 5]")
  264. var a: array[3, int]
  265. load(s, a)
  266. assert a == [1, 3, 5]
  267. var tab = initTable[BiggestInt, pointer]()
  268. loadAny(s, toAny(data), tab)
  269. proc store*[T](s: Stream, data: T) =
  270. ## Stores `data` into the stream `s`. Raises `IOError` in case of an error.
  271. runnableExamples:
  272. import std/streams
  273. var s = newStringStream("")
  274. var a = [1, 3, 5]
  275. store(s, a)
  276. s.setPosition(0)
  277. assert s.readAll() == "[1, 3, 5]"
  278. var stored = initIntSet()
  279. var d: T
  280. shallowCopy(d, data)
  281. storeAny(s, toAny(d), stored)
  282. proc `$$`*[T](x: T): string =
  283. ## Returns a string representation of `x` (serialization, marshalling).
  284. ##
  285. ## **Note:** to serialize `x` to JSON use `%x` from the `json` module
  286. ## or `jsonutils.toJson(x)`.
  287. runnableExamples:
  288. type
  289. Foo = object
  290. id: int
  291. bar: string
  292. let x = Foo(id: 1, bar: "baz")
  293. ## serialize:
  294. let y = $$x
  295. assert y == """{"id": 1, "bar": "baz"}"""
  296. var stored = initIntSet()
  297. var d: T
  298. shallowCopy(d, x)
  299. var s = newStringStream()
  300. storeAny(s, toAny(d), stored)
  301. result = s.data
  302. proc to*[T](data: string): T =
  303. ## Reads data and transforms it to a type `T` (deserialization, unmarshalling).
  304. runnableExamples:
  305. type
  306. Foo = object
  307. id: int
  308. bar: string
  309. let y = """{"id": 1, "bar": "baz"}"""
  310. assert typeof(y) is string
  311. ## deserialize to type 'Foo':
  312. let z = y.to[:Foo]
  313. assert typeof(z) is Foo
  314. assert z.id == 1
  315. assert z.bar == "baz"
  316. var tab = initTable[BiggestInt, pointer]()
  317. loadAny(newStringStream(data), toAny(result), tab)