-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathelement.go
119 lines (95 loc) · 2.53 KB
/
element.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
// Copyright 2011 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.
package skiplist
import (
"unsafe"
)
// Element is an element node of a skip list.
type Element struct {
elementHeader
Value interface{}
key interface{}
score float64
prev *Element // Points to previous adjacent elem.
prevTopLevel *Element // Points to previous element which points to this element's top most level.
list *SkipList // The list contains this elem.
}
// elementHeader is the header of an element or a skip list.
// It must be the first anonymous field in a type to make Element() work correctly.
type elementHeader struct {
levels []*Element // Next element at all levels.
}
func (header *elementHeader) Element() *Element {
return (*Element)(unsafe.Pointer(header))
}
func newElement(list *SkipList, level int, score float64, key, value interface{}) *Element {
return &Element{
elementHeader: elementHeader{
levels: make([]*Element, level),
},
Value: value,
key: key,
score: score,
list: list,
}
}
// Next returns next adjacent elem.
func (elem *Element) Next() *Element {
if len(elem.levels) == 0 {
return nil
}
return elem.levels[0]
}
// Prev returns previous adjacent elem.
func (elem *Element) Prev() *Element {
return elem.prev
}
// NextLevel returns next element at specific level.
// If level is invalid, returns nil.
func (elem *Element) NextLevel(level int) *Element {
if level < 0 || level >= len(elem.levels) {
return nil
}
return elem.levels[level]
}
// PrevLevel returns previous element which points to this element at specific level.
// If level is invalid, returns nil.
func (elem *Element) PrevLevel(level int) *Element {
if level < 0 || level >= len(elem.levels) {
return nil
}
if level == 0 {
return elem.prev
}
if level == len(elem.levels)-1 {
return elem.prevTopLevel
}
prev := elem.prev
for prev != nil {
if level < len(prev.levels) {
return prev
}
prev = prev.prevTopLevel
}
return prev
}
// Key returns the key of the elem.
func (elem *Element) Key() interface{} {
return elem.key
}
// Score returns the score of this element.
// The score is a hint when comparing elements.
// Skip list keeps all elements sorted by score from smallest to largest.
func (elem *Element) Score() float64 {
return elem.score
}
// Level returns the level of this elem.
func (elem *Element) Level() int {
return len(elem.levels)
}
func (elem *Element) reset() {
elem.list = nil
elem.prev = nil
elem.prevTopLevel = nil
elem.levels = nil
}