-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathlinkMap.go
108 lines (93 loc) · 2 KB
/
linkMap.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
package hashmap
/*
顺序map
按照添加元素的顺序保存,Keys,Values能按照添加顺序输出所有内容
*/
import (
"container/list"
"encoding/json"
)
type LinkMap struct {
list list.List
m map[string]*list.Element
}
func NewLinkMap() IMap {
return &LinkMap{
list: list.List{},
m: make(map[string]*list.Element),
}
}
func (lm *LinkMap) Set(key string, val interface{}) {
item, exist := lm.m[key]
if !exist {
et := &entity{
key: key,
value: val,
}
lm.m[key] = lm.list.PushBack(et)
} else {
item.Value.(*entity).value = val
}
}
func (lm *LinkMap) Get(key string) (interface{}, bool) {
if item, exist := lm.m[key]; !exist {
return nil, exist
} else {
curItem, _ := item.Value.(*entity)
return curItem.value, exist
}
}
func (lm *LinkMap) Remove(key string) bool {
if item, exist := lm.m[key]; !exist {
return exist
} else {
lm.list.Remove(item)
curItem, _ := item.Value.(*entity)
delete(lm.m, curItem.key)
return exist
}
}
func (lm *LinkMap) Exist(key string) bool {
_, exist := lm.m[key]
return exist
}
func (lm *LinkMap) Len() int {
return len(lm.m)
}
func (lm *LinkMap) Cap() int {
return len(lm.m)
}
func (lm *LinkMap) Clear() {
lm.list.Init()
lm.m = make(map[string]*list.Element)
}
func (lm *LinkMap) Marshal() ([]byte, error) {
return json.Marshal(lm.m)
}
func (lm *LinkMap) Unmarshal(data []byte) error {
m := map[string]interface{}{}
err := json.Unmarshal(data, &m)
if err != nil {
return err
}
for key, value := range m {
lm.Set(key, value)
}
return err
}
func (lm *LinkMap) Values() []interface{} {
list := make([]interface{}, 0, lm.list.Len())
for item := lm.list.Front(); item != nil; item = item.Next() {
curItem, _ := item.Value.(*entity)
list = append(list, curItem.value)
}
return list
}
func (lm *LinkMap) Keys() []string {
list := make([]string, 0, lm.list.Len())
for item := lm.list.Front(); item != nil; item = item.Next() {
curItem, _ := item.Value.(*entity)
list = append(list, curItem.key)
}
return list
}