Skip to content

Commit 8c7fa95

Browse files
Bryan C. Millsrsc
Bryan C. Mills
authored andcommitted
[release-branch.go1.9] expvar: make (*Map).Init clear existing keys
fixes #21619 Change-Id: I5bb513dfc8cac875b06a262eec40b5863ae23a4c Reviewed-on: https://go-review.googlesource.com/62370 Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-on: https://go-review.googlesource.com/70973 Run-TryBot: Russ Cox <[email protected]>
1 parent ccd5abc commit 8c7fa95

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/expvar/expvar.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,17 @@ func (v *Map) String() string {
125125
return b.String()
126126
}
127127

128-
func (v *Map) Init() *Map { return v }
128+
// Init removes all keys from the map.
129+
func (v *Map) Init() *Map {
130+
v.keysMu.Lock()
131+
defer v.keysMu.Unlock()
132+
v.keys = v.keys[:0]
133+
v.m.Range(func(k, _ interface{}) bool {
134+
v.m.Delete(k)
135+
return true
136+
})
137+
return v
138+
}
129139

130140
// updateKeys updates the sorted list of keys in v.keys.
131141
func (v *Map) addKey(key string) {

src/expvar/expvar_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,28 @@ func BenchmarkStringSet(b *testing.B) {
161161
})
162162
}
163163

164+
func TestMapInit(t *testing.T) {
165+
RemoveAll()
166+
colors := NewMap("bike-shed-colors")
167+
colors.Add("red", 1)
168+
colors.Add("blue", 1)
169+
colors.Add("chartreuse", 1)
170+
171+
n := 0
172+
colors.Do(func(KeyValue) { n++ })
173+
if n != 3 {
174+
t.Errorf("after three Add calls with distinct keys, Do should invoke f 3 times; got %v", n)
175+
}
176+
177+
colors.Init()
178+
179+
n = 0
180+
colors.Do(func(KeyValue) { n++ })
181+
if n != 0 {
182+
t.Errorf("after Init, Do should invoke f 0 times; got %v", n)
183+
}
184+
}
185+
164186
func TestMapCounter(t *testing.T) {
165187
RemoveAll()
166188
colors := NewMap("bike-shed-colors")

0 commit comments

Comments
 (0)