From 86164a864c8210850a7ac7497e6f9c6cd79e349e Mon Sep 17 00:00:00 2001 From: Pranjal Pandit Date: Tue, 30 Aug 2016 01:05:50 +0530 Subject: [PATCH] cache test and Update added --- cache.go | 16 ++++++++++++++++ sharded_test.go | 6 +++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/cache.go b/cache.go index 3562543..f214480 100644 --- a/cache.go +++ b/cache.go @@ -109,6 +109,22 @@ func (c *cache) Replace(k string, x interface{}, d time.Duration) error { return nil } +// Update only if it is already existing, keep same ttl +// Set new expiry time which is now - its expiration +func (c *cache) Update(k string, x interface{}) error { + c.mu.Lock() + _, found := c.get(k) + if !found { + c.mu.Unlock() + return fmt.Errorf("Item %s doesn't exist", k) + } + newTtl := time.Unix(0, c.items[k].Expiration) + c.set(k, x, newTtl.Sub(time.Now())) + c.mu.Unlock() + return nil +} + + // Get an item from the cache. Returns the item or nil, and a bool indicating // whether the key was found. func (c *cache) Get(k string) (interface{}, bool) { diff --git a/sharded_test.go b/sharded_test.go index aef8597..384ed59 100644 --- a/sharded_test.go +++ b/sharded_test.go @@ -27,7 +27,7 @@ var shardedKeys = []string{ } func TestShardedCache(t *testing.T) { - tc := unexportedNewSharded(DefaultExpiration, 0, 13) + tc := NewSharded(DefaultExpiration, 0, 13) for _, v := range shardedKeys { tc.Set(v, "value", DefaultExpiration) } @@ -43,7 +43,7 @@ func BenchmarkShardedCacheGetNotExpiring(b *testing.B) { func benchmarkShardedCacheGet(b *testing.B, exp time.Duration) { b.StopTimer() - tc := unexportedNewSharded(exp, 0, 10) + tc := NewSharded(exp, 0, 10) tc.Set("foobarba", "zquux", DefaultExpiration) b.StartTimer() for i := 0; i < b.N; i++ { @@ -62,7 +62,7 @@ func BenchmarkShardedCacheGetManyConcurrentNotExpiring(b *testing.B) { func benchmarkShardedCacheGetManyConcurrent(b *testing.B, exp time.Duration) { b.StopTimer() n := 10000 - tsc := unexportedNewSharded(exp, 0, 20) + tsc := NewSharded(exp, 0, 20) keys := make([]string, n) for i := 0; i < n; i++ { k := "foo" + strconv.Itoa(n)