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.

532 lines
13 KiB

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