diff --git a/report/counters.go b/report/counters.go index 28ce8e479..fa5c05f22 100644 --- a/report/counters.go +++ b/report/counters.go @@ -88,21 +88,25 @@ func (c Counters) Merge(other Counters) Counters { return Counters{output} } -func (c Counters) String() string { - if c.psMap == nil { - return "{}" +func (c Counters) ForEach(f func(key string, val int)) { + if c.psMap != nil { + keys := c.psMap.Keys() + sort.Strings(keys) + for _, key := range keys { + if val, ok := c.psMap.Lookup(key); ok { + f(key, val.(int)) + } + } } - keys := []string{} - for _, k := range c.psMap.Keys() { - keys = append(keys, k) - } - sort.Strings(keys) +} +func (c Counters) String() string { buf := bytes.NewBufferString("{") - for _, key := range keys { - val, _ := c.psMap.Lookup(key) - fmt.Fprintf(buf, "%s: %d, ", key, val) - } + prefix := "" + c.ForEach(func(k string, v int) { + fmt.Fprintf(buf, "%s%s: %d", prefix, k, v) + prefix = ", " + }) fmt.Fprintf(buf, "}") return buf.String() } diff --git a/report/counters_internal_test.go b/report/counters_internal_test.go index 7e8f29e5d..0f912aebb 100644 --- a/report/counters_internal_test.go +++ b/report/counters_internal_test.go @@ -132,3 +132,33 @@ func TestCountersEncoding(t *testing.T) { } } + +func TestCountersString(t *testing.T) { + { + var c Counters + have := c.String() + want := `{}` + if want != have { + t.Errorf("Expected: %s, Got %s", want, have) + } + } + + { + have := EmptyCounters.String() + want := `{}` + if want != have { + t.Errorf("Expected: %s, Got %s", want, have) + } + } + + { + have := EmptyCounters. + Add("foo", 1). + Add("bar", 2).String() + + want := `{bar: 2, foo: 1}` + if want != have { + t.Errorf("Expected: %s, Got %s", want, have) + } + } +}