From a267f73e0a2c70b065695f5adce12ea98261970d Mon Sep 17 00:00:00 2001 From: Felix Krause Date: Sat, 2 Apr 2016 18:29:26 +0200 Subject: [PATCH] Serialization: support sets --- private/serialization.nim | 22 ++++++++++++++++++++-- test/serializing.nim | 14 ++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/private/serialization.nim b/private/serialization.nim index 22fc82b..1cdb183 100644 --- a/private/serialization.nim +++ b/private/serialization.nim @@ -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 = diff --git a/test/serializing.nim b/test/serializing.nim index 9435b0c..1eff566 100644 --- a/test/serializing.nim +++ b/test/serializing.nim @@ -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")