syncs: allocate map with Map.WithLock (#13755)

One primary purpose of WithLock is to mutate the underlying map.
However, this can lead to a panic if it happens to be nil.
Thus, always allocate a map before passing it to f.

Updates tailscale/corp#11038

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai 2024-10-09 14:03:37 -07:00 committed by GitHub
parent c763b7a7db
commit 5b7303817e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -304,6 +304,9 @@ func (m *Map[K, V]) All() iter.Seq2[K, V] {
func (m *Map[K, V]) WithLock(f func(m2 map[K]V)) {
m.mu.Lock()
defer m.mu.Unlock()
if m.m == nil {
m.m = make(map[K]V)
}
f(m.m)
}