summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorGrundleTrundle <gtrundle@sdf.org>2017-03-16 03:06:24 -0400
committerAndreas Rumpf <rumpf_a@web.de>2017-03-16 08:06:24 +0100
commit13ba0b557e7009a397fa550747fbc92e6fb15400 (patch)
tree836028ff471f3e2ad599c516178216d4802a4f9d /lib
parente99721a593cfceb43b8b0c3869d82565c03f3fae (diff)
downloadNim-13ba0b557e7009a397fa550747fbc92e6fb15400.tar.gz
Added clear() function for OrderedSet and HashSet. (#5545)
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/collections/sets.nim25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index b2ffbe58d..c0ffcb19c 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..<s.data.len:
+    s.data[i].hcode = 0
+    s.data[i].key   = default(type(s.data[i].key))
+
 # hcode for real keys cannot be zero.  hcode==0 signifies an empty slot.  These
 # two procs retain clarity of that encoding without the space cost of an enum.
 proc isEmpty(hcode: Hash): bool {.inline.} =
@@ -581,6 +594,18 @@ type
 
 {.deprecated: [TOrderedSet: OrderedSet].}
 
+proc clear*[A](s: var OrderedSet[A]) = 
+  ## Clears the OrderedSet 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
+  s.first = -1
+  s.last = -1
+  for i in 0..<s.data.len:
+    s.data[i].hcode = 0
+    s.data[i].next = 0
+    s.data[i].key = default(type(s.data[i].key))
+
+
 proc isValid*[A](s: OrderedSet[A]): bool =
   ## Returns `true` if the ordered set has been initialized with `initSet
   ## <#initOrderedSet>`_.