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