Make counter zero value useable.

This commit is contained in:
Tom Wilkie
2016-01-25 12:52:19 -08:00
parent b809f94272
commit 7a70a076b8
3 changed files with 47 additions and 3 deletions
+20 -3
View File
@@ -31,6 +31,9 @@ func (c Counters) Copy() Counters {
// Add value to the counter 'key'
func (c Counters) Add(key string, value int) Counters {
if c.psMap == nil {
c = EmptyCounters
}
if existingValue, ok := c.psMap.Lookup(key); ok {
value += existingValue.(int)
}
@@ -41,15 +44,20 @@ func (c Counters) Add(key string, value int) Counters {
// Lookup the counter 'key'
func (c Counters) Lookup(key string) (int, bool) {
existingValue, ok := c.psMap.Lookup(key)
if ok {
return existingValue.(int), true
if c.psMap != nil {
existingValue, ok := c.psMap.Lookup(key)
if ok {
return existingValue.(int), true
}
}
return 0, false
}
// Size returns the number of counters
func (c Counters) Size() int {
if c.psMap == nil {
return 0
}
return c.psMap.Size()
}
@@ -81,6 +89,9 @@ func (c Counters) Merge(other Counters) Counters {
}
func (c Counters) String() string {
if c.psMap == nil {
return "{}"
}
keys := []string{}
for _, k := range c.psMap.Keys() {
keys = append(keys, k)
@@ -103,6 +114,12 @@ func (c Counters) DeepEqual(i interface{}) bool {
return false
}
if (c.psMap == nil) != (d.psMap == nil) {
return false
} else if c.psMap == nil && d.psMap == nil {
return true
}
if c.psMap.Size() != d.psMap.Size() {
return false
}
+22
View File
@@ -27,6 +27,28 @@ func TestCountersDeepEquals(t *testing.T) {
if !reflect.DeepEqual(want, have) {
t.Errorf(test.Diff(want, have))
}
notequal := EmptyCounters.
Add("foo", 4)
if reflect.DeepEqual(want, notequal) {
t.Errorf(test.Diff(want, have))
}
}
func TestCountersNil(t *testing.T) {
want := Counters{}
if want.Size() != 0 {
t.Errorf("nil.Size != 0")
}
if v, ok := want.Lookup("foo"); ok || v != 0 {
t.Errorf("nil.Lookup != false")
}
have := want.Add("foo", 1)
if v, ok := have.Lookup("foo"); !ok || v != 1 {
t.Errorf("nil.Add failed")
}
if have2 := want.Merge(have); !reflect.DeepEqual(have, have2) {
t.Errorf(test.Diff(have, have2))
}
}
func TestCountersMerge(t *testing.T) {
+5
View File
@@ -43,6 +43,11 @@ func TestLatestMapDeepEquals(t *testing.T) {
if !reflect.DeepEqual(want, have) {
t.Errorf(test.Diff(want, have))
}
notequal := EmptyLatestMap.
Set("foo", now, "Baz")
if reflect.DeepEqual(want, notequal) {
t.Errorf(test.Diff(want, have))
}
}
func TestLatestMapDelete(t *testing.T) {