Serialization: support sets

This commit is contained in:
Felix Krause 2016-04-02 18:29:26 +02:00
parent cde346b85c
commit a267f73e0a
2 changed files with 34 additions and 2 deletions

View File

@ -210,7 +210,11 @@ proc representObject*(value: char, ts: TagStyle, c: SerializationContext,
yield scalarEvent("" & value, tag, yAnchorNone)
proc yamlTag*[I](T: typedesc[seq[I]]): TagId {.inline, raises: [].} =
let uri = "!nim:system:seq(" & safeTagUri(yamlTag(I)) & ")"
let uri = "!nim:system:seq(" & safeTagUri(yamlTag(I)) & ')'
result = lazyLoadTag(uri)
proc yamlTag*[I](T: typedesc[set[I]]): TagId {.inline, raises: [].} =
let uri = "!nim:system:set(" & safeTagUri(yamlTag(I)) & ')'
result = lazyLoadTag(uri)
proc constructObject*[T](s: var YamlStream, c: ConstructionContext,
@ -227,7 +231,21 @@ proc constructObject*[T](s: var YamlStream, c: ConstructionContext,
result.add(item)
discard s.next()
proc representObject*[T](value: seq[T], ts: TagStyle,
proc constructObject*[T](s: var YamlStream, c: ConstructionContext,
result: var set[T])
{.raises: [YamlConstructionError, YamlStreamError].} =
## constructs a Nim seq from a YAML sequence
let event = s.next()
if event.kind != yamlStartSeq:
raise newException(YamlConstructionError, "Expected sequence start")
result = {}
while s.peek().kind != yamlEndSeq:
var item: T
constructChild(s, c, item)
result.incl(item)
discard s.next()
proc representObject*[T](value: seq[T]|set[T], ts: TagStyle,
c: SerializationContext, tag: TagId): RawYamlStream {.raises: [].} =
## represents a Nim seq as YAML sequence
result = iterator(): YamlStreamEvent =

View File

@ -78,6 +78,20 @@ suite "Serialization":
var output = newStringStream()
dump(input, output, tsNone, asTidy, blockOnly)
assertStringEqual "%YAML 1.2\n--- \n- a\n- b", output.data
test "Serialization: Load char set":
let input = newStringStream("- a\n- b")
var result: set[char]
load(input, result)
assert result.card == 2
assert 'a' in result
assert 'b' in result
test "Serialization: Represent char set":
var input = {'a', 'b'}
var output = newStringStream()
dump(input, output, tsNone, asTidy, blockOnly)
assertStringEqual "%YAML 1.2\n--- \n- a\n- b", output.data
test "Serialization: Load Table[int, string]":
let input = newStringStream("23: dreiundzwanzig\n42: zweiundvierzig")