-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstub.go
119 lines (97 loc) · 1.81 KB
/
stub.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
package kv
import (
"bytes"
"container/list"
)
type stub struct {
lst *list.List
}
func newStub() *stub {
return &stub{lst: list.New()}
}
func (s *stub) Close() {
s.lst = list.New()
}
func (s *stub) Delete(key []byte) {
if s == nil || len(key) == 0 {
return
}
for e := s.lst.Front(); e != nil; e = e.Next() {
v := e.Value.([][]byte)
cmp := bytes.Compare(v[0], key)
if cmp == 0 {
s.lst.Remove(e)
return
}
}
}
func (s *stub) Get(key []byte) []byte {
if s == nil || len(key) == 0 {
return nil
}
for e := s.lst.Front(); e != nil; e = e.Next() {
v := e.Value.([][]byte)
cmp := bytes.Compare(v[0], key)
if cmp == 0 {
return v[1]
}
}
return nil
}
func (s *stub) Has(key []byte) bool {
return len(s.Get(key)) > 0
}
func (s *stub) Set(key []byte, value []byte) {
if s == nil || len(key) == 0 {
return
}
if len(value) == 0 {
s.Delete(key)
return
}
for e := s.lst.Front(); e != nil; e = e.Next() {
v := e.Value.([][]byte)
cmp := bytes.Compare(v[0], key)
if cmp == 0 {
v[1] = value
return
} else if cmp > 0 {
s.lst.InsertBefore([][]byte{key, value}, e)
return
}
}
s.lst.PushBack([][]byte{key, value})
}
func (s *stub) Prefix(prefix []byte, fn PairIteratorFunc) {
if s == nil {
return
}
size := len(prefix)
for e := s.lst.Front(); e != nil; e = e.Next() {
v := e.Value.([][]byte)
key := v[0]
value := v[1]
if len(key) >= size {
if bytes.Compare(key[:size], prefix) == 0 {
if !fn(key, value) {
return
}
}
}
}
}
func (s *stub) Range(from []byte, to []byte, fn PairIteratorFunc) {
if s == nil {
return
}
for e := s.lst.Front(); e != nil; e = e.Next() {
v := e.Value.([][]byte)
key := v[0]
value := v[1]
if bytes.Compare(key, from) >= 0 && bytes.Compare(key, to) < 0 {
if !fn(key, value) {
return
}
}
}
}