Skip to content

Commit

Permalink
reduce indentation level in Get functions
Browse files Browse the repository at this point in the history
  • Loading branch information
paskal authored and umputun committed May 11, 2020
1 parent 791f17b commit f7a20de
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 23 deletions.
19 changes: 11 additions & 8 deletions expirable_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,20 @@ func (c *ExpirableCache) Get(key string, fn func() (Value, error)) (data Value,
}
atomic.AddInt64(&c.Misses, 1)

if c.allowed(key, data) {
if s, ok := data.(Sizer); ok {
if c.maxCacheSize > 0 && atomic.LoadInt64(&c.currentSize)+int64(s.Size()) >= c.maxCacheSize {
c.backend.DeleteExpired()
return data, nil
}
atomic.AddInt64(&c.currentSize, int64(s.Size()))
if !c.allowed(key, data) {
return data, nil
}

if s, ok := data.(Sizer); ok {
if c.maxCacheSize > 0 && atomic.LoadInt64(&c.currentSize)+int64(s.Size()) >= c.maxCacheSize {
c.backend.DeleteExpired()
return data, nil
}
c.backend.Set(key, data)
atomic.AddInt64(&c.currentSize, int64(s.Size()))
}

c.backend.Set(key, data)

return data, nil
}

Expand Down
21 changes: 12 additions & 9 deletions lru_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,21 @@ func (c *LruCache) Get(key string, fn func() (Value, error)) (data Value, err er

atomic.AddInt64(&c.Misses, 1)

if c.allowed(key, data) {
c.backend.Add(key, data)

if s, ok := data.(Sizer); ok {
atomic.AddInt64(&c.currentSize, int64(s.Size()))
if c.maxCacheSize > 0 && atomic.LoadInt64(&c.currentSize) > c.maxCacheSize {
for atomic.LoadInt64(&c.currentSize) > c.maxCacheSize {
c.backend.RemoveOldest()
}
if !c.allowed(key, data) {
return data, nil
}

c.backend.Add(key, data)

if s, ok := data.(Sizer); ok {
atomic.AddInt64(&c.currentSize, int64(s.Size()))
if c.maxCacheSize > 0 && atomic.LoadInt64(&c.currentSize) > c.maxCacheSize {
for atomic.LoadInt64(&c.currentSize) > c.maxCacheSize {
c.backend.RemoveOldest()
}
}
}

return data, nil
}

Expand Down
15 changes: 9 additions & 6 deletions redis_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,16 @@ func (c *RedisCache) Get(key string, fn func() (Value, error)) (data Value, err
}
atomic.AddInt64(&c.Misses, 1)

if c.allowed(key, data) {
_, setErr := c.backend.Set(key, data, c.ttl).Result()
if setErr != nil {
atomic.AddInt64(&c.Errors, 1)
return data, setErr
}
if !c.allowed(key, data) {
return data, nil
}

_, setErr := c.backend.Set(key, data, c.ttl).Result()
if setErr != nil {
atomic.AddInt64(&c.Errors, 1)
return data, setErr
}

return data, nil
}

Expand Down

0 comments on commit f7a20de

Please sign in to comment.