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.

531 lines
12 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, level 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 <= level {
  61. return i
  62. }
  63. }
  64. return 0
  65. }
  66. func (t *SkipList) findExtended(key []byte, findGreaterOrEqual bool) (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. var currentNodeNext *SkipListElement
  102. currentNodeNext, err = t.loadElement(currentNode.Next[0])
  103. if err != nil {
  104. return
  105. }
  106. foundElem = currentNodeNext
  107. ok = true
  108. return
  109. }
  110. // Go down
  111. index--
  112. } else {
  113. // Element is not found and we reached the bottom.
  114. if findGreaterOrEqual {
  115. foundElem, err = t.loadElement(currentNode.Next[index])
  116. if err != nil {
  117. return
  118. }
  119. ok = foundElem != nil
  120. }
  121. return
  122. }
  123. }
  124. }
  125. }
  126. // Find tries to find an element in the skiplist based on the key from the given ListElement.
  127. // elem can be used, if ok is true.
  128. // Find runs in approx. O(log(n))
  129. func (t *SkipList) Find(key []byte) (elem *SkipListElement, ok bool, err error) {
  130. if t == nil || key == nil {
  131. return
  132. }
  133. elem, ok, err = t.findExtended(key, false)
  134. return
  135. }
  136. // FindGreaterOrEqual finds the first element, that is greater or equal to the given ListElement e.
  137. // The comparison is done on the keys (So on ExtractKey()).
  138. // FindGreaterOrEqual runs in approx. O(log(n))
  139. func (t *SkipList) FindGreaterOrEqual(key []byte) (elem *SkipListElement, ok bool, err error) {
  140. if t == nil || key == nil {
  141. return
  142. }
  143. elem, ok, err = t.findExtended(key, true)
  144. return
  145. }
  146. // Delete removes an element equal to e from the skiplist, if there is one.
  147. // If there are multiple entries with the same value, Delete will remove one of them
  148. // (Which one will change based on the actual skiplist layout)
  149. // Delete runs in approx. O(log(n))
  150. func (t *SkipList) Delete(key []byte) (err error) {
  151. if t == nil || t.IsEmpty() || key == nil {
  152. return
  153. }
  154. index := t.findEntryIndex(key, t.maxLevel)
  155. var currentNode *SkipListElement
  156. var nextNode *SkipListElement
  157. for {
  158. if currentNode == nil {
  159. nextNode, err = t.loadElement(t.startLevels[index])
  160. } else {
  161. nextNode, err = t.loadElement(currentNode.Next[index])
  162. }
  163. if err != nil {
  164. return err
  165. }
  166. // Found and remove!
  167. if nextNode != nil && compareElement(nextNode, key) == 0 {
  168. if currentNode != nil {
  169. currentNode.Next[index] = nextNode.Next[index]
  170. if err = t.saveElement(currentNode); err != nil {
  171. return err
  172. }
  173. }
  174. if index == 0 {
  175. if nextNode.Next[index] != nil {
  176. nextNextNode, err := t.loadElement(nextNode.Next[index])
  177. if err != nil {
  178. return err
  179. }
  180. nextNextNode.Prev = currentNode.Reference()
  181. if err = t.saveElement(nextNextNode); err != nil {
  182. return err
  183. }
  184. }
  185. // t.elementCount--
  186. if err = t.deleteElement(nextNode); err != nil {
  187. return err
  188. }
  189. }
  190. // Link from start needs readjustments.
  191. startNextKey := t.startLevels[index].Key
  192. if compareElement(nextNode, startNextKey) == 0 {
  193. t.startLevels[index] = nextNode.Next[index]
  194. // This was our currently highest node!
  195. if t.startLevels[index] == nil {
  196. t.maxLevel = index - 1
  197. }
  198. }
  199. // Link from end needs readjustments.
  200. if nextNode.Next[index] == nil {
  201. t.endLevels[index] = currentNode.Reference()
  202. }
  203. nextNode.Next[index] = nil
  204. }
  205. if nextNode != nil && compareElement(nextNode, key) < 0 {
  206. // Go right
  207. currentNode = nextNode
  208. } else {
  209. // Go down
  210. index--
  211. if index < 0 {
  212. break
  213. }
  214. }
  215. }
  216. return
  217. }
  218. // Insert inserts the given ListElement into the skiplist.
  219. // Insert runs in approx. O(log(n))
  220. func (t *SkipList) Insert(key, value []byte) (err error){
  221. if t == nil || key == nil {
  222. return
  223. }
  224. level := t.generateLevel(t.maxNewLevel)
  225. // Only grow the height of the skiplist by one at a time!
  226. if level > t.maxLevel {
  227. level = t.maxLevel + 1
  228. t.maxLevel = level
  229. }
  230. elem := &SkipListElement{
  231. Id: rand.Int63(),
  232. Next: make([]*SkipListElementReference, t.maxNewLevel, t.maxNewLevel),
  233. Level: int32(level),
  234. Key: key,
  235. Value: value,
  236. }
  237. // t.elementCount++
  238. newFirst := true
  239. newLast := true
  240. if !t.IsEmpty() {
  241. newFirst = compareElement(elem, t.startLevels[0].Key) < 0
  242. newLast = compareElement(elem, t.endLevels[0].Key) > 0
  243. }
  244. normallyInserted := false
  245. if !newFirst && !newLast {
  246. normallyInserted = true
  247. index := t.findEntryIndex(key, level)
  248. var currentNode *SkipListElement
  249. var nextNodeRef *SkipListElementReference
  250. for {
  251. if currentNode == nil {
  252. nextNodeRef = t.startLevels[index]
  253. } else {
  254. nextNodeRef = currentNode.Next[index]
  255. }
  256. var nextNode *SkipListElement
  257. // Connect node to next
  258. if index <= level && (nextNodeRef == nil || bytes.Compare(nextNodeRef.Key, key) > 0) {
  259. elem.Next[index] = nextNodeRef
  260. if currentNode != nil {
  261. currentNode.Next[index] = elem.Reference()
  262. if err = t.saveElement(currentNode); err != nil {
  263. return
  264. }
  265. }
  266. if index == 0 {
  267. elem.Prev = currentNode.Reference()
  268. if nextNodeRef != nil {
  269. if nextNode, err = t.loadElement(nextNodeRef); err != nil {
  270. return
  271. }
  272. nextNode.Prev = elem.Reference()
  273. if err = t.saveElement(nextNode); err != nil {
  274. return
  275. }
  276. }
  277. }
  278. }
  279. if nextNodeRef != nil && bytes.Compare(nextNodeRef.Key, key) <= 0 {
  280. // Go right
  281. if nextNode == nil {
  282. // reuse nextNode when index == 0
  283. if nextNode, err = t.loadElement(nextNodeRef); err != nil {
  284. return
  285. }
  286. }
  287. currentNode = nextNode
  288. } else {
  289. // Go down
  290. index--
  291. if index < 0 {
  292. break
  293. }
  294. }
  295. }
  296. }
  297. // Where we have a left-most position that needs to be referenced!
  298. for i := level; i >= 0; i-- {
  299. didSomething := false
  300. if newFirst || normallyInserted {
  301. if t.startLevels[i] == nil || bytes.Compare(t.startLevels[i].Key, key) > 0 {
  302. if i == 0 && t.startLevels[i] != nil {
  303. startLevelElement, err := t.loadElement(t.startLevels[i])
  304. if err != nil {
  305. return err
  306. }
  307. startLevelElement.Prev = elem.Reference()
  308. if err = t.saveElement(startLevelElement); err != nil {
  309. return err
  310. }
  311. }
  312. elem.Next[i] = t.startLevels[i]
  313. t.startLevels[i] = elem.Reference()
  314. }
  315. // link the endLevels to this element!
  316. if elem.Next[i] == nil {
  317. t.endLevels[i] = elem.Reference()
  318. }
  319. didSomething = true
  320. }
  321. if newLast {
  322. // Places the element after the very last element on this level!
  323. // This is very important, so we are not linking the very first element (newFirst AND newLast) to itself!
  324. if !newFirst {
  325. if t.endLevels[i] != nil {
  326. endLevelElement, err := t.loadElement(t.endLevels[i])
  327. if err != nil {
  328. return err
  329. }
  330. endLevelElement.Next[i] = elem.Reference()
  331. if err = t.saveElement(endLevelElement); err != nil {
  332. return err
  333. }
  334. }
  335. if i == 0 {
  336. elem.Prev = t.endLevels[i]
  337. }
  338. t.endLevels[i] = elem.Reference()
  339. }
  340. // Link the startLevels to this element!
  341. if t.startLevels[i] == nil || bytes.Compare(t.startLevels[i].Key, key) > 0 {
  342. t.startLevels[i] = elem.Reference()
  343. }
  344. didSomething = true
  345. }
  346. if !didSomething {
  347. break
  348. }
  349. }
  350. if err = t.saveElement(elem); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. // GetSmallestNode returns the very first/smallest node in the skiplist.
  356. // GetSmallestNode runs in O(1)
  357. func (t *SkipList) GetSmallestNode() (*SkipListElement, error) {
  358. return t.loadElement(t.startLevels[0])
  359. }
  360. // GetLargestNode returns the very last/largest node in the skiplist.
  361. // GetLargestNode runs in O(1)
  362. func (t *SkipList) GetLargestNode() (*SkipListElement, error) {
  363. return t.loadElement(t.endLevels[0])
  364. }
  365. // Next returns the next element based on the given node.
  366. // Next will loop around to the first node, if you call it on the last!
  367. func (t *SkipList) Next(e *SkipListElement) (*SkipListElement, error) {
  368. if e.Next[0] == nil {
  369. return t.loadElement(t.startLevels[0])
  370. }
  371. return t.loadElement(e.Next[0])
  372. }
  373. // Prev returns the previous element based on the given node.
  374. // Prev will loop around to the last node, if you call it on the first!
  375. func (t *SkipList) Prev(e *SkipListElement) (*SkipListElement, error) {
  376. if e.Prev == nil {
  377. return t.loadElement(t.endLevels[0])
  378. }
  379. return t.loadElement(e.Prev)
  380. }
  381. // ChangeValue can be used to change the actual value of a node in the skiplist
  382. // without the need of Deleting and reinserting the node again.
  383. // Be advised, that ChangeValue only works, if the actual key from ExtractKey() will stay the same!
  384. // ok is an indicator, wether the value is actually changed.
  385. func (t *SkipList) ChangeValue(e *SkipListElement, newValue []byte) (err error) {
  386. // The key needs to stay correct, so this is very important!
  387. e.Value = newValue
  388. return t.saveElement(e)
  389. }
  390. // String returns a string format of the skiplist. Useful to get a graphical overview and/or debugging.
  391. func (t *SkipList) println() {
  392. print("start --> ")
  393. for i, l := range t.startLevels {
  394. if l == nil {
  395. break
  396. }
  397. if i > 0 {
  398. print(" -> ")
  399. }
  400. next := "---"
  401. if l != nil {
  402. next = string(l.Key)
  403. }
  404. print(fmt.Sprintf("[%v]", next))
  405. }
  406. println()
  407. nodeRef := t.startLevels[0]
  408. for nodeRef != nil {
  409. print(fmt.Sprintf("%v: ", string(nodeRef.Key)))
  410. node, _ := t.loadElement(nodeRef)
  411. for i := 0; i <= int(node.Level); i++ {
  412. l := node.Next[i]
  413. next := "---"
  414. if l != nil {
  415. next = string(l.Key)
  416. }
  417. if i == 0 {
  418. prev := "---"
  419. if node.Prev != nil {
  420. prev = string(node.Prev.Key)
  421. }
  422. print(fmt.Sprintf("[%v|%v]", prev, next))
  423. } else {
  424. print(fmt.Sprintf("[%v]", next))
  425. }
  426. if i < int(node.Level) {
  427. print(" -> ")
  428. }
  429. }
  430. println()
  431. nodeRef = node.Next[0]
  432. }
  433. print("end --> ")
  434. for i, l := range t.endLevels {
  435. if l == nil {
  436. break
  437. }
  438. if i > 0 {
  439. print(" -> ")
  440. }
  441. next := "---"
  442. if l != nil {
  443. next = string(l.Key)
  444. }
  445. print(fmt.Sprintf("[%v]", next))
  446. }
  447. println()
  448. }