summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2016-05-27 11:20:46 +0200
committerAndreas Rumpf <rumpf_a@web.de>2016-05-27 11:20:46 +0200
commit4476226b80c2a370cd58f1c3675756456ba82631 (patch)
tree34c6bc92a07a7dea63d4c72a957dee23f79fa298 /lib
parentd2ddeb47c52f3507d0a95412dd17304de3732dda (diff)
parent49c50e4e214b82466b44fab3fa9ac51d66242499 (diff)
downloadNim-4476226b80c2a370cd58f1c3675756456ba82631.tar.gz
Merge pull request #4226 from cheatfate/tables_templates
Introduce template withValue() for tables.nim too.
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/collections/tables.nim45
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim
index 58a789e76..b702f6248 100644
--- a/lib/pure/collections/tables.nim
+++ b/lib/pure/collections/tables.nim
@@ -136,6 +136,51 @@ proc mget*[A, B](t: var Table[A, B], key: A): var B {.deprecated.} =
 
 proc getOrDefault*[A, B](t: Table[A, B], key: A): B = getOrDefaultImpl(t, key)
 
+template withValue*[A, B](t: var Table[A, B], key: A,
+                          value, body: untyped) =
+  ## retrieves the value at ``t[key]``. 
+  ## `value` can be modified in the scope of the ``withValue`` call.
+  ##
+  ## .. code-block:: nim
+  ##
+  ##   sharedTable.withValue(key, value) do:
+  ##     # block is executed only if ``key`` in ``t``
+  ##     value.name = "username" 
+  ##     value.uid = 1000
+  ##
+  mixin rawGet
+  var hc: Hash
+  var index = rawGet(t, key, hc)
+  let hasKey = index >= 0
+  if hasKey:
+    var value {.inject.} = addr(t.data[index].val)
+    body
+
+template withValue*[A, B](t: var Table[A, B], key: A,
+                          value, body1, body2: untyped) =
+  ## retrieves the value at ``t[key]``. 
+  ## `value` can be modified in the scope of the ``withValue`` call.
+  ## 
+  ## .. code-block:: nim
+  ##
+  ##   table.withValue(key, value) do:
+  ##     # block is executed only if ``key`` in ``t``
+  ##     value.name = "username" 
+  ##     value.uid = 1000
+  ##   do:
+  ##     # block is executed when ``key`` not in ``t``
+  ##     raise newException(KeyError, "Key not found")
+  ##
+  mixin rawGet
+  var hc: Hash
+  var index = rawGet(t, key, hc)
+  let hasKey = index >= 0
+  if hasKey:
+    var value {.inject.} = addr(t.data[index].val)
+    body1
+  else:
+    body2
+
 iterator allValues*[A, B](t: Table[A, B]; key: A): B =
   ## iterates over any value in the table `t` that belongs to the given `key`.
   var h: Hash = hash(key) and high(t.data)