-
Notifications
You must be signed in to change notification settings - Fork 12
/
peers.go
112 lines (97 loc) · 2.51 KB
/
peers.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
109
110
111
112
package bully
import (
"fmt"
"io"
"sync"
)
// Peers is an `interface` exposing methods to handle communication with other
// `bully.Bully`s.
//
// NOTE: This project offers a default implementation of the `Peers` interface
// that provides basic functions. This will work for the most simple of use
// cases fo exemples, although I strongly recommend you provide your own, safer
// implementation while doing real work.
type Peers interface {
Add(ID, addr string, fd io.Writer)
Delete(ID string)
Find(ID string) bool
Write(ID string, msg interface{}) error
PeerData() []struct {
ID string
Addr string
}
}
// PeerMap is a `struct` implementing the `Peers` interface and representing
// a container of `bully.Peer`s.
type PeerMap struct {
mu *sync.RWMutex
peers map[string]*Peer
}
// NewPeerMap returns a new `bully.PeerMap`.
func NewPeerMap() *PeerMap {
return &PeerMap{mu: &sync.RWMutex{}, peers: make(map[string]*Peer)}
}
// Add creates a new `bully.Peer` and adds it to `pm.peers` using `ID` as a key.
//
// NOTE: This function is thread-safe.
func (pm *PeerMap) Add(ID, addr string, fd io.Writer) {
pm.mu.Lock()
defer pm.mu.Unlock()
pm.peers[ID] = NewPeer(ID, addr, fd)
}
// Delete erases the `bully.Peer` corresponding to `ID` from `pm.peers`.
//
// NOTE: This function is thread-safe.
func (pm *PeerMap) Delete(ID string) {
pm.mu.Lock()
defer pm.mu.Unlock()
delete(pm.peers, ID)
}
// Find returns `true` if `pm.peers[ID]` exists, `false` otherwise.
//
// NOTE: This function is thread-safe.
func (pm *PeerMap) Find(ID string) bool {
pm.mu.RLock()
defer pm.mu.RUnlock()
_, ok := pm.peers[ID]
return ok
}
// Write writes `msg` to `pm.peers[ID]`. It returns `nil` or an `error` if
// something occurs.
//
// NOTE: This function is thread-safe.
func (pm *PeerMap) Write(ID string, msg interface{}) error {
pm.mu.Lock()
defer pm.mu.Unlock()
if p, ok := pm.peers[ID]; !ok {
return fmt.Errorf("Write: peer %s not found in PeerMap", ID)
} else if err := p.sock.Encode(msg); err != nil {
return fmt.Errorf("Write: %v", err)
}
return nil
}
// PeerData returns a slice of anonymous structures representing a tupple
// composed of a `Peer.ID` and `Peer.addr`.
//
// NOTE: This function is thread-safe.
func (pm *PeerMap) PeerData() []struct {
ID string
Addr string
} {
pm.mu.RLock()
defer pm.mu.RUnlock()
var IDSlice []struct {
ID string
Addr string
}
for _, peer := range pm.peers {
IDSlice = append(IDSlice, struct {
ID string
Addr string
}{
peer.ID,
peer.addr,
})
}
return IDSlice
}