bitsets.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #
  2. #
  3. # The Nim Compiler
  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. # this unit handles Nim sets; it implements bit sets
  10. # the code here should be reused in the Nim standard library
  11. type
  12. TBitSet* = seq[int8] # we use byte here to avoid issues with
  13. # cross-compiling; uint would be more efficient
  14. # however
  15. const
  16. ElemSize* = sizeof(int8) * 8
  17. proc bitSetInit*(b: var TBitSet, length: int)
  18. proc bitSetUnion*(x: var TBitSet, y: TBitSet)
  19. proc bitSetDiff*(x: var TBitSet, y: TBitSet)
  20. proc bitSetSymDiff*(x: var TBitSet, y: TBitSet)
  21. proc bitSetIntersect*(x: var TBitSet, y: TBitSet)
  22. proc bitSetIncl*(x: var TBitSet, elem: BiggestInt)
  23. proc bitSetExcl*(x: var TBitSet, elem: BiggestInt)
  24. proc bitSetIn*(x: TBitSet, e: BiggestInt): bool
  25. proc bitSetEquals*(x, y: TBitSet): bool
  26. proc bitSetContains*(x, y: TBitSet): bool
  27. # implementation
  28. proc bitSetIn(x: TBitSet, e: BiggestInt): bool =
  29. result = (x[int(e div ElemSize)] and toU8(int(1 shl (e mod ElemSize)))) !=
  30. toU8(0)
  31. proc bitSetIncl(x: var TBitSet, elem: BiggestInt) =
  32. assert(elem >= 0)
  33. x[int(elem div ElemSize)] = x[int(elem div ElemSize)] or
  34. toU8(int(1 shl (elem mod ElemSize)))
  35. proc bitSetExcl(x: var TBitSet, elem: BiggestInt) =
  36. x[int(elem div ElemSize)] = x[int(elem div ElemSize)] and
  37. not toU8(int(1 shl (elem mod ElemSize)))
  38. proc bitSetInit(b: var TBitSet, length: int) =
  39. newSeq(b, length)
  40. proc bitSetUnion(x: var TBitSet, y: TBitSet) =
  41. for i in countup(0, high(x)): x[i] = x[i] or y[i]
  42. proc bitSetDiff(x: var TBitSet, y: TBitSet) =
  43. for i in countup(0, high(x)): x[i] = x[i] and not y[i]
  44. proc bitSetSymDiff(x: var TBitSet, y: TBitSet) =
  45. for i in countup(0, high(x)): x[i] = x[i] xor y[i]
  46. proc bitSetIntersect(x: var TBitSet, y: TBitSet) =
  47. for i in countup(0, high(x)): x[i] = x[i] and y[i]
  48. proc bitSetEquals(x, y: TBitSet): bool =
  49. for i in countup(0, high(x)):
  50. if x[i] != y[i]:
  51. return false
  52. result = true
  53. proc bitSetContains(x, y: TBitSet): bool =
  54. for i in countup(0, high(x)):
  55. if (x[i] and not y[i]) != int8(0):
  56. return false
  57. result = true