marshal.nim 10.0 KB

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