This module implements efficient computations of hash values for diverse Nim types. All the procs are based on these two building blocks:
If you want to implement hash procs for your custom types you will end up writing the following kind of skeleton of code:
proc hash(x: Something): Hash =
## Computes a Hash from `x`.
var h: Hash = 0
# Iterate over parts of `x`.
for xAtom in x:
# Mix the atom with the partial hash.
h = h !& xAtom
# Finish the hash.
result = !$h
If your custom types contain fields for which there already is a hash proc, like for example objects made up of strings, you can simply hash together the hash value of the individual fields:
proc hash(x: Something): Hash = ## Computes a Hash from `x`. var h: Hash = 0 h = h !& hash(x.foo) h = h !& hash(x.bar) result = !$h
Hash = int
and operator instead of mod for truncation of the hash value. proc `!&`(h: Hash; val: int): Hash {...}{.inline, raises: [], tags: [].}proc `!$`(h: Hash): Hash {...}{.inline, raises: [], tags: [].}proc hashData(data: pointer; size: int): Hash {...}{.raises: [], tags: [].}proc hash(x: pointer): Hash {...}{.inline, raises: [], tags: [].}proc hash[T: proc](x: T): Hash {...}{.inline.}proc hash(x: int): Hash {...}{.inline, raises: [], tags: [].}proc hash(x: int64): Hash {...}{.inline, raises: [], tags: [].}proc hash(x: uint): Hash {...}{.inline, raises: [], tags: [].}proc hash(x: uint64): Hash {...}{.inline, raises: [], tags: [].}proc hash(x: char): Hash {...}{.inline, raises: [], tags: [].}proc hash[T: Ordinal](x: T): Hash {...}{.inline.}proc hash(x: string): Hash {...}{.raises: [], tags: [].}proc hash(x: cstring): Hash {...}{.raises: [], tags: [].}proc hash(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].}efficient hashing of a string buffer, from starting position sPos to ending position ePos
hash(myStr, 0, myStr.high) is equivalent to hash(myStr)
proc hashIgnoreStyle(x: string): Hash {...}{.raises: [], tags: [].}proc hashIgnoreStyle(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].}efficient hashing of a string buffer, from starting position sPos to ending position ePos; style is ignored
hashIgnoreStyle(myBuf, 0, myBuf.high) is equivalent to hashIgnoreStyle(myBuf)
proc hashIgnoreCase(x: string): Hash {...}{.raises: [], tags: [].}proc hashIgnoreCase(sBuf: string; sPos, ePos: int): Hash {...}{.raises: [], tags: [].}efficient hashing of a string buffer, from starting position sPos to ending position ePos; case is ignored
hashIgnoreCase(myBuf, 0, myBuf.high) is equivalent to hashIgnoreCase(myBuf)
proc hash(x: float): Hash {...}{.inline, raises: [], tags: [].}proc hash[T: tuple](x: T): Hash
proc hash[A](x: openArray[A]): Hash
proc hash[A](aBuf: openArray[A]; sPos, ePos: int): Hash
efficient hashing of portions of arrays and sequences.
hash(myBuf, 0, myBuf.high) is equivalent to hash(myBuf)
proc hash[A](x: set[A]): Hash
© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/hashes.html