diff --git a/cache.go b/cache.go index 3562543..e741f34 100644 --- a/cache.go +++ b/cache.go @@ -45,6 +45,30 @@ type cache struct { janitor *janitor } +// Add an item to the cache, replacing any existing item. If the duration is 0 +// (DefaultExpiration), the cache's default expiration time is used. If it is -1 +// (NoExpiration), the item never expires. +func (c *cache) SetMulti(items map[string]interface{}, d time.Duration) { + // "Inlining" of set + var e int64 + if d == DefaultExpiration { + d = c.defaultExpiration + } + if d > 0 { + e = time.Now().Add(d).UnixNano() + } + c.mu.Lock() + for k, v := range items { + c.items[k] = Item{ + Object: v, + Expiration: e, + } + } + // TODO: Calls to mu.Unlock are currently not deferred because defer + // adds ~200 ns (as of go1.) + c.mu.Unlock() +} + // Add an item to the cache, replacing any existing item. If the duration is 0 // (DefaultExpiration), the cache's default expiration time is used. If it is -1 // (NoExpiration), the item never expires. diff --git a/cache_test.go b/cache_test.go index 6e81693..01fb3bb 100644 --- a/cache_test.go +++ b/cache_test.go @@ -106,6 +106,29 @@ func TestCacheTimes(t *testing.T) { } } +func TestCache_SetMulti(t *testing.T) { + m := map[string]interface{}{ + "a": 1, + "b": 2, + } + tc := New(DefaultExpiration, 0) + tc.SetMulti(m, 0) + a, found := tc.Get("a") + if !found { + t.Fatal("Did not find a") + } + if a.(int) != 1 { + t.Fatal("a is not 1") + } + b, found := tc.Get("b") + if !found { + t.Fatal("Did not find b") + } + if b.(int) != 2 { + t.Fatal("b is not 2") + } +} + func TestNewFrom(t *testing.T) { m := map[string]Item{ "a": Item{