Commit 189c7398 authored by Faissal Elamraoui's avatar Faissal Elamraoui Committed by GitHub

Merge pull request #2351 from amrfaissal/add-safemap-count

Add Count method to BeeMap struct
parents 99093693 fe21305b
...@@ -61,10 +61,8 @@ func (m *BeeMap) Set(k interface{}, v interface{}) bool { ...@@ -61,10 +61,8 @@ func (m *BeeMap) Set(k interface{}, v interface{}) bool {
func (m *BeeMap) Check(k interface{}) bool { func (m *BeeMap) Check(k interface{}) bool {
m.lock.RLock() m.lock.RLock()
defer m.lock.RUnlock() defer m.lock.RUnlock()
if _, ok := m.bm[k]; !ok { _, ok := m.bm[k]
return false return ok
}
return true
} }
// Delete the given key and value. // Delete the given key and value.
...@@ -84,3 +82,10 @@ func (m *BeeMap) Items() map[interface{}]interface{} { ...@@ -84,3 +82,10 @@ func (m *BeeMap) Items() map[interface{}]interface{} {
} }
return r return r
} }
// Count returns the number of items within the map.
func (m *BeeMap) Count() int {
m.lock.RLock()
defer m.lock.RUnlock()
return len(m.bm)
}
...@@ -14,25 +14,44 @@ ...@@ -14,25 +14,44 @@
package utils package utils
import ( import "testing"
"testing"
) var safeMap *BeeMap
func Test_beemap(t *testing.T) { func TestNewBeeMap(t *testing.T) {
bm := NewBeeMap() safeMap = NewBeeMap()
if !bm.Set("astaxie", 1) { if safeMap == nil {
t.Error("set Error") t.Fatal("expected to return non-nil BeeMap", "got", safeMap)
}
}
func TestSet(t *testing.T) {
if ok := safeMap.Set("astaxie", 1); !ok {
t.Error("expected", true, "got", false)
}
}
func TestCheck(t *testing.T) {
if exists := safeMap.Check("astaxie"); !exists {
t.Error("expected", true, "got", false)
} }
if !bm.Check("astaxie") { }
t.Error("check err")
func TestGet(t *testing.T) {
if val := safeMap.Get("astaxie"); val.(int) != 1 {
t.Error("expected value", 1, "got", val)
} }
}
if v := bm.Get("astaxie"); v.(int) != 1 { func TestDelete(t *testing.T) {
t.Error("get err") safeMap.Delete("astaxie")
if exists := safeMap.Check("astaxie"); exists {
t.Error("expected element to be deleted")
} }
}
bm.Delete("astaxie") func TestCount(t *testing.T) {
if bm.Check("astaxie") { if count := safeMap.Count(); count != 0 {
t.Error("delete err") t.Error("expected count to be", 0, "got", count)
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment