code cleanup (#10874)

This commit is contained in:
Arne Döring 2019-03-28 12:32:02 +01:00 • committed by Andreas Rumpf
commit e904b3f952
6 changed files with 48 additions and 61 deletions

View file

@ -12,17 +12,24 @@
type
NimSet = array[0..4*2048-1, uint8]
proc countBits32(n: int32): int {.compilerproc.} =
var v = n
v = v -% ((v shr 1'i32) and 0x55555555'i32)
v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32)
result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32
# bitops can't be imported here, therefore the code duplication.
proc countBits64(n: int64): int {.compilerproc.} =
result = countBits32(toU32(n and 0xffffffff'i64)) +
countBits32(toU32(n shr 32'i64))
proc countBits32(n: uint32): int {.compilerproc.} =
# generic formula is from: https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
var v = uint32(n)
v = v - ((v shr 1) and 0x55555555)
v = (v and 0x33333333) + ((v shr 2) and 0x33333333)
result = (((v + (v shr 4) and 0xF0F0F0F) * 0x1010101) shr 24).int
proc countBits64(n: uint64): int {.compilerproc.} =
# generic formula is from: https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
var v = uint64(n)
v = v - ((v shr 1'u64) and 0x5555555555555555'u64)
v = (v and 0x3333333333333333'u64) + ((v shr 2'u64) and 0x3333333333333333'u64)
v = (v + (v shr 4'u64) and 0x0F0F0F0F0F0F0F0F'u64)
result = ((v * 0x0101010101010101'u64) shr 56'u64).int
proc cardSet(s: NimSet, len: int): int {.compilerproc, inline.} =
for i in 0..<len:
if likely(s[i] == 0): continue
inc(result, countBits32(int32(s[i])))
inc(result, countBits32(uint32(s[i])))