You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

480 lines
11 KiB

  1. package skiplist
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/bits"
  6. "math/rand"
  7. "time"
  8. )
  9. const (
  10. // maxLevel denotes the maximum height of the skiplist. This height will keep the skiplist
  11. // efficient for up to 34m entries. If there is a need for much more, please adjust this constant accordingly.
  12. maxLevel = 25
  13. )
  14. type SkipList struct {
  15. startLevels [maxLevel]*SkipListElementReference
  16. endLevels [maxLevel]*SkipListElementReference
  17. maxNewLevel int
  18. maxLevel int
  19. elementCount int
  20. }
  21. // NewSeedEps returns a new empty, initialized Skiplist.
  22. // Given a seed, a deterministic height/list behaviour can be achieved.
  23. // Eps is used to compare keys given by the ExtractKey() function on equality.
  24. func NewSeed(seed int64) *SkipList {
  25. // Initialize random number generator.
  26. rand.Seed(seed)
  27. //fmt.Printf("SkipList seed: %v\n", seed)
  28. list := &SkipList{
  29. maxNewLevel: maxLevel,
  30. maxLevel: 0,
  31. elementCount: 0,
  32. }
  33. return list
  34. }
  35. // New returns a new empty, initialized Skiplist.
  36. func New() *SkipList {
  37. return NewSeed(time.Now().UTC().UnixNano())
  38. }
  39. // IsEmpty checks, if the skiplist is empty.
  40. func (t *SkipList) IsEmpty() bool {
  41. return t.startLevels[0] == nil
  42. }
  43. func (t *SkipList) generateLevel(maxLevel int) int {
  44. level := maxLevel - 1
  45. // First we apply some mask which makes sure that we don't get a level
  46. // above our desired level. Then we find the first set bit.
  47. var x = rand.Uint64() & ((1 << uint(maxLevel-1)) - 1)
  48. zeroes := bits.TrailingZeros64(x)
  49. if zeroes <= maxLevel {
  50. level = zeroes
  51. }
  52. return level
  53. }
  54. func (t *SkipList) findEntryIndex(key []byte, level int) int {
  55. // Find good entry point so we don't accidentally skip half the list.
  56. for i := t.maxLevel; i >= 0; i-- {
  57. if t.startLevels[i] != nil && bytes.Compare(t.startLevels[i].Key, key) < 0 || i <= level {
  58. return i
  59. }
  60. }
  61. return 0
  62. }
  63. func (t *SkipList) findExtended(key []byte, findGreaterOrEqual bool) (foundElem *SkipListElement, ok bool) {
  64. foundElem = nil
  65. ok = false
  66. if t.IsEmpty() {
  67. return
  68. }
  69. index := t.findEntryIndex(key, 0)
  70. var currentNode *SkipListElement
  71. currentNode = t.startLevels[index].Load()
  72. // In case, that our first element is already greater-or-equal!
  73. if findGreaterOrEqual && compareElement(currentNode, key) > 0 {
  74. foundElem = currentNode
  75. ok = true
  76. return
  77. }
  78. for {
  79. if compareElement(currentNode, key) == 0 {
  80. foundElem = currentNode
  81. ok = true
  82. return
  83. }
  84. // Which direction are we continuing next time?
  85. if currentNode.Next[index] != nil && bytes.Compare(currentNode.Next[index].Key, key) <= 0 {
  86. // Go right
  87. currentNode = currentNode.Next[index].Load()
  88. } else {
  89. if index > 0 {
  90. // Early exit
  91. if currentNode.Next[0] != nil && bytes.Compare(currentNode.Next[0].Key, key) == 0 {
  92. currentNodeNext := currentNode.Next[0].Load()
  93. foundElem = currentNodeNext
  94. ok = true
  95. return
  96. }
  97. // Go down
  98. index--
  99. } else {
  100. // Element is not found and we reached the bottom.
  101. if findGreaterOrEqual {
  102. foundElem = currentNode.Next[index].Load()
  103. ok = foundElem != nil
  104. }
  105. return
  106. }
  107. }
  108. }
  109. }
  110. // Find tries to find an element in the skiplist based on the key from the given ListElement.
  111. // elem can be used, if ok is true.
  112. // Find runs in approx. O(log(n))
  113. func (t *SkipList) Find(key []byte) (elem *SkipListElement, ok bool) {
  114. if t == nil || key == nil {
  115. return
  116. }
  117. elem, ok = t.findExtended(key, false)
  118. return
  119. }
  120. // FindGreaterOrEqual finds the first element, that is greater or equal to the given ListElement e.
  121. // The comparison is done on the keys (So on ExtractKey()).
  122. // FindGreaterOrEqual runs in approx. O(log(n))
  123. func (t *SkipList) FindGreaterOrEqual(key []byte) (elem *SkipListElement, ok bool) {
  124. if t == nil || key == nil {
  125. return
  126. }
  127. elem, ok = t.findExtended(key, true)
  128. return
  129. }
  130. // Delete removes an element equal to e from the skiplist, if there is one.
  131. // If there are multiple entries with the same value, Delete will remove one of them
  132. // (Which one will change based on the actual skiplist layout)
  133. // Delete runs in approx. O(log(n))
  134. func (t *SkipList) Delete(key []byte) {
  135. if t == nil || t.IsEmpty() || key == nil {
  136. return
  137. }
  138. index := t.findEntryIndex(key, t.maxLevel)
  139. var currentNode *SkipListElement
  140. var nextNode *SkipListElement
  141. for {
  142. if currentNode == nil {
  143. nextNode = t.startLevels[index].Load()
  144. } else {
  145. nextNode = currentNode.Next[index].Load()
  146. }
  147. // Found and remove!
  148. if nextNode != nil && compareElement(nextNode, key) == 0 {
  149. if currentNode != nil {
  150. currentNode.Next[index] = nextNode.Next[index]
  151. currentNode.Save()
  152. }
  153. if index == 0 {
  154. if nextNode.Next[index] != nil {
  155. nextNextNode := nextNode.Next[index].Load()
  156. nextNextNode.Prev = currentNode.Reference()
  157. nextNextNode.Save()
  158. }
  159. t.elementCount--
  160. nextNode.DeleteSelf()
  161. }
  162. // Link from start needs readjustments.
  163. startNextKey := t.startLevels[index].Key
  164. if compareElement(nextNode, startNextKey) == 0 {
  165. t.startLevels[index] = nextNode.Next[index]
  166. // This was our currently highest node!
  167. if t.startLevels[index] == nil {
  168. t.maxLevel = index - 1
  169. }
  170. }
  171. // Link from end needs readjustments.
  172. if nextNode.Next[index] == nil {
  173. t.endLevels[index] = currentNode.Reference()
  174. }
  175. nextNode.Next[index] = nil
  176. }
  177. if nextNode != nil && compareElement(nextNode, key) < 0 {
  178. // Go right
  179. currentNode = nextNode
  180. } else {
  181. // Go down
  182. index--
  183. if index < 0 {
  184. break
  185. }
  186. }
  187. }
  188. }
  189. // Insert inserts the given ListElement into the skiplist.
  190. // Insert runs in approx. O(log(n))
  191. func (t *SkipList) Insert(key []byte) {
  192. if t == nil || key == nil {
  193. return
  194. }
  195. level := t.generateLevel(t.maxNewLevel)
  196. // Only grow the height of the skiplist by one at a time!
  197. if level > t.maxLevel {
  198. level = t.maxLevel + 1
  199. t.maxLevel = level
  200. }
  201. elem := &SkipListElement{
  202. Id: rand.Int63(),
  203. Next: make([]*SkipListElementReference, t.maxNewLevel, t.maxNewLevel),
  204. Level: int32(level),
  205. Values: [][]byte{key},
  206. }
  207. t.elementCount++
  208. newFirst := true
  209. newLast := true
  210. if !t.IsEmpty() {
  211. newFirst = compareElement(elem, t.startLevels[0].Key) < 0
  212. newLast = compareElement(elem, t.endLevels[0].Key) > 0
  213. }
  214. normallyInserted := false
  215. if !newFirst && !newLast {
  216. normallyInserted = true
  217. index := t.findEntryIndex(key, level)
  218. var currentNode *SkipListElement
  219. var nextNodeRef *SkipListElementReference
  220. for {
  221. if currentNode == nil {
  222. nextNodeRef = t.startLevels[index]
  223. } else {
  224. nextNodeRef = currentNode.Next[index]
  225. }
  226. var nextNode *SkipListElement
  227. // Connect node to next
  228. if index <= level && (nextNodeRef == nil || bytes.Compare(nextNodeRef.Key, key) > 0) {
  229. elem.Next[index] = nextNodeRef
  230. if currentNode != nil {
  231. currentNode.Next[index] = elem.Reference()
  232. currentNode.Save()
  233. }
  234. if index == 0 {
  235. elem.Prev = currentNode.Reference()
  236. if nextNodeRef != nil {
  237. nextNode = nextNodeRef.Load()
  238. nextNode.Prev = elem.Reference()
  239. nextNode.Save()
  240. }
  241. }
  242. }
  243. if nextNodeRef != nil && bytes.Compare(nextNodeRef.Key, key) <= 0 {
  244. // Go right
  245. if nextNode == nil {
  246. // reuse nextNode when index == 0
  247. nextNode = nextNodeRef.Load()
  248. }
  249. currentNode = nextNode
  250. } else {
  251. // Go down
  252. index--
  253. if index < 0 {
  254. break
  255. }
  256. }
  257. }
  258. }
  259. // Where we have a left-most position that needs to be referenced!
  260. for i := level; i >= 0; i-- {
  261. didSomething := false
  262. if newFirst || normallyInserted {
  263. if t.startLevels[i] == nil || bytes.Compare(t.startLevels[i].Key, key) > 0 {
  264. if i == 0 && t.startLevels[i] != nil {
  265. startLevelElement := t.startLevels[i].Load()
  266. startLevelElement.Prev = elem.Reference()
  267. startLevelElement.Save()
  268. }
  269. elem.Next[i] = t.startLevels[i]
  270. t.startLevels[i] = elem.Reference()
  271. }
  272. // link the endLevels to this element!
  273. if elem.Next[i] == nil {
  274. t.endLevels[i] = elem.Reference()
  275. }
  276. didSomething = true
  277. }
  278. if newLast {
  279. // Places the element after the very last element on this level!
  280. // This is very important, so we are not linking the very first element (newFirst AND newLast) to itself!
  281. if !newFirst {
  282. if t.endLevels[i] != nil {
  283. endLevelElement := t.endLevels[i].Load()
  284. endLevelElement.Next[i] = elem.Reference()
  285. endLevelElement.Save()
  286. }
  287. if i == 0 {
  288. elem.Prev = t.endLevels[i]
  289. }
  290. t.endLevels[i] = elem.Reference()
  291. }
  292. // Link the startLevels to this element!
  293. if t.startLevels[i] == nil || bytes.Compare(t.startLevels[i].Key, key) > 0 {
  294. t.startLevels[i] = elem.Reference()
  295. }
  296. didSomething = true
  297. }
  298. if !didSomething {
  299. break
  300. }
  301. }
  302. elem.Save()
  303. }
  304. // GetValue extracts the ListElement value from a skiplist node.
  305. func (e *SkipListElement) GetValue() []byte {
  306. return e.Values[0]
  307. }
  308. // GetSmallestNode returns the very first/smallest node in the skiplist.
  309. // GetSmallestNode runs in O(1)
  310. func (t *SkipList) GetSmallestNode() *SkipListElement {
  311. return t.startLevels[0].Load()
  312. }
  313. // GetLargestNode returns the very last/largest node in the skiplist.
  314. // GetLargestNode runs in O(1)
  315. func (t *SkipList) GetLargestNode() *SkipListElement {
  316. return t.endLevels[0].Load()
  317. }
  318. // Next returns the next element based on the given node.
  319. // Next will loop around to the first node, if you call it on the last!
  320. func (t *SkipList) Next(e *SkipListElement) *SkipListElement {
  321. if e.Next[0] == nil {
  322. return t.startLevels[0].Load()
  323. }
  324. return e.Next[0].Load()
  325. }
  326. // Prev returns the previous element based on the given node.
  327. // Prev will loop around to the last node, if you call it on the first!
  328. func (t *SkipList) Prev(e *SkipListElement) *SkipListElement {
  329. if e.Prev == nil {
  330. return t.endLevels[0].Load()
  331. }
  332. return e.Prev.Load()
  333. }
  334. // GetNodeCount returns the number of nodes currently in the skiplist.
  335. func (t *SkipList) GetNodeCount() int {
  336. return t.elementCount
  337. }
  338. // String returns a string format of the skiplist. Useful to get a graphical overview and/or debugging.
  339. func (t *SkipList) println() {
  340. print("start --> ")
  341. for i, l := range t.startLevels {
  342. if l == nil {
  343. break
  344. }
  345. if i > 0 {
  346. print(" -> ")
  347. }
  348. next := "---"
  349. if l != nil {
  350. next = string(l.Key)
  351. }
  352. print(fmt.Sprintf("[%v]", next))
  353. }
  354. println()
  355. nodeRef := t.startLevels[0]
  356. for nodeRef != nil {
  357. print(fmt.Sprintf("%v: ", string(nodeRef.Key)))
  358. node := nodeRef.Load()
  359. for i := 0; i <= int(node.Level); i++ {
  360. l := node.Next[i]
  361. next := "---"
  362. if l != nil {
  363. next = string(l.Key)
  364. }
  365. if i == 0 {
  366. prev := "---"
  367. if node.Prev != nil {
  368. prev = string(node.Prev.Key)
  369. }
  370. print(fmt.Sprintf("[%v|%v]", prev, next))
  371. } else {
  372. print(fmt.Sprintf("[%v]", next))
  373. }
  374. if i < int(node.Level) {
  375. print(" -> ")
  376. }
  377. }
  378. println()
  379. nodeRef = node.Next[0]
  380. }
  381. print("end --> ")
  382. for i, l := range t.endLevels {
  383. if l == nil {
  384. break
  385. }
  386. if i > 0 {
  387. print(" -> ")
  388. }
  389. next := "---"
  390. if l != nil {
  391. next = string(l.Key)
  392. }
  393. print(fmt.Sprintf("[%v]", next))
  394. }
  395. println()
  396. }