Debian Codegraph @

skiplist/skiplist.go

raw symbols SCIP
1 // Copyright 2012 Google Inc. All rights reserved.
2 // Author: Ric Szopa (Ryszard) <[email protected]>
3
4 // Package skiplist implements skip list based maps and sets.
5 //
6 // Skip lists are a data structure that can be used in place of
7 // balanced trees. Skip lists use probabilistic balancing rather than
8 // strictly enforced balancing and as a result the algorithms for
9 // insertion and deletion in skip lists are much simpler and
10 // significantly faster than equivalent algorithms for balanced trees.
11 //
12 // Skip lists were first described in Pugh, William (June 1990). "Skip
13 // lists: a probabilistic alternative to balanced
14 // trees". Communications of the ACM 33 (6): 668–676
15 package skiplist
16
17 import (
18 "math/rand"
19 )
20
21 // TODO(ryszard):
22 // - A separately seeded source of randomness
23
24 // p is the fraction of nodes with level i pointers that also have
25 // level i+1 pointers. p equal to 1/4 is a good value from the point
26 // of view of speed and space requirements. If variability of running
27 // times is a concern, 1/2 is a better value for p.
28 const p = 0.25
29
30 const DefaultMaxLevel = 32
31
32 // A node is a container for key-value pairs that are stored in a skip
33 // list.
34 type node struct {
35 forward []*node
36 backward *node
37 key, value interface{}
38 }
39
40 // next returns the next node in the skip list containing n.
41 func (n *node) next() *node {
42 if len(n.forward) == 0 {
43 return nil
44 }
45 return n.forward[0]
46 }
47
48 // previous returns the previous node in the skip list containing n.
49 func (n *node) previous() *node {
50 return n.backward
51 }
52
53 // hasNext returns true if n has a next node.
54 func (n *node) hasNext() bool {
55 return n.next() != nil
56 }
57
58 // hasPrevious returns true if n has a previous node.
59 func (n *node) hasPrevious() bool {
60 return n.previous() != nil
61 }
62
63 // A SkipList is a map-like data structure that maintains an ordered
64 // collection of key-value pairs. Insertion, lookup, and deletion are
65 // all O(log n) operations. A SkipList can efficiently store up to
66 // 2^MaxLevel items.
67 //
68 // To iterate over a skip list (where s is a
69 // *SkipList):
70 //
71 // for i := s.Iterator(); i.Next(); {
72 // // do something with i.Key() and i.Value()
73 // }
74 type SkipList struct {
75 lessThan func(l, r interface{}) bool
76 header *node
77 footer *node
78 length int
79 // MaxLevel determines how many items the SkipList can store
80 // efficiently (2^MaxLevel).
81 //
82 // It is safe to increase MaxLevel to accomodate more
83 // elements. If you decrease MaxLevel and the skip list
84 // already contains nodes on higer levels, the effective
85 // MaxLevel will be the greater of the new MaxLevel and the
86 // level of the highest node.
87 //
88 // A SkipList with MaxLevel equal to 0 is equivalent to a
89 // standard linked list and will not have any of the nice
90 // properties of skip lists (probably not what you want).
91 MaxLevel int
92 }
93
94 // Len returns the length of s.
95 func (s *SkipList) Len() int {
96 return s.length
97 }
98
99 // Iterator is an interface that you can use to iterate through the
100 // skip list (in its entirety or fragments). For an use example, see
101 // the documentation of SkipList.
102 //
103 // Key and Value return the key and the value of the current node.
104 type Iterator interface {
105 // Next returns true if the iterator contains subsequent elements
106 // and advances its state to the next element if that is possible.
107 Next() (ok bool)
108 // Previous returns true if the iterator contains previous elements
109 // and rewinds its state to the previous element if that is possible.
110 Previous() (ok bool)
111 // Key returns the current key.
112 Key() interface{}
113 // Value returns the current value.
114 Value() interface{}
115 // Seek reduces iterative seek costs for searching forward into the Skip List
116 // by remarking the range of keys over which it has scanned before. If the
117 // requested key occurs prior to the point, the Skip List will start searching
118 // as a safeguard. It returns true if the key is within the known range of
119 // the list.
120 Seek(key interface{}) (ok bool)
121 // Close this iterator to reap resources associated with it. While not
122 // strictly required, it will provide extra hints for the garbage collector.
123 Close()
124 }
125
126 type iter struct {
127 current *node
128 key interface{}
129 list *SkipList
130 value interface{}
131 }
132
133 func (i iter) Key() interface{} {
134 return i.key
135 }
136
137 func (i iter) Value() interface{} {
138 return i.value
139 }
140
141 func (i *iter) Next() bool {
142 if !i.current.hasNext() {
143 return false
144 }
145
146 i.current = i.current.next()
147 i.key = i.current.key
148 i.value = i.current.value
149
150 return true
151 }
152
153 func (i *iter) Previous() bool {
154 if !i.current.hasPrevious() {
155 return false
156 }
157
158 i.current = i.current.previous()
159 i.key = i.current.key
160 i.value = i.current.value
161
162 return true
163 }
164
165 func (i *iter) Seek(key interface{}) (ok bool) {
166 current := i.current
167 list := i.list
168
169 // If the existing iterator outside of the known key range, we should set the
170 // position back to the beginning of the list.
171 if current == nil {
172 current = list.header
173 }
174
175 // If the target key occurs before the current key, we cannot take advantage
176 // of the heretofore spent traversal cost to find it; resetting back to the
177 // beginning is the safest choice.
178 if current.key != nil && list.lessThan(key, current.key) {
179 current = list.header
180 }
181
182 // We should back up to the so that we can seek to our present value if that
183 // is requested for whatever reason.
184 if current.backward == nil {
185 current = list.header
186 } else {
187 current = current.backward
188 }
189
190 current = list.getPath(current, nil, key)
191
192 if current == nil {
193 return
194 }
195
196 i.current = current
197 i.key = current.key
198 i.value = current.value
199
200 return true
201 }
202
203 func (i *iter) Close() {
204 i.key = nil
205 i.value = nil
206 i.current = nil
207 i.list = nil
208 }
209
210 type rangeIterator struct {
211 iter
212 upperLimit interface{}
213 lowerLimit interface{}
214 }
215
216 func (i *rangeIterator) Next() bool {
217 if !i.current.hasNext() {
218 return false
219 }
220
221 next := i.current.next()
222
223 if !i.list.lessThan(next.key, i.upperLimit) {
224 return false
225 }
226
227 i.current = i.current.next()
228 i.key = i.current.key
229 i.value = i.current.value
230 return true
231 }
232
233 func (i *rangeIterator) Previous() bool {
234 if !i.current.hasPrevious() {
235 return false
236 }
237
238 previous := i.current.previous()
239
240 if i.list.lessThan(previous.key, i.lowerLimit) {
241 return false
242 }
243
244 i.current = i.current.previous()
245 i.key = i.current.key
246 i.value = i.current.value
247 return true
248 }
249
250 func (i *rangeIterator) Seek(key interface{}) (ok bool) {
251 if i.list.lessThan(key, i.lowerLimit) {
252 return
253 } else if !i.list.lessThan(key, i.upperLimit) {
254 return
255 }
256
257 return i.iter.Seek(key)
258 }
259
260 func (i *rangeIterator) Close() {
261 i.iter.Close()
262 i.upperLimit = nil
263 i.lowerLimit = nil
264 }
265
266 // Iterator returns an Iterator that will go through all elements s.
267 func (s *SkipList) Iterator() Iterator {
268 return &iter{
269 current: s.header,
270 list: s,
271 }
272 }
273
274 // Seek returns a bidirectional iterator starting with the first element whose
275 // key is greater or equal to key; otherwise, a nil iterator is returned.
276 func (s *SkipList) Seek(key interface{}) Iterator {
277 current := s.getPath(s.header, nil, key)
278 if current == nil {
279 return nil
280 }
281
282 return &iter{
283 current: current,
284 key: current.key,
285 list: s,
286 value: current.value,
287 }
288 }
289
290 // SeekToFirst returns a bidirectional iterator starting from the first element
291 // in the list if the list is populated; otherwise, a nil iterator is returned.
292 func (s *SkipList) SeekToFirst() Iterator {
293 if s.length == 0 {
294 return nil
295 }
296
297 current := s.header.next()
298
299 return &iter{
300 current: current,
301 key: current.key,
302 list: s,
303 value: current.value,
304 }
305 }
306
307 // SeekToLast returns a bidirectional iterator starting from the last element
308 // in the list if the list is populated; otherwise, a nil iterator is returned.
309 func (s *SkipList) SeekToLast() Iterator {
310 current := s.footer
311 if current == nil {
312 return nil
313 }
314
315 return &iter{
316 current: current,
317 key: current.key,
318 list: s,
319 value: current.value,
320 }
321 }
322
323 // Range returns an iterator that will go through all the
324 // elements of the skip list that are greater or equal than from, but
325 // less than to.
326 func (s *SkipList) Range(from, to interface{}) Iterator {
327 start := s.getPath(s.header, nil, from)
328 return &rangeIterator{
329 iter: iter{
330 current: &node{
331 forward: []*node{start},
332 backward: start,
333 },
334 list: s,
335 },
336 upperLimit: to,
337 lowerLimit: from,
338 }
339 }
340
341 func (s *SkipList) level() int {
342 return len(s.header.forward) - 1
343 }
344
345 func maxInt(x, y int) int {
346 if x > y {
347 return x
348 }
349 return y
350 }
351
352 func (s *SkipList) effectiveMaxLevel() int {
353 return maxInt(s.level(), s.MaxLevel)
354 }
355
356 // Returns a new random level.
357 func (s SkipList) randomLevel() (n int) {
358 for n = 0; n < s.effectiveMaxLevel() && rand.Float64() < p; n++ {
359 }
360 return
361 }
362
363 // Get returns the value associated with key from s (nil if the key is
364 // not present in s). The second return value is true when the key is
365 // present.
366 func (s *SkipList) Get(key interface{}) (value interface{}, ok bool) {
367 candidate := s.getPath(s.header, nil, key)
368
369 if candidate == nil || candidate.key != key {
370 return nil, false
371 }
372
373 return candidate.value, true
374 }
375
376 // GetGreaterOrEqual finds the node whose key is greater than or equal
377 // to min. It returns its value, its actual key, and whether such a
378 // node is present in the skip list.
379 func (s *SkipList) GetGreaterOrEqual(min interface{}) (actualKey, value interface{}, ok bool) {
380 candidate := s.getPath(s.header, nil, min)
381
382 if candidate != nil {
383 return candidate.key, candidate.value, true
384 }
385 return nil, nil, false
386 }
387
388 // getPath populates update with nodes that constitute the path to the
389 // node that may contain key. The candidate node will be returned. If
390 // update is nil, it will be left alone (the candidate node will still
391 // be returned). If update is not nil, but it doesn't have enough
392 // slots for all the nodes in the path, getPath will panic.
393 func (s *SkipList) getPath(current *node, update []*node, key interface{}) *node {
394 depth := len(current.forward) - 1
395
396 for i := depth; i >= 0; i-- {
397 for current.forward[i] != nil && s.lessThan(current.forward[i].key, key) {
398 current = current.forward[i]
399 }
400 if update != nil {
401 update[i] = current
402 }
403 }
404 return current.next()
405 }
406
407 // Sets set the value associated with key in s.
408 func (s *SkipList) Set(key, value interface{}) {
409 if key == nil {
410 panic("goskiplist: nil keys are not supported")
411 }
412 // s.level starts from 0, so we need to allocate one.
413 update := make([]*node, s.level()+1, s.effectiveMaxLevel()+1)
414 candidate := s.getPath(s.header, update, key)
415
416 if candidate != nil && candidate.key == key {
417 candidate.value = value
418 return
419 }
420
421 newLevel := s.randomLevel()
422
423 if currentLevel := s.level(); newLevel > currentLevel {
424 // there are no pointers for the higher levels in
425 // update. Header should be there. Also add higher
426 // level links to the header.
427 for i := currentLevel + 1; i <= newLevel; i++ {
428 update = append(update, s.header)
429 s.header.forward = append(s.header.forward, nil)
430 }
431 }
432
433 newNode := &node{
434 forward: make([]*node, newLevel+1, s.effectiveMaxLevel()+1),
435 key: key,
436 value: value,
437 }
438
439 if previous := update[0]; previous.key != nil {
440 newNode.backward = previous
441 }
442
443 for i := 0; i <= newLevel; i++ {
444 newNode.forward[i] = update[i].forward[i]
445 update[i].forward[i] = newNode
446 }
447
448 s.length++
449
450 if newNode.forward[0] != nil {
451 if newNode.forward[0].backward != newNode {
452 newNode.forward[0].backward = newNode
453 }
454 }
455
456 if s.footer == nil || s.lessThan(s.footer.key, key) {
457 s.footer = newNode
458 }
459 }
460
461 // Delete removes the node with the given key.
462 //
463 // It returns the old value and whether the node was present.
464 func (s *SkipList) Delete(key interface{}) (value interface{}, ok bool) {
465 if key == nil {
466 panic("goskiplist: nil keys are not supported")
467 }
468 update := make([]*node, s.level()+1, s.effectiveMaxLevel())
469 candidate := s.getPath(s.header, update, key)
470
471 if candidate == nil || candidate.key != key {
472 return nil, false
473 }
474
475 previous := candidate.backward
476 if s.footer == candidate {
477 s.footer = previous
478 }
479
480 next := candidate.next()
481 if next != nil {
482 next.backward = previous
483 }
484
485 for i := 0; i <= s.level() && update[i].forward[i] == candidate; i++ {
486 update[i].forward[i] = candidate.forward[i]
487 }
488
489 for s.level() > 0 && s.header.forward[s.level()] == nil {
490 s.header.forward = s.header.forward[:s.level()]
491 }
492 s.length--
493
494 return candidate.value, true
495 }
496
497 // NewCustomMap returns a new SkipList that will use lessThan as the
498 // comparison function. lessThan should define a linear order on keys
499 // you intend to use with the SkipList.
500 func NewCustomMap(lessThan func(l, r interface{}) bool) *SkipList {
501 return &SkipList{
502 lessThan: lessThan,
503 header: &node{
504 forward: []*node{nil},
505 },
506 MaxLevel: DefaultMaxLevel,
507 }
508 }
509
510 // Ordered is an interface which can be linearly ordered by the
511 // LessThan method, whereby this instance is deemed to be less than
512 // other. Additionally, Ordered instances should behave properly when
513 // compared using == and !=.
514 type Ordered interface {
515 LessThan(other Ordered) bool
516 }
517
518 // New returns a new SkipList.
519 //
520 // Its keys must implement the Ordered interface.
521 func New() *SkipList {
522 comparator := func(left, right interface{}) bool {
523 return left.(Ordered).LessThan(right.(Ordered))
524 }
525 return NewCustomMap(comparator)
526
527 }
528
529 // NewIntKey returns a SkipList that accepts int keys.
530 func NewIntMap() *SkipList {
531 return NewCustomMap(func(l, r interface{}) bool {
532 return l.(int) < r.(int)
533 })
534 }
535
536 // NewStringMap returns a SkipList that accepts string keys.
537 func NewStringMap() *SkipList {
538 return NewCustomMap(func(l, r interface{}) bool {
539 return l.(string) < r.(string)
540 })
541 }
542
543 // Set is an ordered set data structure.
544 //
545 // Its elements must implement the Ordered interface. It uses a
546 // SkipList for storage, and it gives you similar performance
547 // guarantees.
548 //
549 // To iterate over a set (where s is a *Set):
550 //
551 // for i := s.Iterator(); i.Next(); {
552 // // do something with i.Key().
553 // // i.Value() will be nil.
554 // }
555 type Set struct {
556 skiplist SkipList
557 }
558
559 // NewSet returns a new Set.
560 func NewSet() *Set {
561 comparator := func(left, right interface{}) bool {
562 return left.(Ordered).LessThan(right.(Ordered))
563 }
564 return NewCustomSet(comparator)
565 }
566
567 // NewCustomSet returns a new Set that will use lessThan as the
568 // comparison function. lessThan should define a linear order on
569 // elements you intend to use with the Set.
570 func NewCustomSet(lessThan func(l, r interface{}) bool) *Set {
571 return &Set{skiplist: SkipList{
572 lessThan: lessThan,
573 header: &node{
574 forward: []*node{nil},
575 },
576 MaxLevel: DefaultMaxLevel,
577 }}
578 }
579
580 // NewIntSet returns a new Set that accepts int elements.
581 func NewIntSet() *Set {
582 return NewCustomSet(func(l, r interface{}) bool {
583 return l.(int) < r.(int)
584 })
585 }
586
587 // NewStringSet returns a new Set that accepts string elements.
588 func NewStringSet() *Set {
589 return NewCustomSet(func(l, r interface{}) bool {
590 return l.(string) < r.(string)
591 })
592 }
593
594 // Add adds key to s.
595 func (s *Set) Add(key interface{}) {
596 s.skiplist.Set(key, nil)
597 }
598
599 // Remove tries to remove key from the set. It returns true if key was
600 // present.
601 func (s *Set) Remove(key interface{}) (ok bool) {
602 _, ok = s.skiplist.Delete(key)
603 return ok
604 }
605
606 // Len returns the length of the set.
607 func (s *Set) Len() int {
608 return s.skiplist.Len()
609 }
610
611 // Contains returns true if key is present in s.
612 func (s *Set) Contains(key interface{}) bool {
613 _, ok := s.skiplist.Get(key)
614 return ok
615 }
616
617 func (s *Set) Iterator() Iterator {
618 return s.skiplist.Iterator()
619 }
620
621 // Range returns an iterator that will go through all the elements of
622 // the set that are greater or equal than from, but less than to.
623 func (s *Set) Range(from, to interface{}) Iterator {
624 return s.skiplist.Range(from, to)
625 }
626
627 // SetMaxLevel sets MaxLevel in the underlying skip list.
628 func (s *Set) SetMaxLevel(newMaxLevel int) {
629 s.skiplist.MaxLevel = newMaxLevel
630 }
631
632 // GetMaxLevel returns MaxLevel fo the underlying skip list.
633 func (s *Set) GetMaxLevel() int {
634 return s.skiplist.MaxLevel
635 }