-
Notifications
You must be signed in to change notification settings - Fork 3
/
direct_map.go
63 lines (51 loc) · 920 Bytes
/
direct_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
package overlay
import (
"math/rand"
"strconv"
"sync"
)
type DirectMap interface {
Bootstrap
Chan(id string) DirectConnector
}
type ChanMap struct {
*sync.RWMutex
chanMap map[string]DirectConnector
}
func NewChanMap() DirectMap {
return &ChanMap{
RWMutex: new(sync.RWMutex),
chanMap: make(map[string]DirectConnector),
}
}
func (mp *ChanMap) NewId() string {
mp.Lock()
defer mp.Unlock()
id := strconv.Itoa(len(mp.chanMap))
mp.chanMap[id] = newDirectChan(id, mp)
return id
}
func (mp *ChanMap) Join(id string) string {
i := rand.Intn(len(mp.chanMap))
for k := range mp.chanMap {
if i == 0 {
if k == id && len(mp.chanMap) > 1 {
return mp.Join(id)
}
if k != id {
return k
}
}
i--
}
return ""
}
func (mp *ChanMap) Chan(id string) DirectConnector {
mp.RLock()
defer mp.RUnlock()
if channel, ok := mp.chanMap[id]; ok {
return channel
} else {
return nil
}
}