-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstate.go
76 lines (59 loc) · 1.35 KB
/
state.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
package ipv6disc
import (
"fmt"
"net"
"sort"
"strings"
"sync"
)
type State struct {
macs map[string]*AddrCollection
macsMutex sync.RWMutex
}
// accepts default TTL and onExpiration function
func (s *State) Enlist(addr *Addr) (*Addr, bool) {
s.macsMutex.Lock()
defer s.macsMutex.Unlock()
mac := addr.Hw.String()
_, exists := s.macs[mac]
if !exists {
s.macs[mac] = NewAddrCollection()
}
return s.macs[mac].Enlist(addr)
}
func (s *State) FilterMACs(hws []net.HardwareAddr) *AddrCollection {
results := NewAddrCollection()
s.macsMutex.Lock()
defer s.macsMutex.Unlock()
for _, hw := range hws {
collection, exists := s.macs[hw.String()]
if exists {
results.Join(collection)
}
}
return results
}
func (s *State) PrettyPrint(prefix string, hideSensible bool) string {
var result strings.Builder
s.macsMutex.Lock()
defer s.macsMutex.Unlock()
fmt.Fprintf(&result, "%sDiscovery:\n", prefix)
// Get the keys from the map
keys := make([]string, 0, len(s.macs))
for k := range s.macs {
keys = append(keys, k)
}
// Sort the keys
sort.Strings(keys)
// Iterate ordered
for _, key := range keys {
fmt.Fprintf(&result, "%s %s\n", prefix, key)
fmt.Fprint(&result, s.macs[key].PrettyPrint(prefix+" "))
}
return result.String()
}
func NewState() *State {
return &State{
macs: make(map[string]*AddrCollection),
}
}