summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorDmitry Atamanov <data-man@users.noreply.github.com>2018-05-18 22:13:29 +0300
committerAndreas Rumpf <rumpf_a@web.de>2018-05-18 21:13:29 +0200
commit06bdf8392bd3e597dbe3ef12c7a819b60e32d7ac (patch)
tree661b2410afde62935766ccdf1f1803a1e8e7715f
parent508dfdabeefedd1d839cc01b867fdb38e09b4333 (diff)
downloadNim-06bdf8392bd3e597dbe3ef12c7a819b60e32d7ac.tar.gz
Fixes CritBitTree.inc's bug (#7838)
* Fixes CritBitTree.inc's bug

* Update changelog
-rw-r--r--changelog.md1
-rw-r--r--lib/pure/collections/critbits.nim18
2 files changed, 15 insertions, 4 deletions
diff --git a/changelog.md b/changelog.md
index cbefbc421..f9daf55d1 100644
--- a/changelog.md
+++ b/changelog.md
@@ -74,6 +74,7 @@
   deprecated.
 - The `terminal` module now exports additional procs for generating ANSI color
   codes as strings.
+- Added the parameter ``val`` for the ``CritBitTree[int].inc`` proc.
 
 ### Language additions
 
diff --git a/lib/pure/collections/critbits.nim b/lib/pure/collections/critbits.nim
index 95fffdf88..5ae5e26b2 100644
--- a/lib/pure/collections/critbits.nim
+++ b/lib/pure/collections/critbits.nim
@@ -163,13 +163,13 @@ proc containsOrIncl*(c: var CritBitTree[void], key: string): bool =
   var n = rawInsert(c, key)
   result = c.count == oldCount
 
-proc inc*(c: var CritBitTree[int]; key: string) =
-  ## counts the 'key'.
+proc inc*(c: var CritBitTree[int]; key: string, val: int = 1) =
+  ## increments `c[key]` by `val`.
   let oldCount = c.count
   var n = rawInsert(c, key)
-  if c.count == oldCount:
+  if c.count == oldCount or oldCount == 0:
     # not a new key:
-    inc n.val
+    inc n.val, val
 
 proc incl*(c: var CritBitTree[void], key: string) =
   ## includes `key` in `c`.
@@ -352,3 +352,13 @@ when isMainModule:
   assert toSeq(r.items) == @["abc", "definition", "prefix", "xyz"]
 
   assert toSeq(r.itemsWithPrefix("de")) == @["definition"]
+  var c = CritBitTree[int]()
+
+  c.inc("a")
+  assert c["a"] == 1
+
+  c.inc("a", 4)
+  assert c["a"] == 5
+
+  c.inc("a", -5)
+  assert c["a"] == 0