marshal.nim 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. ## .. code-block:: nim
  21. ##
  22. ## type
  23. ## A = object of RootObj
  24. ## B = object of A
  25. ## f: int
  26. ##
  27. ## var
  28. ## a: ref A
  29. ## b: ref B
  30. ##
  31. ## new(b)
  32. ## a = b
  33. ## echo($$a[]) # produces "{}", not "{f: 0}"
  34. ##
  35. ## # unmarshal
  36. ## let c = to[B]("""{"f": 2}""")
  37. ## assert typeof(c) is B
  38. ## assert c.f == 2
  39. ##
  40. ## # marshal
  41. ## let s = $$c
  42. ## assert s == """{"f": 2}"""
  43. ##
  44. ## **Note**: The ``to`` and ``$$`` operations are available at compile-time!
  45. ##
  46. ##
  47. ## See also
  48. ## ========
  49. ## * `streams module <streams.html>`_
  50. ## * `json module <json.html>`_
  51. import streams, typeinfo, json, intsets, tables, unicode
  52. proc ptrToInt(x: pointer): int {.inline.} =
  53. result = cast[int](x) # don't skip alignment
  54. proc storeAny(s: Stream, a: Any, stored: var IntSet) =
  55. case a.kind
  56. of akNone: assert false
  57. of akBool: s.write($getBool(a))
  58. of akChar:
  59. let ch = getChar(a)
  60. if ch < '\128':
  61. s.write(escapeJson($ch))
  62. else:
  63. s.write($int(ch))
  64. of akArray, akSequence:
  65. s.write("[")
  66. for i in 0 .. a.len-1:
  67. if i > 0: s.write(", ")
  68. storeAny(s, a[i], stored)
  69. s.write("]")
  70. of akObject, akTuple:
  71. s.write("{")
  72. var i = 0
  73. for key, val in fields(a):
  74. if i > 0: s.write(", ")
  75. s.write(escapeJson(key))
  76. s.write(": ")
  77. storeAny(s, val, stored)
  78. inc(i)
  79. s.write("}")
  80. of akSet:
  81. s.write("[")
  82. var i = 0
  83. for e in elements(a):
  84. if i > 0: s.write(", ")
  85. s.write($e)
  86. inc(i)
  87. s.write("]")
  88. of akRange: storeAny(s, skipRange(a), stored)
  89. of akEnum: s.write(getEnumField(a).escapeJson)
  90. of akPtr, akRef:
  91. var x = a.getPointer
  92. if isNil(x): s.write("null")
  93. elif stored.containsOrIncl(x.ptrToInt):
  94. # already stored, so we simply write out the pointer as an int:
  95. s.write($x.ptrToInt)
  96. else:
  97. # else as a [value, key] pair:
  98. # (reversed order for convenient x[0] access!)
  99. s.write("[")
  100. s.write($x.ptrToInt)
  101. s.write(", ")
  102. storeAny(s, a[], stored)
  103. s.write("]")
  104. of akProc, akPointer, akCString: s.write($a.getPointer.ptrToInt)
  105. of akString:
  106. var x = getString(a)
  107. if x.validateUtf8() == -1: s.write(escapeJson(x))
  108. else:
  109. s.write("[")
  110. var i = 0
  111. for c in x:
  112. if i > 0: s.write(", ")
  113. s.write($ord(c))
  114. inc(i)
  115. s.write("]")
  116. of akInt..akInt64, akUInt..akUInt64: s.write($getBiggestInt(a))
  117. of akFloat..akFloat128: s.write($getBiggestFloat(a))
  118. proc loadAny(p: var JsonParser, a: Any, t: var Table[BiggestInt, pointer]) =
  119. case a.kind
  120. of akNone: assert false
  121. of akBool:
  122. case p.kind
  123. of jsonFalse: setBiggestInt(a, 0)
  124. of jsonTrue: setBiggestInt(a, 1)
  125. else: raiseParseErr(p, "'true' or 'false' expected for a bool")
  126. next(p)
  127. of akChar:
  128. if p.kind == jsonString:
  129. var x = p.str
  130. if x.len == 1:
  131. setBiggestInt(a, ord(x[0]))
  132. next(p)
  133. return
  134. elif p.kind == jsonInt:
  135. setBiggestInt(a, getInt(p))
  136. next(p)
  137. return
  138. raiseParseErr(p, "string of length 1 expected for a char")
  139. of akEnum:
  140. if p.kind == jsonString:
  141. setBiggestInt(a, getEnumOrdinal(a, p.str))
  142. next(p)
  143. return
  144. raiseParseErr(p, "string expected for an enum")
  145. of akArray:
  146. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for an array")
  147. next(p)
  148. var i = 0
  149. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  150. loadAny(p, a[i], t)
  151. inc(i)
  152. if p.kind == jsonArrayEnd: next(p)
  153. else: raiseParseErr(p, "']' end of array expected")
  154. of akSequence:
  155. case p.kind
  156. of jsonNull:
  157. setPointer(a, nil)
  158. next(p)
  159. of jsonArrayStart:
  160. next(p)
  161. invokeNewSeq(a, 0)
  162. var i = 0
  163. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  164. extendSeq(a)
  165. loadAny(p, a[i], t)
  166. inc(i)
  167. if p.kind == jsonArrayEnd: next(p)
  168. else: raiseParseErr(p, "")
  169. else:
  170. raiseParseErr(p, "'[' expected for a seq")
  171. of akObject, akTuple:
  172. if a.kind == akObject: setObjectRuntimeType(a)
  173. if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
  174. next(p)
  175. while p.kind != jsonObjectEnd and p.kind != jsonEof:
  176. if p.kind != jsonString:
  177. raiseParseErr(p, "string expected for a field name")
  178. var fieldName = p.str
  179. next(p)
  180. loadAny(p, a[fieldName], t)
  181. if p.kind == jsonObjectEnd: next(p)
  182. else: raiseParseErr(p, "'}' end of object expected")
  183. of akSet:
  184. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
  185. next(p)
  186. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  187. if p.kind != jsonInt: raiseParseErr(p, "int expected for a set")
  188. inclSetElement(a, p.getInt.int)
  189. next(p)
  190. if p.kind == jsonArrayEnd: next(p)
  191. else: raiseParseErr(p, "']' end of array expected")
  192. of akPtr, akRef:
  193. case p.kind
  194. of jsonNull:
  195. setPointer(a, nil)
  196. next(p)
  197. of jsonInt:
  198. setPointer(a, t.getOrDefault(p.getInt))
  199. next(p)
  200. of jsonArrayStart:
  201. next(p)
  202. if a.kind == akRef: invokeNew(a)
  203. else: setPointer(a, alloc0(a.baseTypeSize))
  204. if p.kind == jsonInt:
  205. t[p.getInt] = getPointer(a)
  206. next(p)
  207. else: raiseParseErr(p, "index for ref type expected")
  208. loadAny(p, a[], t)
  209. if p.kind == jsonArrayEnd: next(p)
  210. else: raiseParseErr(p, "']' end of ref-address pair expected")
  211. else: raiseParseErr(p, "int for pointer type expected")
  212. of akProc, akPointer, akCString:
  213. case p.kind
  214. of jsonNull:
  215. setPointer(a, nil)
  216. next(p)
  217. of jsonInt:
  218. setPointer(a, cast[pointer](p.getInt.int))
  219. next(p)
  220. else: raiseParseErr(p, "int for pointer type expected")
  221. of akString:
  222. case p.kind
  223. of jsonNull:
  224. setPointer(a, nil)
  225. next(p)
  226. of jsonString:
  227. setString(a, p.str)
  228. next(p)
  229. of jsonArrayStart:
  230. next(p)
  231. var str = ""
  232. while p.kind == jsonInt:
  233. let code = p.getInt()
  234. if code < 0 or code > 255:
  235. raiseParseErr(p, "invalid charcode: " & $code)
  236. str.add(chr(code))
  237. next(p)
  238. if p.kind == jsonArrayEnd: next(p)
  239. else: raiseParseErr(p, "an array of charcodes expected for string")
  240. setString(a, str)
  241. else: raiseParseErr(p, "string expected")
  242. of akInt..akInt64, akUInt..akUInt64:
  243. if p.kind == jsonInt:
  244. setBiggestInt(a, getInt(p))
  245. next(p)
  246. return
  247. raiseParseErr(p, "int expected")
  248. of akFloat..akFloat128:
  249. if p.kind == jsonFloat:
  250. setBiggestFloat(a, getFloat(p))
  251. next(p)
  252. return
  253. raiseParseErr(p, "float expected")
  254. of akRange: loadAny(p, a.skipRange, t)
  255. proc loadAny(s: Stream, a: Any, t: var Table[BiggestInt, pointer]) =
  256. var p: JsonParser
  257. open(p, s, "unknown file")
  258. next(p)
  259. loadAny(p, a, t)
  260. close(p)
  261. proc load*[T](s: Stream, data: var T) =
  262. ## Loads `data` from the stream `s`. Raises `IOError` in case of an error.
  263. runnableExamples:
  264. import marshal, streams
  265. var s = newStringStream("[1, 3, 5]")
  266. var a: array[3, int]
  267. load(s, a)
  268. assert a == [1, 3, 5]
  269. var tab = initTable[BiggestInt, pointer]()
  270. loadAny(s, toAny(data), tab)
  271. proc store*[T](s: Stream, data: T) =
  272. ## Stores `data` into the stream `s`. Raises `IOError` in case of an error.
  273. runnableExamples:
  274. import marshal, streams
  275. var s = newStringStream("")
  276. var a = [1, 3, 5]
  277. store(s, a)
  278. s.setPosition(0)
  279. assert s.readAll() == "[1, 3, 5]"
  280. var stored = initIntSet()
  281. var d: T
  282. shallowCopy(d, data)
  283. storeAny(s, toAny(d), stored)
  284. proc `$$`*[T](x: T): string =
  285. ## Returns a string representation of `x` (serialization, marshalling).
  286. ##
  287. ## **Note:** to serialize `x` to JSON use `$(%x)` from the ``json`` module.
  288. runnableExamples:
  289. type
  290. Foo = object
  291. id: int
  292. bar: string
  293. let x = Foo(id: 1, bar: "baz")
  294. ## serialize:
  295. let y = $$x
  296. assert y == """{"id": 1, "bar": "baz"}"""
  297. var stored = initIntSet()
  298. var d: T
  299. shallowCopy(d, x)
  300. var s = newStringStream()
  301. storeAny(s, toAny(d), stored)
  302. result = s.data
  303. proc to*[T](data: string): T =
  304. ## Reads data and transforms it to a type ``T`` (deserialization, unmarshalling).
  305. runnableExamples:
  306. type
  307. Foo = object
  308. id: int
  309. bar: string
  310. let y = """{"id": 1, "bar": "baz"}"""
  311. assert typeof(y) is string
  312. ## deserialize to type 'Foo':
  313. let z = y.to[:Foo]
  314. assert typeof(z) is Foo
  315. assert z.id == 1
  316. assert z.bar == "baz"
  317. var tab = initTable[BiggestInt, pointer]()
  318. loadAny(newStringStream(data), toAny(result), tab)
  319. when not defined(testing) and isMainModule:
  320. template testit(x: untyped) = echo($$to[type(x)]($$x))
  321. var x: array[0..4, array[0..4, string]] = [
  322. ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
  323. ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
  324. ["test", "1", "2", "3", "4"]]
  325. testit(x)
  326. var test2: tuple[name: string, s: uint] = ("tuple test", 56u)
  327. testit(test2)
  328. type
  329. TE = enum
  330. blah, blah2
  331. TestObj = object
  332. test, asd: int
  333. case test2: TE
  334. of blah:
  335. help: string
  336. else:
  337. nil
  338. PNode = ref Node
  339. Node = object
  340. next, prev: PNode
  341. data: string
  342. proc buildList(): PNode =
  343. new(result)
  344. new(result.next)
  345. new(result.prev)
  346. result.data = "middle"
  347. result.next.data = "next"
  348. result.prev.data = "prev"
  349. result.next.next = result.prev
  350. result.next.prev = result
  351. result.prev.next = result
  352. result.prev.prev = result.next
  353. var test3: TestObj
  354. test3.test = 42
  355. test3 = TestObj(test2: blah)
  356. testit(test3)
  357. var test4: ref tuple[a, b: string]
  358. new(test4)
  359. test4.a = "ref string test: A"
  360. test4.b = "ref string test: B"
  361. testit(test4)
  362. var test5 = @[(0, 1), (2, 3), (4, 5)]
  363. testit(test5)
  364. var test6: set[char] = {'A'..'Z', '_'}
  365. testit(test6)
  366. var test7 = buildList()
  367. echo($$test7)
  368. testit(test7)
  369. type
  370. A {.inheritable.} = object
  371. B = object of A
  372. f: int
  373. var
  374. a: ref A
  375. b: ref B
  376. new(b)
  377. a = b
  378. echo($$a[]) # produces "{}", not "{f: 0}"