/
map.go
82 lines (72 loc) · 1.7 KB
/
map.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
/*
* Copyright (C) 2020-2021 AnySwap Ltd. All rights reserved.
* Copyright (C) 2020-2021 haijun.cai@anyswap.exchange
*
* This library is free software; you can redistribute it and/or
* modify it under the Apache License, Version 2.0.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package common Self encapsulated map structure supporting concurrent operation
package common
import (
"sync"
)
// SafeMap map + sync mutex
type SafeMap struct {
sync.RWMutex
Map map[string]interface{}
}
// NewSafeMap new SafeMap
func NewSafeMap(size int) *SafeMap {
sm := new(SafeMap)
sm.Map = make(map[string]interface{})
return sm
}
// ReadMap get value by key
func (sm *SafeMap) ReadMap(key string) (interface{}, bool) {
sm.RLock()
value, ok := sm.Map[key]
sm.RUnlock()
return value, ok
}
// WriteMap write value by key
func (sm *SafeMap) WriteMap(key string, value interface{}) {
sm.Lock()
sm.Map[key] = value
sm.Unlock()
}
// DeleteMap delete value by key
func (sm *SafeMap) DeleteMap(key string) {
sm.Lock()
delete(sm.Map, key)
sm.Unlock()
}
// ListMap get all (key,value)
func (sm *SafeMap) ListMap() ([]string, []interface{}) {
sm.RLock()
l := len(sm.Map)
key := make([]string, l)
value := make([]interface{}, l)
i := 0
for k, v := range sm.Map {
key[i] = k
value[i] = v
i++
}
sm.RUnlock()
return key, value
}
// MapLength get len of map
func (sm *SafeMap) MapLength() int {
sm.RLock()
l := len(sm.Map)
sm.RUnlock()
return l
}