summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorMiran <narimiran@disroot.org>2019-10-15 16:31:07 +0200
committerAndreas Rumpf <rumpf_a@web.de>2019-10-15 16:31:07 +0200
commit734da9e1dfdd5cb441a5c1461539f10ab331596a (patch)
treeff80c11ffd6d524a993eeacaf207be21ce306005 /lib
parent5f5ac8ce1616c7a68002b99ba4ffc36ab3a3ec42 (diff)
downloadNim-734da9e1dfdd5cb441a5c1461539f10ab331596a.tar.gz
fixes #11764, faster hashing of (u)int (#12407)
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/collections/sets.nim4
-rw-r--r--lib/pure/hashes.nim15
2 files changed, 11 insertions, 8 deletions
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index 322cb5486..4b896b12b 100644
--- a/lib/pure/collections/sets.nim
+++ b/lib/pure/collections/sets.nim
@@ -1019,9 +1019,9 @@ when isMainModule and not defined(release):
       # --> {1, 3, 5}
 
     block toSeqAndString:
-      var a = toHashSet([2, 4, 5])
+      var a = toHashSet([2, 7, 5])
       var b = initHashSet[int]()
-      for x in [2, 4, 5]: b.incl(x)
+      for x in [2, 7, 5]: b.incl(x)
       assert($a == $b)
       #echo a
       #echo toHashSet(["no", "esc'aping", "is \" provided"])
diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim
index cb0250dbd..f5b9cda85 100644
--- a/lib/pure/hashes.nim
+++ b/lib/pure/hashes.nim
@@ -112,29 +112,32 @@ proc hash*[T: proc](x: T): Hash {.inline.} =
   else:
     result = hash(pointer(x))
 
+const
+  prime = uint(11)
+
 proc hash*(x: int): Hash {.inline.} =
   ## Efficient hashing of integers.
-  result = x
+  result = cast[Hash](cast[uint](x) * prime)
 
 proc hash*(x: int64): Hash {.inline.} =
   ## Efficient hashing of `int64` integers.
-  result = cast[int](x)
+  result = cast[Hash](cast[uint](x) * prime)
 
 proc hash*(x: uint): Hash {.inline.} =
   ## Efficient hashing of unsigned integers.
-  result = cast[int](x)
+  result = cast[Hash](x * prime)
 
 proc hash*(x: uint64): Hash {.inline.} =
   ## Efficient hashing of `uint64` integers.
-  result = cast[int](x)
+  result = cast[Hash](cast[uint](x) * prime)
 
 proc hash*(x: char): Hash {.inline.} =
   ## Efficient hashing of characters.
-  result = ord(x)
+  result = cast[Hash](cast[uint](ord(x)) * prime)
 
 proc hash*[T: Ordinal](x: T): Hash {.inline.} =
   ## Efficient hashing of other ordinal types (e.g. enums).
-  result = ord(x)
+  result = cast[Hash](cast[uint](ord(x)) * prime)
 
 proc hash*(x: float): Hash {.inline.} =
   ## Efficient hashing of floats.