std/sharedtables
Source EditShared table support for Nim. Use plain old non GC'ed keys and values or you'll be in trouble. Uses a single lock to protect the table, lockfree implementations welcome but if lock contention is so high that you need a lockfree hash table, you're doing it wrong.
Unstable API.
Imports
- hashes, math, locks, outparams
Types
Consts
Procs
proc withKey[A, B](t: var SharedTable[A, B]; key: A; mapper: proc (key: A; val: var B; pairExists: var bool))-
Computes a new mapping for the
keywith the specifiedmapperprocedure.The
mappertakes 3 arguments:-
key- the current key, if it exists, or the key passed towithKeyotherwise; -
val- the current value, if the key exists, or default value of the type otherwise; -
pairExists-trueif the key exists,falseotherwise.
The
mappercan can modifyvalandpairExistsvalues to change the mapping of the key or delete it from the table. When adding a value, make sure to setpairExiststotruealong with modifying theval.The operation is performed atomically and other operations on the table will be blocked while the
mapperis invoked, so it should be short and simple.Example usage:
# If value exists, decrement it. # If it becomes zero or less, delete the key t.withKey(1'i64) do (k: int64, v: var int, pairExists: var bool): if pairExists: dec v if v <= 0: pairExists = falseSource Edit -
Templates
template withValue[A, B](t: var SharedTable[A, B]; key: A; value, body1, body2: untyped)- Retrieves the value at
t[key].valuecan be modified in the scope of thewithValuecall.Example:
var table: SharedTable[string, string] init(table) table["a"] = "x" table["b"] = "y" table["c"] = "z" table.withValue("a", value): value[] = "m" var flag = false table.withValue("d", value): discard value doAssert false do: # if "d" notin table flag = true if flag: table["d"] = "n" assert table.mget("a") == "m" assert table.mget("d") == "n"Source Edit template withValue[A, B](t: var SharedTable[A, B]; key: A; value, body: untyped)
- Retrieves the value at
t[key].valuecan be modified in the scope of thewithValuecall.Example:
var table: SharedTable[string, string] init(table) table["a"] = "x" table["b"] = "y" table["c"] = "z" table.withValue("a", value): assert value[] == "x" table.withValue("b", value): value[] = "modified" table.withValue("b", value): assert value[] == "modified" table.withValue("nonexistent", value): assert false # not calledSource Edit
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/sharedtables.html