Skip to content

Commit 7e15c78

Browse files
committed
syncs: add map.Clear() method
Updates https://github.com/tailscale/corp/issues/13979 Signed-off-by: Denton Gentry <dgentry@tailscale.com>
1 parent 239ad57 commit 7e15c78

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

syncs/syncs.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"sync"
1010
"sync/atomic"
1111

12+
"golang.org/x/exp/maps"
1213
"tailscale.com/util/mak"
1314
)
1415

@@ -227,6 +228,13 @@ func (m *Map[K, V]) Len() int {
227228
return len(m.m)
228229
}
229230

231+
// Clear removes all entries from the map.
232+
func (m *Map[K, V]) Clear() {
233+
m.mu.Lock()
234+
defer m.mu.Unlock()
235+
maps.Clear(m.m)
236+
}
237+
230238
// WaitGroup is identical to [sync.WaitGroup],
231239
// but provides a Go method to start a goroutine.
232240
type WaitGroup struct{ sync.WaitGroup }

syncs/syncs_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,22 @@ func TestMap(t *testing.T) {
137137
t.Errorf("exactly one LoadOrStore should load")
138138
}
139139
})
140+
141+
t.Run("Clear", func(t *testing.T) {
142+
var m Map[string, string]
143+
_, _ = m.LoadOrStore("a", "1")
144+
_, _ = m.LoadOrStore("b", "2")
145+
_, _ = m.LoadOrStore("c", "3")
146+
_, _ = m.LoadOrStore("d", "4")
147+
_, _ = m.LoadOrStore("e", "5")
148+
149+
if m.Len() != 5 {
150+
t.Errorf("Len after loading want=5 got=%d", m.Len())
151+
}
152+
153+
m.Clear()
154+
if m.Len() != 0 {
155+
t.Errorf("Len after Clear want=0 got=%d", m.Len())
156+
}
157+
})
140158
}

0 commit comments

Comments
 (0)