packedsets.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. ## The `packedsets` module implements an efficient `Ordinal` set implemented as a
  10. ## `sparse bit set`:idx:.
  11. ##
  12. ## Supports any Ordinal type.
  13. ##
  14. ## **Note**: Currently the assignment operator `=` for `PackedSet[A]`
  15. ## performs some rather meaningless shallow copy. Since Nim currently does
  16. ## not allow the assignment operator to be overloaded, use the `assign proc
  17. ## <#assign,PackedSet[A],PackedSet[A]>`_ to get a deep copy.
  18. ##
  19. ## See also
  20. ## ========
  21. ## * `sets module <sets.html>`_ for more general hash sets
  22. import std/private/since
  23. import hashes
  24. type
  25. BitScalar = uint
  26. const
  27. InitIntSetSize = 8 # must be a power of two!
  28. TrunkShift = 9
  29. BitsPerTrunk = 1 shl TrunkShift # needs to be a power of 2 and
  30. # divisible by 64
  31. TrunkMask = BitsPerTrunk - 1
  32. IntsPerTrunk = BitsPerTrunk div (sizeof(BitScalar) * 8)
  33. IntShift = 5 + ord(sizeof(BitScalar) == 8) # 5 or 6, depending on int width
  34. IntMask = 1 shl IntShift - 1
  35. type
  36. Trunk = ref object
  37. next: Trunk # all nodes are connected with this pointer
  38. key: int # start address at bit 0
  39. bits: array[0..IntsPerTrunk - 1, BitScalar] # a bit vector
  40. TrunkSeq = seq[Trunk]
  41. PackedSet*[A: Ordinal] = object
  42. ## An efficient set of `Ordinal` types implemented as a sparse bit set.
  43. elems: int # only valid for small numbers
  44. counter, max: int
  45. head: Trunk
  46. data: TrunkSeq
  47. a: array[0..33, int] # profiling shows that 34 elements are enough
  48. proc mustRehash[T](t: T): bool {.inline.} =
  49. let length = t.max + 1
  50. assert length > t.counter
  51. result = (length * 2 < t.counter * 3) or (length - t.counter < 4)
  52. proc nextTry(h, maxHash: Hash, perturb: var Hash): Hash {.inline.} =
  53. const PERTURB_SHIFT = 5
  54. var perturb2 = cast[uint](perturb) shr PERTURB_SHIFT
  55. perturb = cast[Hash](perturb2)
  56. result = ((5 * h) + 1 + perturb) and maxHash
  57. proc packedSetGet[A](t: PackedSet[A], key: int): Trunk =
  58. var h = key and t.max
  59. var perturb = key
  60. while t.data[h] != nil:
  61. if t.data[h].key == key:
  62. return t.data[h]
  63. h = nextTry(h, t.max, perturb)
  64. result = nil
  65. proc intSetRawInsert[A](t: PackedSet[A], data: var TrunkSeq, desc: Trunk) =
  66. var h = desc.key and t.max
  67. var perturb = desc.key
  68. while data[h] != nil:
  69. assert data[h] != desc
  70. h = nextTry(h, t.max, perturb)
  71. assert data[h] == nil
  72. data[h] = desc
  73. proc intSetEnlarge[A](t: var PackedSet[A]) =
  74. var n: TrunkSeq
  75. var oldMax = t.max
  76. t.max = ((t.max + 1) * 2) - 1
  77. newSeq(n, t.max + 1)
  78. for i in countup(0, oldMax):
  79. if t.data[i] != nil: intSetRawInsert(t, n, t.data[i])
  80. swap(t.data, n)
  81. proc intSetPut[A](t: var PackedSet[A], key: int): Trunk =
  82. var h = key and t.max
  83. var perturb = key
  84. while t.data[h] != nil:
  85. if t.data[h].key == key:
  86. return t.data[h]
  87. h = nextTry(h, t.max, perturb)
  88. if mustRehash(t): intSetEnlarge(t)
  89. inc(t.counter)
  90. h = key and t.max
  91. perturb = key
  92. while t.data[h] != nil: h = nextTry(h, t.max, perturb)
  93. assert t.data[h] == nil
  94. new(result)
  95. result.next = t.head
  96. result.key = key
  97. t.head = result
  98. t.data[h] = result
  99. proc bitincl[A](s: var PackedSet[A], key: int) {.inline.} =
  100. var ret: Trunk
  101. var t = intSetPut(s, key shr TrunkShift)
  102. var u = key and TrunkMask
  103. t.bits[u shr IntShift] = t.bits[u shr IntShift] or
  104. (BitScalar(1) shl (u and IntMask))
  105. proc exclImpl[A](s: var PackedSet[A], key: int) =
  106. if s.elems <= s.a.len:
  107. for i in 0..<s.elems:
  108. if s.a[i] == key:
  109. s.a[i] = s.a[s.elems - 1]
  110. dec(s.elems)
  111. return
  112. else:
  113. var t = packedSetGet(s, key shr TrunkShift)
  114. if t != nil:
  115. var u = key and TrunkMask
  116. t.bits[u shr IntShift] = t.bits[u shr IntShift] and
  117. not(BitScalar(1) shl (u and IntMask))
  118. template dollarImpl(): untyped =
  119. result = "{"
  120. for key in items(s):
  121. if result.len > 1: result.add(", ")
  122. result.add $key
  123. result.add("}")
  124. iterator items*[A](s: PackedSet[A]): A {.inline.} =
  125. ## Iterates over any included element of `s`.
  126. if s.elems <= s.a.len:
  127. for i in 0..<s.elems:
  128. yield A(s.a[i])
  129. else:
  130. var r = s.head
  131. while r != nil:
  132. var i = 0
  133. while i <= high(r.bits):
  134. var w: uint = r.bits[i]
  135. # taking a copy of r.bits[i] here is correct, because
  136. # modifying operations are not allowed during traversation
  137. var j = 0
  138. while w != 0: # test all remaining bits for zero
  139. if (w and 1) != 0: # the bit is set!
  140. yield A((r.key shl TrunkShift) or (i shl IntShift +% j))
  141. inc(j)
  142. w = w shr 1
  143. inc(i)
  144. r = r.next
  145. proc initPackedSet*[A]: PackedSet[A] =
  146. ## Returns an empty `PackedSet[A]`.
  147. ## `A` must be `Ordinal`.
  148. ##
  149. ## **See also:**
  150. ## * `toPackedSet proc <#toPackedSet,openArray[A]>`_
  151. runnableExamples:
  152. let a = initPackedSet[int]()
  153. assert len(a) == 0
  154. type Id = distinct int
  155. var ids = initPackedSet[Id]()
  156. ids.incl(3.Id)
  157. result = PackedSet[A](
  158. elems: 0,
  159. counter: 0,
  160. max: 0,
  161. head: nil,
  162. data: @[])
  163. # a: array[0..33, int] # profiling shows that 34 elements are enough
  164. proc contains*[A](s: PackedSet[A], key: A): bool =
  165. ## Returns true if `key` is in `s`.
  166. ##
  167. ## This allows the usage of the `in` operator.
  168. runnableExamples:
  169. type ABCD = enum A, B, C, D
  170. let a = [1, 3, 5].toPackedSet
  171. assert a.contains(3)
  172. assert 3 in a
  173. assert not a.contains(8)
  174. assert 8 notin a
  175. let letters = [A, C].toPackedSet
  176. assert A in letters
  177. assert C in letters
  178. assert B notin letters
  179. if s.elems <= s.a.len:
  180. for i in 0..<s.elems:
  181. if s.a[i] == ord(key): return true
  182. else:
  183. var t = packedSetGet(s, ord(key) shr TrunkShift)
  184. if t != nil:
  185. var u = ord(key) and TrunkMask
  186. result = (t.bits[u shr IntShift] and
  187. (BitScalar(1) shl (u and IntMask))) != 0
  188. else:
  189. result = false
  190. proc incl*[A](s: var PackedSet[A], key: A) =
  191. ## Includes an element `key` in `s`.
  192. ##
  193. ## This doesn't do anything if `key` is already in `s`.
  194. ##
  195. ## **See also:**
  196. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  197. ## * `incl proc <#incl,PackedSet[A],PackedSet[A]>`_ for including a set
  198. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  199. runnableExamples:
  200. var a = initPackedSet[int]()
  201. a.incl(3)
  202. a.incl(3)
  203. assert len(a) == 1
  204. if s.elems <= s.a.len:
  205. for i in 0..<s.elems:
  206. if s.a[i] == ord(key): return
  207. if s.elems < s.a.len:
  208. s.a[s.elems] = ord(key)
  209. inc(s.elems)
  210. return
  211. newSeq(s.data, InitIntSetSize)
  212. s.max = InitIntSetSize - 1
  213. for i in 0..<s.elems:
  214. bitincl(s, s.a[i])
  215. s.elems = s.a.len + 1
  216. # fall through:
  217. bitincl(s, ord(key))
  218. proc incl*[A](s: var PackedSet[A], other: PackedSet[A]) =
  219. ## Includes all elements from `other` into `s`.
  220. ##
  221. ## This is the in-place version of `s + other <#+,PackedSet[A],PackedSet[A]>`_.
  222. ##
  223. ## **See also:**
  224. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  225. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  226. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  227. runnableExamples:
  228. var a = [1].toPackedSet
  229. a.incl([5].toPackedSet)
  230. assert len(a) == 2
  231. assert 5 in a
  232. for item in other.items: incl(s, item)
  233. proc toPackedSet*[A](x: openArray[A]): PackedSet[A] {.since: (1, 3).} =
  234. ## Creates a new `PackedSet[A]` that contains the elements of `x`.
  235. ##
  236. ## Duplicates are removed.
  237. ##
  238. ## **See also:**
  239. ## * `initPackedSet proc <#initPackedSet>`_
  240. runnableExamples:
  241. let a = [5, 6, 7, 8, 8].toPackedSet
  242. assert len(a) == 4
  243. assert $a == "{5, 6, 7, 8}"
  244. result = initPackedSet[A]()
  245. for item in x:
  246. result.incl(item)
  247. proc containsOrIncl*[A](s: var PackedSet[A], key: A): bool =
  248. ## Includes `key` in the set `s` and tells if `key` was already in `s`.
  249. ##
  250. ## The difference with regards to the `incl proc <#incl,PackedSet[A],A>`_ is
  251. ## that this proc returns true if `s` already contained `key`. The
  252. ## proc will return false if `key` was added as a new value to `s` during
  253. ## this call.
  254. ##
  255. ## **See also:**
  256. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  257. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  258. runnableExamples:
  259. var a = initPackedSet[int]()
  260. assert a.containsOrIncl(3) == false
  261. assert a.containsOrIncl(3) == true
  262. assert a.containsOrIncl(4) == false
  263. if s.elems <= s.a.len:
  264. for i in 0..<s.elems:
  265. if s.a[i] == ord(key):
  266. return true
  267. incl(s, key)
  268. result = false
  269. else:
  270. var t = packedSetGet(s, ord(key) shr TrunkShift)
  271. if t != nil:
  272. var u = ord(key) and TrunkMask
  273. result = (t.bits[u shr IntShift] and BitScalar(1) shl (u and IntMask)) != 0
  274. if not result:
  275. t.bits[u shr IntShift] = t.bits[u shr IntShift] or
  276. (BitScalar(1) shl (u and IntMask))
  277. else:
  278. incl(s, key)
  279. result = false
  280. proc excl*[A](s: var PackedSet[A], key: A) =
  281. ## Excludes `key` from the set `s`.
  282. ##
  283. ## This doesn't do anything if `key` is not found in `s`.
  284. ##
  285. ## **See also:**
  286. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  287. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  288. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  289. runnableExamples:
  290. var a = [3].toPackedSet
  291. a.excl(3)
  292. a.excl(3)
  293. a.excl(99)
  294. assert len(a) == 0
  295. exclImpl[A](s, ord(key))
  296. proc excl*[A](s: var PackedSet[A], other: PackedSet[A]) =
  297. ## Excludes all elements from `other` from `s`.
  298. ##
  299. ## This is the in-place version of `s - other <#-,PackedSet[A],PackedSet[A]>`_.
  300. ##
  301. ## **See also:**
  302. ## * `incl proc <#incl,PackedSet[A],PackedSet[A]>`_ for including a set
  303. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  304. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  305. runnableExamples:
  306. var a = [1, 5].toPackedSet
  307. a.excl([5].toPackedSet)
  308. assert len(a) == 1
  309. assert 5 notin a
  310. for item in other.items:
  311. excl(s, item)
  312. proc len*[A](s: PackedSet[A]): int {.inline.} =
  313. ## Returns the number of elements in `s`.
  314. runnableExamples:
  315. let a = [1, 3, 5].toPackedSet
  316. assert len(a) == 3
  317. if s.elems < s.a.len:
  318. result = s.elems
  319. else:
  320. result = 0
  321. for _ in s.items:
  322. # pending bug #11167; when fixed, check each explicit `items` to see if it can be removed
  323. inc(result)
  324. proc missingOrExcl*[A](s: var PackedSet[A], key: A): bool =
  325. ## Excludes `key` from the set `s` and tells if `key` was already missing from `s`.
  326. ##
  327. ## The difference with regards to the `excl proc <#excl,PackedSet[A],A>`_ is
  328. ## that this proc returns true if `key` was missing from `s`.
  329. ## The proc will return false if `key` was in `s` and it was removed
  330. ## during this call.
  331. ##
  332. ## **See also:**
  333. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  334. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  335. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  336. runnableExamples:
  337. var a = [5].toPackedSet
  338. assert a.missingOrExcl(5) == false
  339. assert a.missingOrExcl(5) == true
  340. var count = s.len
  341. exclImpl(s, ord(key))
  342. result = count == s.len
  343. proc clear*[A](result: var PackedSet[A]) =
  344. ## Clears the `PackedSet[A]` back to an empty state.
  345. runnableExamples:
  346. var a = [5, 7].toPackedSet
  347. clear(a)
  348. assert len(a) == 0
  349. # setLen(result.data, InitIntSetSize)
  350. # for i in 0..InitIntSetSize - 1: result.data[i] = nil
  351. # result.max = InitIntSetSize - 1
  352. result.data = @[]
  353. result.max = 0
  354. result.counter = 0
  355. result.head = nil
  356. result.elems = 0
  357. proc isNil*[A](x: PackedSet[A]): bool {.inline.} =
  358. ## Returns true if `x` is empty, false otherwise.
  359. runnableExamples:
  360. var a = initPackedSet[int]()
  361. assert a.isNil
  362. a.incl(2)
  363. assert not a.isNil
  364. a.excl(2)
  365. assert a.isNil
  366. x.head.isNil and x.elems == 0
  367. proc assign*[A](dest: var PackedSet[A], src: PackedSet[A]) =
  368. ## Copies `src` to `dest`.
  369. ## `dest` does not need to be initialized by the `initPackedSet proc <#initPackedSet>`_.
  370. runnableExamples:
  371. var
  372. a = initPackedSet[int]()
  373. b = initPackedSet[int]()
  374. b.incl(5)
  375. b.incl(7)
  376. a.assign(b)
  377. assert len(a) == 2
  378. if src.elems <= src.a.len:
  379. dest.data = @[]
  380. dest.max = 0
  381. dest.counter = src.counter
  382. dest.head = nil
  383. dest.elems = src.elems
  384. dest.a = src.a
  385. else:
  386. dest.counter = src.counter
  387. dest.max = src.max
  388. dest.elems = src.elems
  389. newSeq(dest.data, src.data.len)
  390. var it = src.head
  391. while it != nil:
  392. var h = it.key and dest.max
  393. var perturb = it.key
  394. while dest.data[h] != nil: h = nextTry(h, dest.max, perturb)
  395. assert dest.data[h] == nil
  396. var n: Trunk
  397. new(n)
  398. n.next = dest.head
  399. n.key = it.key
  400. n.bits = it.bits
  401. dest.head = n
  402. dest.data[h] = n
  403. it = it.next
  404. proc union*[A](s1, s2: PackedSet[A]): PackedSet[A] =
  405. ## Returns the union of the sets `s1` and `s2`.
  406. ##
  407. ## The same as `s1 + s2 <#+,PackedSet[A],PackedSet[A]>`_.
  408. runnableExamples:
  409. let
  410. a = [1, 2, 3].toPackedSet
  411. b = [3, 4, 5].toPackedSet
  412. c = union(a, b)
  413. assert c.len == 5
  414. assert c == [1, 2, 3, 4, 5].toPackedSet
  415. result.assign(s1)
  416. incl(result, s2)
  417. proc intersection*[A](s1, s2: PackedSet[A]): PackedSet[A] =
  418. ## Returns the intersection of the sets `s1` and `s2`.
  419. ##
  420. ## The same as `s1 * s2 <#*,PackedSet[A],PackedSet[A]>`_.
  421. runnableExamples:
  422. let
  423. a = [1, 2, 3].toPackedSet
  424. b = [3, 4, 5].toPackedSet
  425. c = intersection(a, b)
  426. assert c.len == 1
  427. assert c == [3].toPackedSet
  428. result = initPackedSet[A]()
  429. for item in s1.items:
  430. if contains(s2, item):
  431. incl(result, item)
  432. proc difference*[A](s1, s2: PackedSet[A]): PackedSet[A] =
  433. ## Returns the difference of the sets `s1` and `s2`.
  434. ##
  435. ## The same as `s1 - s2 <#-,PackedSet[A],PackedSet[A]>`_.
  436. runnableExamples:
  437. let
  438. a = [1, 2, 3].toPackedSet
  439. b = [3, 4, 5].toPackedSet
  440. c = difference(a, b)
  441. assert c.len == 2
  442. assert c == [1, 2].toPackedSet
  443. result = initPackedSet[A]()
  444. for item in s1.items:
  445. if not contains(s2, item):
  446. incl(result, item)
  447. proc symmetricDifference*[A](s1, s2: PackedSet[A]): PackedSet[A] =
  448. ## Returns the symmetric difference of the sets `s1` and `s2`.
  449. runnableExamples:
  450. let
  451. a = [1, 2, 3].toPackedSet
  452. b = [3, 4, 5].toPackedSet
  453. c = symmetricDifference(a, b)
  454. assert c.len == 4
  455. assert c == [1, 2, 4, 5].toPackedSet
  456. result.assign(s1)
  457. for item in s2.items:
  458. if containsOrIncl(result, item):
  459. excl(result, item)
  460. proc `+`*[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.} =
  461. ## Alias for `union(s1, s2) <#union,PackedSet[A],PackedSet[A]>`_.
  462. result = union(s1, s2)
  463. proc `*`*[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.} =
  464. ## Alias for `intersection(s1, s2) <#intersection,PackedSet[A],PackedSet[A]>`_.
  465. result = intersection(s1, s2)
  466. proc `-`*[A](s1, s2: PackedSet[A]): PackedSet[A] {.inline.} =
  467. ## Alias for `difference(s1, s2) <#difference,PackedSet[A],PackedSet[A]>`_.
  468. result = difference(s1, s2)
  469. proc disjoint*[A](s1, s2: PackedSet[A]): bool =
  470. ## Returns true if the sets `s1` and `s2` have no items in common.
  471. runnableExamples:
  472. let
  473. a = [1, 2].toPackedSet
  474. b = [2, 3].toPackedSet
  475. c = [3, 4].toPackedSet
  476. assert disjoint(a, b) == false
  477. assert disjoint(a, c) == true
  478. for item in s1.items:
  479. if contains(s2, item):
  480. return false
  481. return true
  482. proc card*[A](s: PackedSet[A]): int {.inline.} =
  483. ## Alias for `len() <#len,PackedSet[A]>`_.
  484. ##
  485. ## Card stands for the [cardinality](http://en.wikipedia.org/wiki/Cardinality)
  486. ## of a set.
  487. result = s.len()
  488. proc `<=`*[A](s1, s2: PackedSet[A]): bool =
  489. ## Returns true if `s1` is a subset of `s2`.
  490. ##
  491. ## A subset `s1` has all of its elements in `s2`, but `s2` doesn't necessarily
  492. ## have more elements than `s1`. That is, `s1` can be equal to `s2`.
  493. runnableExamples:
  494. let
  495. a = [1].toPackedSet
  496. b = [1, 2].toPackedSet
  497. c = [1, 3].toPackedSet
  498. assert a <= b
  499. assert b <= b
  500. assert not (c <= b)
  501. for item in s1.items:
  502. if not s2.contains(item):
  503. return false
  504. return true
  505. proc `<`*[A](s1, s2: PackedSet[A]): bool =
  506. ## Returns true if `s1` is a proper subset of `s2`.
  507. ##
  508. ## A strict or proper subset `s1` has all of its elements in `s2`, but `s2` has
  509. ## more elements than `s1`.
  510. runnableExamples:
  511. let
  512. a = [1].toPackedSet
  513. b = [1, 2].toPackedSet
  514. c = [1, 3].toPackedSet
  515. assert a < b
  516. assert not (b < b)
  517. assert not (c < b)
  518. return s1 <= s2 and not (s2 <= s1)
  519. proc `==`*[A](s1, s2: PackedSet[A]): bool =
  520. ## Returns true if both `s1` and `s2` have the same elements and set size.
  521. runnableExamples:
  522. assert [1, 2].toPackedSet == [2, 1].toPackedSet
  523. assert [1, 2].toPackedSet == [2, 1, 2].toPackedSet
  524. return s1 <= s2 and s2 <= s1
  525. proc `$`*[A](s: PackedSet[A]): string =
  526. ## Converts `s` to a string.
  527. runnableExamples:
  528. let a = [1, 2, 3].toPackedSet
  529. assert $a == "{1, 2, 3}"
  530. dollarImpl()