sets.nim 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # set handling
  10. type
  11. NimSet = array[0..4*2048-1, uint8]
  12. # bitops can't be imported here, therefore the code duplication.
  13. proc countBits32(n: uint32): int {.compilerproc.} =
  14. # generic formula is from: https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  15. var v = uint32(n)
  16. v = v - ((v shr 1) and 0x55555555)
  17. v = (v and 0x33333333) + ((v shr 2) and 0x33333333)
  18. result = (((v + (v shr 4) and 0xF0F0F0F) * 0x1010101) shr 24).int
  19. proc countBits64(n: uint64): int {.compilerproc.} =
  20. # generic formula is from: https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  21. var v = uint64(n)
  22. v = v - ((v shr 1'u64) and 0x5555555555555555'u64)
  23. v = (v and 0x3333333333333333'u64) + ((v shr 2'u64) and 0x3333333333333333'u64)
  24. v = (v + (v shr 4'u64) and 0x0F0F0F0F0F0F0F0F'u64)
  25. result = ((v * 0x0101010101010101'u64) shr 56'u64).int
  26. proc cardSet(s: NimSet, len: int): int {.compilerproc, inline.} =
  27. for i in 0..<len:
  28. if likely(s[i] == 0): continue
  29. inc(result, countBits32(uint32(s[i])))