diff --git a/concurrent_map.go b/concurrent_map.go index 0e2319c..0baa06c 100644 --- a/concurrent_map.go +++ b/concurrent_map.go @@ -79,6 +79,20 @@ func (m ConcurrentMap) SetIfAbsent(key string, value interface{}) bool { return !ok } +// Sets the given value under the specified key if no value was associated with it, otherwise return existing value +func (m ConcurrentMap) SetOrGet(key string, value interface{}) (actual interface{}, absent bool) { + // Get map shard. + shard := m.GetShard(key) + shard.Lock() + actual, ok := shard.items[key] + if !ok { + shard.items[key] = value + actual = value + } + shard.Unlock() + return actual, !ok +} + // Retrieves an element from map under given key. func (m ConcurrentMap) Get(key string) (interface{}, bool) { // Get shard diff --git a/concurrent_map_test.go b/concurrent_map_test.go index 5861f12..c3d5f05 100644 --- a/concurrent_map_test.go +++ b/concurrent_map_test.go @@ -133,10 +133,9 @@ func TestRemoveCb(t *testing.T) { m.Set("elephant", elephant) var ( - mapKey string - mapVal interface{} + mapKey string + mapVal interface{} wasFound bool - ) cb := func(key string, val interface{}, exists bool) bool { mapKey = key