Documentation ¶
Overview ¶
Package lru implements a generic least-recently-used cache with near O(1) perf.
LRU Cache ¶
A least-recently-used (LRU) cache is a cache that holds a limited number of items with an eviction policy such that when the capacity of the cache is exceeded, the least-recently-used item is automatically removed when inserting a new item. The meaning of used in this implementation is either accessing the item via a lookup or adding the item into the cache, including when the item already exists.
External Use ¶
This package has intentionally been designed so it can be used as a standalone package for any projects needing to make use of a well-test least-recently-used cache with near O(1) performance characteristics for lookups, inserts, and deletions.
Example (BasicUsage) ¶
This example demonstrates creating a new cache instance, inserting items into the cache, causing an eviction of the least-recently-used item, and removing an item.
package main import ( "fmt" "github.com/Eacred/eacrd/lru" ) func main() { // Create a new cache instance with the desired limit. const maxItems = 100 cache := lru.NewCache(maxItems) // Insert items into the cache. for i := 0; i < maxItems; i++ { cache.Add(i) } // At this point, the cache has reached the limit, so the first entry will // still be a member of the cache. if !cache.Contains(0) { fmt.Println("cache does not contain expected item 0") return } // Adding another item will evict the least-recently-used item, which will // be the value 1 since 0 was just accessed above. cache.Add(int(maxItems) + 1) if cache.Contains(1) { fmt.Println("cache contains unexpected item 1") return } // Remove an item from the cache. cache.Delete(3) if cache.Contains(3) { fmt.Println("cache contains unexpected item 3") return } }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides a concurrency safe least-recently-used cache with nearly O(1) lookups, inserts, and deletions. The cache is limited to a maximum number of items with eviction for the oldest entry when the limit is exceeded.
The NewCache function must be used to create a usable cache since the zero value of this struct is not valid.
func NewCache ¶
Cache returns an initialized and empty LRU cache. See the documentation for Cache for more details.
func (*Cache) Add ¶
func (m *Cache) Add(item interface{})
Add adds the passed item to the cache and handles eviction of the oldest item if adding the new item would exceed the max limit. Adding an existing item makes it the most recently used item.
This function is safe for concurrent access.