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