Skip to content

Commit

Permalink
[release-branch.go1.9] expvar: make (*Map).Init clear existing keys
Browse files Browse the repository at this point in the history
fixes #21619

Change-Id: I5bb513dfc8cac875b06a262eec40b5863ae23a4c
Reviewed-on: https://go-review.googlesource.com/62370
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-on: https://go-review.googlesource.com/70973
Run-TryBot: Russ Cox <rsc@golang.org>
  • Loading branch information
Bryan C. Mills authored and rsc committed Oct 25, 2017
1 parent ccd5abc commit 8c7fa95
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/expvar/expvar.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,17 @@ func (v *Map) String() string {
return b.String()
}

func (v *Map) Init() *Map { return v }
// Init removes all keys from the map.
func (v *Map) Init() *Map {
v.keysMu.Lock()
defer v.keysMu.Unlock()
v.keys = v.keys[:0]
v.m.Range(func(k, _ interface{}) bool {
v.m.Delete(k)
return true
})
return v
}

// updateKeys updates the sorted list of keys in v.keys.
func (v *Map) addKey(key string) {
Expand Down
22 changes: 22 additions & 0 deletions src/expvar/expvar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,28 @@ func BenchmarkStringSet(b *testing.B) {
})
}

func TestMapInit(t *testing.T) {
RemoveAll()
colors := NewMap("bike-shed-colors")
colors.Add("red", 1)
colors.Add("blue", 1)
colors.Add("chartreuse", 1)

n := 0
colors.Do(func(KeyValue) { n++ })
if n != 3 {
t.Errorf("after three Add calls with distinct keys, Do should invoke f 3 times; got %v", n)
}

colors.Init()

n = 0
colors.Do(func(KeyValue) { n++ })
if n != 0 {
t.Errorf("after Init, Do should invoke f 0 times; got %v", n)
}
}

func TestMapCounter(t *testing.T) {
RemoveAll()
colors := NewMap("bike-shed-colors")
Expand Down

0 comments on commit 8c7fa95

Please sign in to comment.