marshal.nim 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. when defined(nimPreviewSlimSystem):
  51. import std/[assertions, formatfloat]
  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. when defined(nimSeqsV2):
  158. invokeNewSeq(a, 0)
  159. else:
  160. setPointer(a, nil)
  161. next(p)
  162. of jsonArrayStart:
  163. next(p)
  164. invokeNewSeq(a, 0)
  165. var i = 0
  166. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  167. extendSeq(a)
  168. loadAny(p, a[i], t)
  169. inc(i)
  170. if p.kind == jsonArrayEnd: next(p)
  171. else: raiseParseErr(p, "")
  172. else:
  173. raiseParseErr(p, "'[' expected for a seq")
  174. of akObject, akTuple:
  175. if a.kind == akObject: setObjectRuntimeType(a)
  176. if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
  177. next(p)
  178. while p.kind != jsonObjectEnd and p.kind != jsonEof:
  179. if p.kind != jsonString:
  180. raiseParseErr(p, "string expected for a field name")
  181. var fieldName = p.str
  182. next(p)
  183. loadAny(p, a[fieldName], t)
  184. if p.kind == jsonObjectEnd: next(p)
  185. else: raiseParseErr(p, "'}' end of object expected")
  186. of akSet:
  187. if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
  188. next(p)
  189. while p.kind != jsonArrayEnd and p.kind != jsonEof:
  190. if p.kind != jsonInt: raiseParseErr(p, "int expected for a set")
  191. inclSetElement(a, p.getInt.int)
  192. next(p)
  193. if p.kind == jsonArrayEnd: next(p)
  194. else: raiseParseErr(p, "']' end of array expected")
  195. of akPtr, akRef:
  196. case p.kind
  197. of jsonNull:
  198. setPointer(a, nil)
  199. next(p)
  200. of jsonInt:
  201. setPointer(a, t.getOrDefault(p.getInt))
  202. next(p)
  203. of jsonArrayStart:
  204. next(p)
  205. if a.kind == akRef: invokeNew(a)
  206. else: setPointer(a, alloc0(a.baseTypeSize))
  207. if p.kind == jsonInt:
  208. t[p.getInt] = getPointer(a)
  209. next(p)
  210. else: raiseParseErr(p, "index for ref type expected")
  211. loadAny(p, a[], t)
  212. if p.kind == jsonArrayEnd: next(p)
  213. else: raiseParseErr(p, "']' end of ref-address pair expected")
  214. else: raiseParseErr(p, "int for pointer type expected")
  215. of akProc, akPointer, akCString:
  216. case p.kind
  217. of jsonNull:
  218. setPointer(a, nil)
  219. next(p)
  220. of jsonInt:
  221. setPointer(a, cast[pointer](p.getInt.int))
  222. next(p)
  223. else: raiseParseErr(p, "int for pointer type expected")
  224. of akString:
  225. case p.kind
  226. of jsonNull:
  227. when defined(nimSeqsV2):
  228. setString(a, "")
  229. else:
  230. setPointer(a, nil)
  231. next(p)
  232. of jsonString:
  233. setString(a, p.str)
  234. next(p)
  235. of jsonArrayStart:
  236. next(p)
  237. var str = ""
  238. while p.kind == jsonInt:
  239. let code = p.getInt()
  240. if code < 0 or code > 255:
  241. raiseParseErr(p, "invalid charcode: " & $code)
  242. str.add(chr(code))
  243. next(p)
  244. if p.kind == jsonArrayEnd: next(p)
  245. else: raiseParseErr(p, "an array of charcodes expected for string")
  246. setString(a, str)
  247. else: raiseParseErr(p, "string expected")
  248. of akInt..akInt64, akUInt..akUInt64:
  249. if p.kind == jsonInt:
  250. setBiggestInt(a, getInt(p))
  251. next(p)
  252. return
  253. raiseParseErr(p, "int expected")
  254. of akFloat..akFloat128:
  255. if p.kind == jsonFloat:
  256. setBiggestFloat(a, getFloat(p))
  257. next(p)
  258. return
  259. raiseParseErr(p, "float expected")
  260. of akRange: loadAny(p, a.skipRange, t)
  261. proc loadAny(s: Stream, a: Any, t: var Table[BiggestInt, pointer]) =
  262. var p: JsonParser
  263. open(p, s, "unknown file")
  264. next(p)
  265. loadAny(p, a, t)
  266. close(p)
  267. proc load*[T](s: Stream, data: var T) =
  268. ## Loads `data` from the stream `s`. Raises `IOError` in case of an error.
  269. runnableExamples:
  270. import std/streams
  271. var s = newStringStream("[1, 3, 5]")
  272. var a: array[3, int]
  273. load(s, a)
  274. assert a == [1, 3, 5]
  275. var tab = initTable[BiggestInt, pointer]()
  276. loadAny(s, toAny(data), tab)
  277. proc store*[T](s: Stream, data: sink T) =
  278. ## Stores `data` into the stream `s`. Raises `IOError` in case of an error.
  279. runnableExamples:
  280. import std/streams
  281. var s = newStringStream("")
  282. var a = [1, 3, 5]
  283. store(s, a)
  284. s.setPosition(0)
  285. assert s.readAll() == "[1, 3, 5]"
  286. var stored = initIntSet()
  287. var d: T
  288. when defined(gcArc) or defined(gcOrc):
  289. d = data
  290. else:
  291. shallowCopy(d, data)
  292. storeAny(s, toAny(d), stored)
  293. proc loadVM[T](typ: typedesc[T], x: T): string =
  294. discard "the implementation is in the compiler/vmops"
  295. proc `$$`*[T](x: sink T): string =
  296. ## Returns a string representation of `x` (serialization, marshalling).
  297. ##
  298. ## **Note:** to serialize `x` to JSON use `%x` from the `json` module
  299. ## or `jsonutils.toJson(x)`.
  300. runnableExamples:
  301. type
  302. Foo = object
  303. id: int
  304. bar: string
  305. let x = Foo(id: 1, bar: "baz")
  306. ## serialize:
  307. let y = $$x
  308. assert y == """{"id": 1, "bar": "baz"}"""
  309. when nimvm:
  310. result = loadVM(T, x)
  311. else:
  312. var stored = initIntSet()
  313. var d: T
  314. when defined(gcArc) or defined(gcOrc):
  315. d = x
  316. else:
  317. shallowCopy(d, x)
  318. var s = newStringStream()
  319. storeAny(s, toAny(d), stored)
  320. result = s.data
  321. proc toVM[T](typ: typedesc[T], data: string): T =
  322. discard "the implementation is in the compiler/vmops"
  323. proc to*[T](data: string): T =
  324. ## Reads data and transforms it to a type `T` (deserialization, unmarshalling).
  325. runnableExamples:
  326. type
  327. Foo = object
  328. id: int
  329. bar: string
  330. let y = """{"id": 1, "bar": "baz"}"""
  331. assert typeof(y) is string
  332. ## deserialize to type 'Foo':
  333. let z = y.to[:Foo]
  334. assert typeof(z) is Foo
  335. assert z.id == 1
  336. assert z.bar == "baz"
  337. when nimvm:
  338. result = toVM(T, data)
  339. else:
  340. var tab = initTable[BiggestInt, pointer]()
  341. loadAny(newStringStream(data), toAny(result), tab)