This commit is contained in:
Joey Yakimowich-Payne 2020-02-13 06:28:16 -07:00
commit b3dad3007c
2 changed files with 11 additions and 9 deletions

View file

@ -355,6 +355,15 @@ proc firstSetBit*(x: SomeInteger): int {.inline, noSideEffect.} =
when sizeof(x) <= 4: result = firstSetBitNim(x.uint32)
else: result = firstSetBitNim(x.uint64)
proc lastSetBit*(x: SomeUnsignedInt): uint {.inline, noSideEffect.} =
## Returns the 1-based index of the most significant set bit of x.
## If x == 0, the result will also be 0
var temp = x
result = 0
while temp != 0:
temp = temp shr 1
result += 1
proc fastLog2*(x: SomeInteger): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of an integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,

View file

@ -9,6 +9,7 @@
# An ``include`` file which contains common code for
# hash sets and tables.
from bitops import lastSetBit
const
growthFactor = 2
@ -50,16 +51,8 @@ template rawGetKnownHCImpl() {.dirty.} =
proc rawGetKnownHC[X, A](t: X, key: A, hc: Hash): int {.inline.} =
rawGetKnownHCImpl()
template bits(n): uint32 =
var temp = n
var bits = 0.uint32
while temp != 0:
temp = temp shr 1
bits += 1
bits
template genHashImpl(key, hc: typed) =
hc = hash(key, targetBits=bits(maxHash(t)))
hc = hash(key, targetBits=lastSetBit(maxHash(t)))
if hc == 0: # This almost never taken branch should be very predictable.
hc = 314159265 # Value doesn't matter; Any non-zero favorite is fine.