-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
103 lines (83 loc) · 1.49 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package weakref
import (
sync "sync"
)
type Map struct{
mux sync.RWMutex
m map[interface{}]IPointer
}
func NewMap()(*Map){
return &Map{
m: make(map[interface{}]IPointer),
}
}
func (m *Map)Len()(int){
m.mux.RLock()
defer m.mux.RUnlock()
return len(m.m)
}
func (m *Map)Has(k interface{})(ok bool){
m.mux.RLock()
defer m.mux.RUnlock()
_, ok = m.m[k]
return
}
func (m *Map)Get(k interface{})(interface{}){
m.mux.RLock()
defer m.mux.RUnlock()
v, ok := m.m[k]
if !ok {
return nil
}
return iPointerToPtr(v)
}
func (m *Map)Set(k interface{}, ptr interface{})(interface{}){
m.mux.Lock()
defer m.mux.Unlock()
m.setLocked(k, ptr)
return ptr
}
func (m *Map)setLocked(k interface{}, ptr interface{}){
if ptr == nil {
panic("ptr cannot be nil")
}
m.m[k] = SetFinalizer(ptr, func(interface{}){
m.Pop(k)
})
return
}
func (m *Map)GetOrSet(k interface{}, s func()(interface{}))(v interface{}){
m.mux.RLock()
p, ok := m.m[k]
m.mux.RUnlock()
if ok {
v = iPointerToPtr(p)
}else{
v = m.Set(k, s())
}
return
}
func (m *Map)Pop(k interface{})(interface{}){
m.mux.Lock()
defer m.mux.Unlock()
v, ok := m.m[k]
if ok {
delete(m.m, k)
return iPointerToPtr(v)
}
return nil
}
func (m *Map)Reset(){
m.mux.Lock()
defer m.mux.Unlock()
m.m = make(map[interface{}]IPointer)
}
func (m *Map)AsMap()(p map[interface{}]interface{}){
m.mux.RLock()
defer m.mux.RUnlock()
p = make(map[interface{}]interface{}, len(m.m))
for k, v := range m.m {
p[k] = iPointerToPtr(v)
}
return
}