-
Notifications
You must be signed in to change notification settings - Fork 0
/
KVList.go
113 lines (101 loc) · 1.67 KB
/
KVList.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
// KVList
package MemKV
import (
"fmt"
)
func BytesEqual(a, b []byte) bool {
aLen := len(a)
bLen := len(b)
if aLen != bLen {
return false
}
for i := 0; i < aLen; i++ {
if a[i] != b[i] {
return false
}
}
return true
}
type KVNode struct {
Key []byte
Value interface{}
Next *KVNode
}
type KVList struct {
Head *KVNode
Length uint32
}
func NewKVNode(key []byte, value interface{}) *KVNode {
n := &KVNode{
Key: key,
Value: value,
Next: nil,
}
return n
}
func NewKVList() *KVList {
l := &KVList{
Head: NewKVNode([]byte("HEAD"), "HEAD"),
Length: 0,
}
return l
}
func (l *KVList) Len() uint32 {
return l.Length
}
func (l *KVList) Find(n *KVNode) (*KVNode, *KVNode, bool) {
head := l.Head
forward := l.Head
for head.Next != nil {
forward = head
head = head.Next
if BytesEqual(head.Key, n.Key) {
return forward, head, true
}
}
return forward, head, false
}
func (l *KVList) Print() {
head := l.Head
for head.Next != nil {
head = head.Next
fmt.Printf("<%s,%v>", string(head.Key), head.Value)
}
fmt.Println()
}
func (l *KVList) Add(n *KVNode) (add uint32) {
_, cur, ok := l.Find(n)
if ok {
//update
cur.Value = n.Value
add = 0
} else {
cur.Next = n
l.Length++
add = 1
}
return
}
func (l *KVList) Del(n *KVNode) (del uint32) {
del = 0
if l.Length <= 0 {
return
}
p, cur, ok := l.Find(n)
if ok {
p.Next = cur.Next
l.Length--
del = 1
}
return
}
func (l *KVList) Get(n *KVNode) *KVNode {
if l.Length <= 1 {
return l.Head.Next
}
_, cur, ok := l.Find(n)
if !ok {
return nil
}
return cur
}