diff --git a/LICENSE b/LICENSE index 159e1e7..f9fe271 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012-2015 Patrick Mylund Nielsen and the go-cache contributors +Copyright (c) 2012-2016 Patrick Mylund Nielsen and the go-cache contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/cache.go b/cache.go index 19146c7..51b32d6 100644 --- a/cache.go +++ b/cache.go @@ -81,6 +81,12 @@ func (c *cache) set(k string, x interface{}, d time.Duration) { } } +// Add an item to the cache, replacing any existing item, using the default +// expiration. +func (c *cache) SetDefault(k string, x interface{}) { + c.Set(k, x, DefaultExpiration) +} + // Add an item to the cache only if an item doesn't already exist for the given // key, or if the existing item has expired. Returns an error otherwise. func (c *cache) Add(k string, x interface{}, d time.Duration) error { @@ -998,15 +1004,22 @@ func (c *cache) LoadFile(fname string) error { return fp.Close() } -// Returns the items in the cache. This may include items that have expired, -// but have not yet been cleaned up. If this is significant, the Expiration -// fields of the items should be checked. Note that explicit synchronization -// is needed to use a cache and its corresponding Items() return value at -// the same time, as the map is shared. +// Copies all unexpired items in the cache into a new map and returns it. func (c *cache) Items() map[string]Item { c.mu.RLock() defer c.mu.RUnlock() - return c.items + m := make(map[string]Item, len(c.items)) + now := time.Now().UnixNano() + for k, v := range c.items { + // "Inlining" of Expired + if v.Expiration > 0 { + if now > v.Expiration { + continue + } + } + m[k] = v + } + return m } // Returns all not expired items in the cache. This method is save to use with @@ -1026,7 +1039,7 @@ func (c *cache) GetNotExpiredItems() map[string]Item { } // Returns the number of items in the cache. This may include items that have -// expired, but have not yet been cleaned up. Equivalent to len(c.Items()). +// expired, but have not yet been cleaned up. func (c *cache) ItemCount() int { c.mu.RLock() n := len(c.items)