tableimpl.nim 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # An `include` file for the different table implementations.
  10. include hashcommon
  11. template rawGetDeepImpl() {.dirty.} = # Search algo for unconditional add
  12. genHashImpl(key, hc)
  13. var h: Hash = hc and maxHash(t)
  14. while isFilled(t.data[h].hcode):
  15. h = nextTry(h, maxHash(t))
  16. result = h
  17. template rawInsertImpl() {.dirty.} =
  18. data[h].key = key
  19. data[h].val = val
  20. data[h].hcode = hc
  21. proc rawGetDeep[X, A](t: X, key: A, hc: var Hash): int {.inline, outParamsAt: [3].} =
  22. rawGetDeepImpl()
  23. proc rawInsert[X, A, B](t: var X, data: var KeyValuePairSeq[A, B],
  24. key: A, val: sink B, hc: Hash, h: Hash) =
  25. rawInsertImpl()
  26. template checkIfInitialized() =
  27. when compiles(defaultInitialSize):
  28. if t.dataLen == 0:
  29. initImpl(t, defaultInitialSize)
  30. template addImpl(enlarge) {.dirty.} =
  31. checkIfInitialized()
  32. if mustRehash(t): enlarge(t)
  33. var hc: Hash
  34. var j = rawGetDeep(t, key, hc)
  35. rawInsert(t, t.data, key, val, hc, j)
  36. inc(t.counter)
  37. template maybeRehashPutImpl(enlarge) {.dirty.} =
  38. checkIfInitialized()
  39. if mustRehash(t):
  40. enlarge(t)
  41. index = rawGetKnownHC(t, key, hc)
  42. index = -1 - index # important to transform for mgetOrPutImpl
  43. rawInsert(t, t.data, key, val, hc, index)
  44. inc(t.counter)
  45. template putImpl(enlarge) {.dirty.} =
  46. checkIfInitialized()
  47. var hc: Hash
  48. var index = rawGet(t, key, hc)
  49. if index >= 0: t.data[index].val = val
  50. else: maybeRehashPutImpl(enlarge)
  51. template mgetOrPutImpl(enlarge) {.dirty.} =
  52. checkIfInitialized()
  53. var hc: Hash
  54. var index = rawGet(t, key, hc)
  55. if index < 0:
  56. # not present: insert (flipping index)
  57. maybeRehashPutImpl(enlarge)
  58. # either way return modifiable val
  59. result = t.data[index].val
  60. template hasKeyOrPutImpl(enlarge) {.dirty.} =
  61. checkIfInitialized()
  62. var hc: Hash
  63. var index = rawGet(t, key, hc)
  64. if index < 0:
  65. result = false
  66. maybeRehashPutImpl(enlarge)
  67. else: result = true
  68. # delImplIdx is KnuthV3 Algo6.4R adapted to i=i+1 (from i=i-1) which has come to
  69. # be called "back shift delete". It shifts elements in the collision cluster of
  70. # a victim backward to make things as-if the victim were never inserted in the
  71. # first place. This is desirable to keep things "ageless" after many deletes.
  72. # It is trickier than you might guess since initial probe (aka "home") locations
  73. # of keys in a cluster may collide and since table addresses wrap around.
  74. #
  75. # A before-after diagram might look like ('.' means empty):
  76. # slot: 0 1 2 3 4 5 6 7
  77. # before(1)
  78. # hash1: 6 7 . 3 . 5 5 6 ; Really hash() and msk
  79. # data1: E F . A . B C D ; About to delete C @index 6
  80. # after(2)
  81. # hash2: 7 . . 3 . 5 6 6 ; Really hash() and msk
  82. # data2: F . . A . B D E ; After deletion of C
  83. #
  84. # This lowers total search depth over the whole table from 1+1+2+2+2+2=10 to 7.
  85. # Had the victim been B@5, C would need back shifting to slot 5. Total depth is
  86. # always lowered by at least 1, e.g. victim A@3. This is all quite fast when
  87. # empty slots are frequent (also needed to keep insert/miss searches fast) and
  88. # hash() is either fast or avoided (via `.hcode`). It need not compare keys.
  89. #
  90. # delImplIdx realizes the above transformation, but only works for dense Linear
  91. # Probing, nextTry(h)=h+1. This is not an important limitation since that's the
  92. # fastest sequence on any CPU made since the 1980s. { Performance analysis often
  93. # overweights "key cmp" neglecting cache behavior, giving bad ideas how big/slow
  94. # tables behave (when perf matters most!). Comparing hcode first means usually
  95. # only 1 key cmp is needed for *any* seq. Timing only predictable activity,
  96. # small tables, and/or integer keys often perpetuates such bad ideas. }
  97. template delImplIdx(t, i, makeEmpty, cellEmpty, cellHash) =
  98. let msk = maxHash(t)
  99. if i >= 0:
  100. dec(t.counter)
  101. block outer:
  102. while true: # KnuthV3 Algo6.4R adapted for i=i+1 instead of i=i-1
  103. var j = i # The correctness of this depends on (h+1) in nextTry
  104. var r = j # though may be adaptable to other simple sequences.
  105. makeEmpty(i) # mark current EMPTY
  106. t.data[i].key = default(typeof(t.data[i].key))
  107. t.data[i].val = default(typeof(t.data[i].val))
  108. while true:
  109. i = (i + 1) and msk # increment mod table size
  110. if cellEmpty(i): # end of collision cluster; So all done
  111. break outer
  112. r = cellHash(i) and msk # initial probe index for key@slot i
  113. if not ((i >= r and r > j) or (r > j and j > i) or (j > i and i >= r)):
  114. break
  115. when defined(js):
  116. t.data[j] = t.data[i]
  117. else:
  118. t.data[j] = move(t.data[i]) # data[j] will be marked EMPTY next loop
  119. template delImpl(makeEmpty, cellEmpty, cellHash) {.dirty.} =
  120. var hc: Hash
  121. var i = rawGet(t, key, hc)
  122. delImplIdx(t, i, makeEmpty, cellEmpty, cellHash)
  123. template delImplNoHCode(makeEmpty, cellEmpty, cellHash) {.dirty.} =
  124. if t.dataLen > 0:
  125. var i: Hash = hash(key) and maxHash(t)
  126. while not cellEmpty(i):
  127. if t.data[i].key == key:
  128. delImplIdx(t, i, makeEmpty, cellEmpty, cellHash)
  129. break
  130. i = nextTry(i, maxHash(t))
  131. template clearImpl() {.dirty.} =
  132. for i in 0 ..< t.dataLen:
  133. when compiles(t.data[i].hcode): # CountTable records don't contain a hcode
  134. t.data[i].hcode = 0
  135. t.data[i].key = default(typeof(t.data[i].key))
  136. t.data[i].val = default(typeof(t.data[i].val))
  137. t.counter = 0
  138. template ctAnd(a, b): bool =
  139. when a:
  140. when b: true
  141. else: false
  142. else: false
  143. template initImpl(result: typed, size: int) =
  144. let correctSize = slotsNeeded(size)
  145. when ctAnd(declared(SharedTable), typeof(result) is SharedTable):
  146. init(result, correctSize)
  147. else:
  148. result.counter = 0
  149. newSeq(result.data, correctSize)
  150. when compiles(result.first):
  151. result.first = -1
  152. result.last = -1
  153. template insertImpl() = # for CountTable
  154. if t.dataLen == 0: initImpl(t, defaultInitialSize)
  155. if mustRehash(t): enlarge(t)
  156. ctRawInsert(t, t.data, key, val)
  157. inc(t.counter)
  158. template getOrDefaultImpl(t, key): untyped =
  159. mixin rawGet
  160. var hc: Hash
  161. var index = rawGet(t, key, hc)
  162. if index >= 0: result = t.data[index].val
  163. template getOrDefaultImpl(t, key, default: untyped): untyped =
  164. mixin rawGet
  165. var hc: Hash
  166. var index = rawGet(t, key, hc)
  167. result = if index >= 0: t.data[index].val else: default
  168. template dollarImpl(): untyped {.dirty.} =
  169. if t.len == 0:
  170. result = "{:}"
  171. else:
  172. result = "{"
  173. for key, val in pairs(t):
  174. if result.len > 1: result.add(", ")
  175. result.addQuoted(key)
  176. result.add(": ")
  177. result.addQuoted(val)
  178. result.add("}")
  179. template equalsImpl(s, t: typed) =
  180. if s.counter == t.counter:
  181. # different insertion orders mean different 'data' seqs, so we have
  182. # to use the slow route here:
  183. for key, val in s:
  184. if not t.hasKey(key): return false
  185. if t.getOrDefault(key) != val: return false
  186. return true