From 13ba0b557e7009a397fa550747fbc92e6fb15400 Mon Sep 17 00:00:00 2001 From: GrundleTrundle Date: Thu, 16 Mar 2017 03:06:24 -0400 Subject: [PATCH] Added clear() function for OrderedSet and HashSet. (#5545) --- lib/pure/collections/sets.nim | 25 +++++++++++++++++++++ tests/collections/tsets.nim | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index b2ffbe58d6..c0ffcb19c7 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -41,6 +41,19 @@ type {.deprecated: [TSet: HashSet].} +template default[T](t: typedesc[T]): T = + ## Used by clear methods to get a default value. + var v: T + v + +proc clear*[A](s: var HashSet[A]) = + ## Clears the HashSet back to an empty state, without shrinking + ## any of the existing storage. O(n) where n is the size of the hash bucket. + s.counter = 0 + for i in 0..`_. diff --git a/tests/collections/tsets.nim b/tests/collections/tsets.nim index a5bbe8dbd6..6139560bd2 100644 --- a/tests/collections/tsets.nim +++ b/tests/collections/tsets.nim @@ -34,4 +34,46 @@ block setWithSequences: doAssert s.contains(@[1, 2, 3]) doAssert( not s.contains(@[4, 5, 6]) ) +block setClearWorked: + var s = initSet[char]() + + for c in "this is a test": + s.incl(c) + + doAssert len(s) == 7 + clear(s) + doAssert len(s) == 0 + + s.incl('z') + for c in "this is a test": + s.incl(c) + + doAssert len(s) == 8 + +block orderedSetClearWorked: + var s = initOrderedSet[char]() + + for c in "eat at joes": + s.incl(c) + + var r = "" + + for c in items(s): + add(r, c) + + doAssert r == "eat jos" + clear(s) + + s.incl('z') + for c in "eat at joes": + s.incl(c) + + r = "" + for c in items(s): + add(r, c) + + doAssert r == "zeat jos" + + +