packedsets.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. ## See also
  15. ## ========
  16. ## * `sets module <sets.html>`_ for more general hash sets
  17. import std/private/since
  18. import hashes
  19. when defined(nimPreviewSlimSystem):
  20. import std/assertions
  21. type
  22. BitScalar = uint
  23. const
  24. InitIntSetSize = 8 # must be a power of two!
  25. TrunkShift = 9
  26. BitsPerTrunk = 1 shl TrunkShift # needs to be a power of 2 and
  27. # divisible by 64
  28. TrunkMask = BitsPerTrunk - 1
  29. IntsPerTrunk = BitsPerTrunk div (sizeof(BitScalar) * 8)
  30. IntShift = 5 + ord(sizeof(BitScalar) == 8) # 5 or 6, depending on int width
  31. IntMask = 1 shl IntShift - 1
  32. type
  33. Trunk {.acyclic.} = ref object
  34. next: Trunk # all nodes are connected with this pointer
  35. key: int # start address at bit 0
  36. bits: array[0..IntsPerTrunk - 1, BitScalar] # a bit vector
  37. TrunkSeq = seq[Trunk]
  38. PackedSet*[A: Ordinal] = object
  39. ## An efficient set of `Ordinal` types implemented as a sparse bit set.
  40. elems: int # only valid for small numbers
  41. counter, max: int
  42. head: Trunk
  43. data: TrunkSeq
  44. a: array[0..33, int] # profiling shows that 34 elements are enough
  45. proc mustRehash[T](t: T): bool {.inline.} =
  46. let length = t.max + 1
  47. assert length > t.counter
  48. result = (length * 2 < t.counter * 3) or (length - t.counter < 4)
  49. proc nextTry(h, maxHash: Hash, perturb: var Hash): Hash {.inline.} =
  50. const PERTURB_SHIFT = 5
  51. var perturb2 = cast[uint](perturb) shr PERTURB_SHIFT
  52. perturb = cast[Hash](perturb2)
  53. result = ((5 * h) + 1 + perturb) and maxHash
  54. proc packedSetGet[A](t: PackedSet[A], key: int): Trunk =
  55. var h = key and t.max
  56. var perturb = key
  57. while t.data[h] != nil:
  58. if t.data[h].key == key:
  59. return t.data[h]
  60. h = nextTry(h, t.max, perturb)
  61. result = nil
  62. proc intSetRawInsert[A](t: PackedSet[A], data: var TrunkSeq, desc: Trunk) =
  63. var h = desc.key and t.max
  64. var perturb = desc.key
  65. while data[h] != nil:
  66. assert data[h] != desc
  67. h = nextTry(h, t.max, perturb)
  68. assert data[h] == nil
  69. data[h] = desc
  70. proc intSetEnlarge[A](t: var PackedSet[A]) =
  71. var n: TrunkSeq
  72. var oldMax = t.max
  73. t.max = ((t.max + 1) * 2) - 1
  74. newSeq(n, t.max + 1)
  75. for i in countup(0, oldMax):
  76. if t.data[i] != nil: intSetRawInsert(t, n, t.data[i])
  77. swap(t.data, n)
  78. proc intSetPut[A](t: var PackedSet[A], key: int): Trunk =
  79. var h = key and t.max
  80. var perturb = key
  81. while t.data[h] != nil:
  82. if t.data[h].key == key:
  83. return t.data[h]
  84. h = nextTry(h, t.max, perturb)
  85. if mustRehash(t): intSetEnlarge(t)
  86. inc(t.counter)
  87. h = key and t.max
  88. perturb = key
  89. while t.data[h] != nil: h = nextTry(h, t.max, perturb)
  90. assert t.data[h] == nil
  91. new(result)
  92. result.next = t.head
  93. result.key = key
  94. t.head = result
  95. t.data[h] = result
  96. proc bitincl[A](s: var PackedSet[A], key: int) {.inline.} =
  97. var t = intSetPut(s, key shr TrunkShift)
  98. var u = key and TrunkMask
  99. t.bits[u shr IntShift] = t.bits[u shr IntShift] or
  100. (BitScalar(1) shl (u and IntMask))
  101. proc exclImpl[A](s: var PackedSet[A], key: int) =
  102. if s.elems <= s.a.len:
  103. for i in 0..<s.elems:
  104. if s.a[i] == key:
  105. s.a[i] = s.a[s.elems - 1]
  106. dec(s.elems)
  107. return
  108. else:
  109. var t = packedSetGet(s, key shr TrunkShift)
  110. if t != nil:
  111. var u = key and TrunkMask
  112. t.bits[u shr IntShift] = t.bits[u shr IntShift] and
  113. not(BitScalar(1) shl (u and IntMask))
  114. template dollarImpl(): untyped =
  115. result = "{"
  116. for key in items(s):
  117. if result.len > 1: result.add(", ")
  118. result.add $key
  119. result.add("}")
  120. iterator items*[A](s: PackedSet[A]): A {.inline.} =
  121. ## Iterates over any included element of `s`.
  122. if s.elems <= s.a.len:
  123. for i in 0..<s.elems:
  124. yield A(s.a[i])
  125. else:
  126. var r = s.head
  127. while r != nil:
  128. var i = 0
  129. while i <= high(r.bits):
  130. var w: uint = r.bits[i]
  131. # taking a copy of r.bits[i] here is correct, because
  132. # modifying operations are not allowed during traversation
  133. var j = 0
  134. while w != 0: # test all remaining bits for zero
  135. if (w and 1) != 0: # the bit is set!
  136. yield A((r.key shl TrunkShift) or (i shl IntShift +% j))
  137. inc(j)
  138. w = w shr 1
  139. inc(i)
  140. r = r.next
  141. proc initPackedSet*[A]: PackedSet[A] =
  142. ## Returns an empty `PackedSet[A]`.
  143. ## `A` must be `Ordinal`.
  144. ##
  145. ## **See also:**
  146. ## * `toPackedSet proc <#toPackedSet,openArray[A]>`_
  147. runnableExamples:
  148. let a = initPackedSet[int]()
  149. assert len(a) == 0
  150. type Id = distinct int
  151. var ids = initPackedSet[Id]()
  152. ids.incl(3.Id)
  153. result = PackedSet[A](
  154. elems: 0,
  155. counter: 0,
  156. max: 0,
  157. head: nil,
  158. data: @[])
  159. # a: array[0..33, int] # profiling shows that 34 elements are enough
  160. proc contains*[A](s: PackedSet[A], key: A): bool =
  161. ## Returns true if `key` is in `s`.
  162. ##
  163. ## This allows the usage of the `in` operator.
  164. runnableExamples:
  165. type ABCD = enum A, B, C, D
  166. let a = [1, 3, 5].toPackedSet
  167. assert a.contains(3)
  168. assert 3 in a
  169. assert not a.contains(8)
  170. assert 8 notin a
  171. let letters = [A, C].toPackedSet
  172. assert A in letters
  173. assert C in letters
  174. assert B notin letters
  175. if s.elems <= s.a.len:
  176. for i in 0..<s.elems:
  177. if s.a[i] == ord(key): return true
  178. else:
  179. var t = packedSetGet(s, ord(key) shr TrunkShift)
  180. if t != nil:
  181. var u = ord(key) and TrunkMask
  182. result = (t.bits[u shr IntShift] and
  183. (BitScalar(1) shl (u and IntMask))) != 0
  184. else:
  185. result = false
  186. proc incl*[A](s: var PackedSet[A], key: A) =
  187. ## Includes an element `key` in `s`.
  188. ##
  189. ## This doesn't do anything if `key` is already in `s`.
  190. ##
  191. ## **See also:**
  192. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  193. ## * `incl proc <#incl,PackedSet[A],PackedSet[A]>`_ for including a set
  194. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  195. runnableExamples:
  196. var a = initPackedSet[int]()
  197. a.incl(3)
  198. a.incl(3)
  199. assert len(a) == 1
  200. if s.elems <= s.a.len:
  201. for i in 0..<s.elems:
  202. if s.a[i] == ord(key): return
  203. if s.elems < s.a.len:
  204. s.a[s.elems] = ord(key)
  205. inc(s.elems)
  206. return
  207. newSeq(s.data, InitIntSetSize)
  208. s.max = InitIntSetSize - 1
  209. for i in 0..<s.elems:
  210. bitincl(s, s.a[i])
  211. s.elems = s.a.len + 1
  212. # fall through:
  213. bitincl(s, ord(key))
  214. proc incl*[A](s: var PackedSet[A], other: PackedSet[A]) =
  215. ## Includes all elements from `other` into `s`.
  216. ##
  217. ## This is the in-place version of `s + other <#+,PackedSet[A],PackedSet[A]>`_.
  218. ##
  219. ## **See also:**
  220. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  221. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  222. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  223. runnableExamples:
  224. var a = [1].toPackedSet
  225. a.incl([5].toPackedSet)
  226. assert len(a) == 2
  227. assert 5 in a
  228. for item in other.items: incl(s, item)
  229. proc toPackedSet*[A](x: openArray[A]): PackedSet[A] {.since: (1, 3).} =
  230. ## Creates a new `PackedSet[A]` that contains the elements of `x`.
  231. ##
  232. ## Duplicates are removed.
  233. ##
  234. ## **See also:**
  235. ## * `initPackedSet proc <#initPackedSet>`_
  236. runnableExamples:
  237. let a = [5, 6, 7, 8, 8].toPackedSet
  238. assert len(a) == 4
  239. assert $a == "{5, 6, 7, 8}"
  240. result = initPackedSet[A]()
  241. for item in x:
  242. result.incl(item)
  243. proc containsOrIncl*[A](s: var PackedSet[A], key: A): bool =
  244. ## Includes `key` in the set `s` and tells if `key` was already in `s`.
  245. ##
  246. ## The difference with regards to the `incl proc <#incl,PackedSet[A],A>`_ is
  247. ## that this proc returns true if `s` already contained `key`. The
  248. ## proc will return false if `key` was added as a new value to `s` during
  249. ## this call.
  250. ##
  251. ## **See also:**
  252. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  253. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  254. runnableExamples:
  255. var a = initPackedSet[int]()
  256. assert a.containsOrIncl(3) == false
  257. assert a.containsOrIncl(3) == true
  258. assert a.containsOrIncl(4) == false
  259. if s.elems <= s.a.len:
  260. for i in 0..<s.elems:
  261. if s.a[i] == ord(key):
  262. return true
  263. incl(s, key)
  264. result = false
  265. else:
  266. var t = packedSetGet(s, ord(key) shr TrunkShift)
  267. if t != nil:
  268. var u = ord(key) and TrunkMask
  269. result = (t.bits[u shr IntShift] and BitScalar(1) shl (u and IntMask)) != 0
  270. if not result:
  271. t.bits[u shr IntShift] = t.bits[u shr IntShift] or
  272. (BitScalar(1) shl (u and IntMask))
  273. else:
  274. incl(s, key)
  275. result = false
  276. proc excl*[A](s: var PackedSet[A], key: A) =
  277. ## Excludes `key` from the set `s`.
  278. ##
  279. ## This doesn't do anything if `key` is not found in `s`.
  280. ##
  281. ## **See also:**
  282. ## * `incl proc <#incl,PackedSet[A],A>`_ for including an element
  283. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  284. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  285. runnableExamples:
  286. var a = [3].toPackedSet
  287. a.excl(3)
  288. a.excl(3)
  289. a.excl(99)
  290. assert len(a) == 0
  291. exclImpl[A](s, ord(key))
  292. proc excl*[A](s: var PackedSet[A], other: PackedSet[A]) =
  293. ## Excludes all elements from `other` from `s`.
  294. ##
  295. ## This is the in-place version of `s - other <#-,PackedSet[A],PackedSet[A]>`_.
  296. ##
  297. ## **See also:**
  298. ## * `incl proc <#incl,PackedSet[A],PackedSet[A]>`_ for including a set
  299. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  300. ## * `missingOrExcl proc <#missingOrExcl,PackedSet[A],A>`_
  301. runnableExamples:
  302. var a = [1, 5].toPackedSet
  303. a.excl([5].toPackedSet)
  304. assert len(a) == 1
  305. assert 5 notin a
  306. for item in other.items:
  307. excl(s, item)
  308. proc len*[A](s: PackedSet[A]): int {.inline.} =
  309. ## Returns the number of elements in `s`.
  310. runnableExamples:
  311. let a = [1, 3, 5].toPackedSet
  312. assert len(a) == 3
  313. if s.elems < s.a.len:
  314. result = s.elems
  315. else:
  316. result = 0
  317. for _ in s.items:
  318. # pending bug #11167; when fixed, check each explicit `items` to see if it can be removed
  319. inc(result)
  320. proc missingOrExcl*[A](s: var PackedSet[A], key: A): bool =
  321. ## Excludes `key` from the set `s` and tells if `key` was already missing from `s`.
  322. ##
  323. ## The difference with regards to the `excl proc <#excl,PackedSet[A],A>`_ is
  324. ## that this proc returns true if `key` was missing from `s`.
  325. ## The proc will return false if `key` was in `s` and it was removed
  326. ## during this call.
  327. ##
  328. ## **See also:**
  329. ## * `excl proc <#excl,PackedSet[A],A>`_ for excluding an element
  330. ## * `excl proc <#excl,PackedSet[A],PackedSet[A]>`_ for excluding a set
  331. ## * `containsOrIncl proc <#containsOrIncl,PackedSet[A],A>`_
  332. runnableExamples:
  333. var a = [5].toPackedSet
  334. assert a.missingOrExcl(5) == false
  335. assert a.missingOrExcl(5) == true
  336. var count = s.len
  337. exclImpl(s, ord(key))
  338. result = count == s.len
  339. proc clear*[A](result: var PackedSet[A]) =
  340. ## Clears the `PackedSet[A]` back to an empty state.
  341. runnableExamples:
  342. var a = [5, 7].toPackedSet
  343. clear(a)
  344. assert len(a) == 0
  345. # setLen(result.data, InitIntSetSize)
  346. # for i in 0..InitIntSetSize - 1: result.data[i] = nil
  347. # result.max = InitIntSetSize - 1
  348. result.data = @[]
  349. result.max = 0
  350. result.counter = 0
  351. result.head = nil
  352. result.elems = 0
  353. proc isNil*[A](x: PackedSet[A]): bool {.inline.} =
  354. ## Returns true if `x` is empty, false otherwise.
  355. runnableExamples:
  356. var a = initPackedSet[int]()
  357. assert a.isNil
  358. a.incl(2)
  359. assert not a.isNil
  360. a.excl(2)
  361. assert a.isNil
  362. x.head.isNil and x.elems == 0
  363. proc `=copy`*[A](dest: var PackedSet[A], src: PackedSet[A]) =
  364. ## Copies `src` to `dest`.
  365. ## `dest` does not need to be initialized by the `initPackedSet proc <#initPackedSet>`_.
  366. if src.elems <= src.a.len:
  367. dest.data = @[]
  368. dest.max = 0
  369. dest.counter = src.counter
  370. dest.head = nil
  371. dest.elems = src.elems
  372. dest.a = src.a
  373. else:
  374. dest.counter = src.counter
  375. dest.max = src.max
  376. dest.elems = src.elems
  377. newSeq(dest.data, src.data.len)
  378. var it = src.head
  379. while it != nil:
  380. var h = it.key and dest.max
  381. var perturb = it.key
  382. while dest.data[h] != nil: h = nextTry(h, dest.max, perturb)
  383. assert dest.data[h] == nil
  384. var n: Trunk
  385. new(n)
  386. n.next = dest.head
  387. n.key = it.key
  388. n.bits = it.bits
  389. dest.head = n
  390. dest.data[h] = n
  391. it = it.next
  392. proc assign*[A](dest: var PackedSet[A], src: PackedSet[A]) {.inline, deprecated.} =
  393. ## Copies `src` to `dest`.
  394. ## `dest` does not need to be initialized by the `initPackedSet proc <#initPackedSet>`_.
  395. runnableExamples:
  396. var
  397. a = initPackedSet[int]()
  398. b = initPackedSet[int]()
  399. b.incl(5)
  400. b.incl(7)
  401. a.assign(b)
  402. assert len(a) == 2
  403. `=copy`(dest, src)
  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()