-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmastermap.go
58 lines (49 loc) · 1.02 KB
/
mastermap.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
package main
import (
"math/rand"
"sync"
"time"
)
type Mastermap struct {
lock sync.Mutex
items map[string]interface{}
keyLen byte
}
func NewMastermap(keyLen byte) *Mastermap {
rand.Seed(time.Now().UnixNano())
return &Mastermap{
items: make(map[string]interface{}),
keyLen: keyLen,
}
}
func generateRandomKey(keyLen byte) []byte {
key := make([]byte, keyLen)
rand.Read(key)
return key
}
func (m *Mastermap) Register(item interface{}) []byte {
m.lock.Lock()
defer m.lock.Unlock()
for { // ToDo: Smarter and more detrmenistic way to find free key
key := generateRandomKey(m.keyLen)
if _, ok := m.items[string(key)]; !ok {
m.items[string(key)] = item
return key
}
}
}
func (m *Mastermap) Unregister(key []byte) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.items, string(key))
}
func (m *Mastermap) Get(key []byte) (interface{}, bool) {
m.lock.Lock()
defer m.lock.Unlock()
net, ok := m.items[string(key)]
return net, ok
}
func (m *Mastermap) Has(key []byte) bool {
_, ok := m.Get(key)
return ok
}