btrees.nim 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2018 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## BTree implementation with few features, but good enough for the
  10. ## Nim compiler's needs.
  11. const
  12. M = 512 # max children per B-tree node = M-1
  13. # (must be even and greater than 2)
  14. Mhalf = M div 2
  15. type
  16. Node[Key, Val] = ref object
  17. entries: int
  18. keys: array[M, Key]
  19. case isInternal: bool
  20. of false:
  21. vals: array[M, Val]
  22. of true:
  23. links: array[M, Node[Key, Val]]
  24. BTree*[Key, Val] = object
  25. root: Node[Key, Val]
  26. entries: int ## number of key-value pairs
  27. proc initBTree*[Key, Val](): BTree[Key, Val] =
  28. BTree[Key, Val](root: Node[Key, Val](entries: 0, isInternal: false))
  29. template less(a, b): bool = cmp(a, b) < 0
  30. template eq(a, b): bool = cmp(a, b) == 0
  31. proc getOrDefault*[Key, Val](b: BTree[Key, Val], key: Key): Val =
  32. var x = b.root
  33. while x.isInternal:
  34. for j in 0 ..< x.entries:
  35. if j+1 == x.entries or less(key, x.keys[j+1]):
  36. x = x.links[j]
  37. break
  38. assert(not x.isInternal)
  39. for j in 0 ..< x.entries:
  40. if eq(key, x.keys[j]): return x.vals[j]
  41. proc contains*[Key, Val](b: BTree[Key, Val], key: Key): bool =
  42. var x = b.root
  43. while x.isInternal:
  44. for j in 0 ..< x.entries:
  45. if j+1 == x.entries or less(key, x.keys[j+1]):
  46. x = x.links[j]
  47. break
  48. assert(not x.isInternal)
  49. for j in 0 ..< x.entries:
  50. if eq(key, x.keys[j]): return true
  51. return false
  52. proc copyHalf[Key, Val](h, result: Node[Key, Val]) =
  53. for j in 0 ..< Mhalf:
  54. result.keys[j] = h.keys[Mhalf + j]
  55. if h.isInternal:
  56. for j in 0 ..< Mhalf:
  57. result.links[j] = h.links[Mhalf + j]
  58. else:
  59. for j in 0 ..< Mhalf:
  60. shallowCopy(result.vals[j], h.vals[Mhalf + j])
  61. proc split[Key, Val](h: Node[Key, Val]): Node[Key, Val] =
  62. ## split node in half
  63. result = Node[Key, Val](entries: Mhalf, isInternal: h.isInternal)
  64. h.entries = Mhalf
  65. copyHalf(h, result)
  66. proc insert[Key, Val](h: Node[Key, Val], key: Key, val: Val): Node[Key, Val] =
  67. #var t = Entry(key: key, val: val, next: nil)
  68. var newKey = key
  69. var j = 0
  70. if not h.isInternal:
  71. while j < h.entries:
  72. if less(key, h.keys[j]): break
  73. inc j
  74. for i in countdown(h.entries, j+1):
  75. shallowCopy(h.vals[i], h.vals[i-1])
  76. h.vals[j] = val
  77. else:
  78. var newLink: Node[Key, Val] = nil
  79. while j < h.entries:
  80. if j+1 == h.entries or less(key, h.keys[j+1]):
  81. let u = insert(h.links[j], key, val)
  82. inc j
  83. if u == nil: return nil
  84. newKey = u.keys[0]
  85. newLink = u
  86. break
  87. inc j
  88. for i in countdown(h.entries, j+1):
  89. h.links[i] = h.links[i-1]
  90. h.links[j] = newLink
  91. for i in countdown(h.entries, j+1):
  92. h.keys[i] = h.keys[i-1]
  93. h.keys[j] = newKey
  94. inc h.entries
  95. return if h.entries < M: nil else: split(h)
  96. proc add*[Key, Val](b: var BTree[Key, Val]; key: Key; val: Val) =
  97. let u = insert(b.root, key, val)
  98. inc b.entries
  99. if u == nil: return
  100. # need to split root
  101. let t = Node[Key, Val](entries: 2, isInternal: true)
  102. t.keys[0] = b.root.keys[0]
  103. t.links[0] = b.root
  104. t.keys[1] = u.keys[0]
  105. t.links[1] = u
  106. b.root = t
  107. proc toString[Key, Val](h: Node[Key, Val], indent: string; result: var string) =
  108. if not h.isInternal:
  109. for j in 0..<h.entries:
  110. result.add(indent)
  111. result.add($h.keys[j] & " " & $h.vals[j] & "\n")
  112. else:
  113. for j in 0..<h.entries:
  114. if j > 0: result.add(indent & "(" & $h.keys[j] & ")\n")
  115. toString(h.links[j], indent & " ", result)
  116. proc `$`[Key, Val](b: BTree[Key, Val]): string =
  117. result = ""
  118. toString(b.root, "", result)
  119. proc hasNext*[Key, Val](b: BTree[Key, Val]; index: int): bool =
  120. result = index < b.entries
  121. proc countSubTree[Key, Val](it: Node[Key, Val]): int =
  122. if it.isInternal:
  123. result = 0
  124. for k in 0..<it.entries:
  125. inc result, countSubTree(it.links[k])
  126. else:
  127. result = it.entries
  128. proc next*[Key, Val](b: BTree[Key, Val]; index: int): (Key, Val, int) =
  129. var it = b.root
  130. var i = index
  131. # navigate to the right leaf:
  132. while it.isInternal:
  133. var sum = 0
  134. for k in 0..<it.entries:
  135. let c = countSubTree(it.links[k])
  136. inc sum, c
  137. if sum > i:
  138. it = it.links[k]
  139. dec i, (sum - c)
  140. break
  141. result = (it.keys[i], it.vals[i], index+1)
  142. iterator pairs*[Key, Val](b: BTree[Key, Val]): (Key, Val) =
  143. var i = 0
  144. while hasNext(b, i):
  145. let (k, v, i2) = next(b, i)
  146. i = i2
  147. yield (k, v)
  148. proc len*[Key, Val](b: BTree[Key, Val]): int {.inline.} = b.entries
  149. when isMainModule:
  150. import random, tables
  151. proc main =
  152. var st = initBTree[string, string]()
  153. st.add("www.cs.princeton.edu", "abc")
  154. st.add("www.princeton.edu", "128.112.128.15")
  155. st.add("www.yale.edu", "130.132.143.21")
  156. st.add("www.simpsons.com", "209.052.165.60")
  157. st.add("www.apple.com", "17.112.152.32")
  158. st.add("www.amazon.com", "207.171.182.16")
  159. st.add("www.ebay.com", "66.135.192.87")
  160. st.add("www.cnn.com", "64.236.16.20")
  161. st.add("www.google.com", "216.239.41.99")
  162. st.add("www.nytimes.com", "199.239.136.200")
  163. st.add("www.microsoft.com", "207.126.99.140")
  164. st.add("www.dell.com", "143.166.224.230")
  165. st.add("www.slashdot.org", "66.35.250.151")
  166. st.add("www.espn.com", "199.181.135.201")
  167. st.add("www.weather.com", "63.111.66.11")
  168. st.add("www.yahoo.com", "216.109.118.65")
  169. assert st.getOrDefault("www.cs.princeton.edu") == "abc"
  170. assert st.getOrDefault("www.harvardsucks.com") == nil
  171. assert st.getOrDefault("www.simpsons.com") == "209.052.165.60"
  172. assert st.getOrDefault("www.apple.com") == "17.112.152.32"
  173. assert st.getOrDefault("www.ebay.com") == "66.135.192.87"
  174. assert st.getOrDefault("www.dell.com") == "143.166.224.230"
  175. assert(st.entries == 16)
  176. for k, v in st:
  177. echo k, ": ", v
  178. when false:
  179. var b2 = initBTree[string, string]()
  180. const iters = 10_000
  181. for i in 1..iters:
  182. b2.add($i, $(iters - i))
  183. for i in 1..iters:
  184. let x = b2.getOrDefault($i)
  185. if x != $(iters - i):
  186. echo "got ", x, ", but expected ", iters - i
  187. echo b2.entries
  188. when true:
  189. var b2 = initBTree[int, string]()
  190. var t2 = initTable[int, string]()
  191. const iters = 100_000
  192. for i in 1..iters:
  193. let x = rand(high(int))
  194. if not t2.hasKey(x):
  195. doAssert b2.getOrDefault(x).len == 0, " what, tree has this element " & $x
  196. t2[x] = $x
  197. b2.add(x, $x)
  198. doAssert b2.entries == t2.len
  199. echo "unique entries ", b2.entries
  200. for k, v in t2:
  201. doAssert $k == v
  202. doAssert b2.getOrDefault(k) == $k
  203. main()