network: optimize wifi locking and include memory allocation optimization

This commit is contained in:
bonedaddy 2020-12-22 17:10:33 -08:00
commit ac4b1f6e9e
No known key found for this signature in database
GPG key ID: 5386234333106B29
3 changed files with 48 additions and 42 deletions

View file

@ -43,7 +43,7 @@ type APNewCallback func(ap *AccessPoint)
type APLostCallback func(ap *AccessPoint)
type WiFi struct {
sync.Mutex
sync.RWMutex
aliases *data.UnsortedKV
aps map[string]*AccessPoint
@ -67,8 +67,12 @@ func NewWiFi(iface *Endpoint, aliases *data.UnsortedKV, newcb APNewCallback, los
}
func (w *WiFi) MarshalJSON() ([]byte, error) {
w.RLock()
defer w.RUnlock()
doc := wifiJSON{
AccessPoints: make([]*AccessPoint, 0),
// we know the length so preallocate to reduce memory allocations
AccessPoints: make([]*AccessPoint, len(w.aps)),
}
for _, ap := range w.aps {
@ -88,10 +92,11 @@ func (w *WiFi) EachAccessPoint(cb func(mac string, ap *AccessPoint)) {
}
func (w *WiFi) Stations() (list []*Station) {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
list = make([]*Station, len(w.aps))
list = make([]*Station, 0)
for _, ap := range w.aps {
list = append(list, ap.Station)
}
@ -99,10 +104,11 @@ func (w *WiFi) Stations() (list []*Station) {
}
func (w *WiFi) List() (list []*AccessPoint) {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
list = make([]*AccessPoint, len(w.aps))
list = make([]*AccessPoint, 0)
for _, ap := range w.aps {
list = append(list, ap)
}
@ -167,8 +173,8 @@ func (w *WiFi) AddIfNew(ssid, mac string, frequency int, rssi int8) (*AccessPoin
}
func (w *WiFi) Get(mac string) (*AccessPoint, bool) {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
mac = NormalizeMac(mac)
ap, found := w.aps[mac]
@ -176,8 +182,8 @@ func (w *WiFi) Get(mac string) (*AccessPoint, bool) {
}
func (w *WiFi) GetClient(mac string) (*Station, bool) {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
mac = NormalizeMac(mac)
for _, ap := range w.aps {
@ -196,8 +202,8 @@ func (w *WiFi) Clear() {
}
func (w *WiFi) NumHandshakes() int {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
sum := 0
for _, ap := range w.aps {
@ -212,8 +218,8 @@ func (w *WiFi) NumHandshakes() int {
}
func (w *WiFi) SaveHandshakesTo(fileName string, linkType layers.LinkType) error {
w.Lock()
defer w.Unlock()
w.RLock()
defer w.RUnlock()
// check if folder exists first
dirName := filepath.Dir(fileName)