-
Notifications
You must be signed in to change notification settings - Fork 0
/
skiplist.go
392 lines (325 loc) · 7.79 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
package leveldb
// Copyright (c) 2020 Bert Young. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Features:
// (1) Not support delete
// (2) Not support duplicated keys
// (3) One writer and many readers can be concurrent
// Thread safety
// -------------
//
// Writes require external synchronization, most likely a mutex.
// Reads require a guarantee that the SkipList will not be destroyed
// while the read is in progress. Apart from that, reads progress
// without any internal locking or synchronization.
//
// Invariants:
//
// (1) Allocated nodes are never deleted until the SkipList is
// destroyed. This is trivially guaranteed by the code since we
// never delete any skip list nodes.
//
// (2) The contents of a Node except for the next/prev pointers are
// immutable after the Node has been linked into the SkipList.
// Only Insert() modifies the list, and it is careful to initialize
// a node and use release-stores to publish the nodes in one or
// more lists.
//
import (
"fmt"
"bytes"
"math/rand"
"sync/atomic"
"time"
"unsafe"
)
// internal node for skip list
type node struct {
key []byte
value []byte
next []*node
}
func (n *node) String() string {
return fmt.Sprintf("(key:%s, value:%s, next %v)", n.key, n.value, n.next)
}
func (n *node) loadNext(i int) *node {
up := unsafe.Pointer(n.next[i])
return (*node)(atomic.LoadPointer(&up))
}
func (n *node) storeNext(i int, next *node) {
up := unsafe.Pointer(&n.next[i])
atomic.StorePointer((*unsafe.Pointer)(up), unsafe.Pointer(next))
}
func (n *node) getNext(i int) *node {
return n.next[i]
}
func (n *node) setNext(i int, next *node) {
n.next[i] = next
}
type SkipList struct {
head node
height int32 // 0-based
rnd *rand.Rand
cmp Comparator
numNode int
byteSize uint64 // key size + value size
}
func NewSkipList(cmp Comparator) *SkipList {
sl := &SkipList{}
sl.head.next = make([]*node, sl.MaxHeight()+1)
sl.height = 0
sl.cmp = cmp
sl.rnd = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
sl.numNode = 0
sl.byteSize = 0
if sl.cmp == nil {
sl.cmp = NewBytewiseComparator()
}
return sl
}
func (sl *SkipList) NumOfNode() int {
return sl.numNode
}
func (sl *SkipList) ByteSize() uint64 {
return sl.byteSize
}
func (sl *SkipList) Height() int32 {
return atomic.LoadInt32(&sl.height)
}
const (
kMaxHeight = 11
)
func (sl *SkipList) MaxHeight() int32 {
return kMaxHeight // 0-based
}
func (sl *SkipList) randomHeight() int32 {
const kBranching = 4
var h int32 = 0
for ; h <= sl.MaxHeight(); h++ {
if sl.rnd.Int()%kBranching != 0 {
return h
}
}
return sl.MaxHeight()
}
func compareKeyNode(key []byte, n *node, cmp Comparator) int {
if n == nil {
return cmp.Compare(key, nil)
}
return cmp.Compare(key, n.key)
}
// single thread insert
func (sl *SkipList) Insert(key, value []byte) error {
prev := [kMaxHeight + 1]*node{}
ge := sl.findGreatOrEqual(key, &prev)
if ge != nil && sl.cmp.Compare(key, ge.key) == 0 {
return fmt.Errorf("Repeated key not allowed: [%s]", key)
}
h := sl.randomHeight()
if h > sl.Height() {
for i := sl.Height() + 1; i <= h; i++ {
prev[i] = &sl.head
}
// Update height first. It's ok with concurrent readers.
// A concurrent reader that observes the new value of height will see either the old value of
// new level pointers from head (nil), or a new value set in
// the loop below. In the former case the reader will
// immediately drop to the next level since nil sorts after all
// keys. In the latter case the reader will use the new node.
atomic.StoreInt32(&sl.height, h)
}
x := &node{key: key, value: value}
x.next = make([]*node, h+1)
// 从底向上将新节点链接进去;因为高层的节点必须在底层也存在,反之不一定
for i := 0; i <= int(h); i++ {
x.setNext(i, prev[i].getNext(i)) // no need barrier, x is still dangle
prev[i].storeNext(i, x) // commit x into skiplist
}
sl.numNode++
sl.byteSize += uint64(len(key) + len(value))
return nil
}
func (sl *SkipList) Contains(key []byte) bool {
ge := sl.findGreatOrEqual(key, nil)
if ge != nil && sl.cmp.Compare(key, ge.key) == 0 {
return true
}
return false
}
// similar to std::map::lower_bound
func (sl *SkipList) findGreatOrEqual(key []byte, prev *[kMaxHeight + 1]*node) *node {
level := int(sl.Height())
x := &sl.head
for {
next := x.loadNext(level)
cmp := compareKeyNode(key, next, sl.cmp)
if cmp > 0 {
x = next
} else if cmp < 0 {
// next maybe nil
if prev != nil {
prev[level] = x
}
if level == 0 {
return next
} else {
level--
}
} else {
return next
}
}
return nil
}
// similar to std::map::upper_bound
func (sl *SkipList) findGreater(key []byte) *node {
n := sl.findGreatOrEqual(key, nil)
if n != nil {
cmp := sl.cmp.Compare(key, n.key)
if cmp == 0 {
return n.next[0]
} else if cmp > 0 {
panic("fuck me")
}
}
return n
}
func (sl *SkipList) findLessOrEqual(key []byte) *node {
level := int(sl.Height())
x := &sl.head
for {
next := x.loadNext(level)
cmp := compareKeyNode(key, next, sl.cmp)
if cmp > 0 {
x = next
} else if cmp < 0 {
// next maybe nil
if level == 0 {
if x == &sl.head {
x = nil
}
return x
} else {
level--
}
} else {
return next
}
}
return nil
}
func (sl *SkipList) findLesser(key []byte) *node {
level := int(sl.Height())
x := &sl.head
for {
next := x.loadNext(level)
cmp := compareKeyNode(key, next, sl.cmp)
if cmp > 0 {
x = next
} else if cmp <= 0 {
// next maybe nil
if level == 0 {
if x == &sl.head {
x = nil
}
return x
} else {
level--
}
}
}
return nil
}
func (sl *SkipList) first() *node {
return sl.head.getNext(0)
}
func (sl *SkipList) last() *node {
level := int(sl.Height())
prev := sl.head.getNext(level)
for level >= 0 {
if prev == nil {
return nil
}
next := prev.getNext(level)
for next != nil {
prev = next
next = next.getNext(level)
}
if level == 0 {
return prev
} else {
level--
}
}
// never reach here
return nil
}
func (sl *SkipList) String() string {
if sl == nil {
return "SkipList (nil)"
}
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("\nSkiplist Height: %d, Num of node %d, Byte size %v\n", sl.height, sl.numNode, sl.byteSize))
for i := sl.height; i >= 0; i-- {
buf.WriteString(fmt.Sprintf("Level %d ----------------------------------\n", i))
i := int(i)
for n := sl.head.getNext(i); n != nil; n = n.getNext(i) {
buf.WriteString(fmt.Sprintf("%v -> ", n.key))
}
buf.WriteString("(nil)\n")
}
return buf.String()
}
type SkiplistIterator struct {
sklist *SkipList
current *node // point to min value at first
state Status
}
func NewSkiplistIterator(sk *SkipList) Iterator {
it := &SkiplistIterator{sklist: sk}
if sk != nil {
it.SeekToFirst()
}
return it
}
func (it *SkiplistIterator) Valid() bool {
return it.current != nil
}
func (it *SkiplistIterator) SeekToFirst() {
it.current = it.sklist.first()
if it.current != nil {
it.state = NewStatus(OK)
} else {
it.state = NewStatus(IOError, "Empty skiplist")
}
}
func (it *SkiplistIterator) SeekToLast() {
it.current = it.sklist.last()
if it.current == nil {
it.state = NewStatus(IOError, "Empty skiplist")
} else {
it.state = NewStatus(OK)
}
}
func (it *SkiplistIterator) Seek(target []byte) {
ge := it.sklist.findGreatOrEqual(target, nil)
it.current = ge
}
func (it *SkiplistIterator) Next() {
next := it.sklist.findGreater(it.current.key)
it.current = next
}
func (it *SkiplistIterator) Prev() {
prev := it.sklist.findLesser(it.current.key)
it.current = prev
}
func (it *SkiplistIterator) Key() []byte {
return it.current.key
}
func (it *SkiplistIterator) Value() []byte {
return it.current.value
}
func (it *SkiplistIterator) Status() Status {
return it.state
}