Documentation
¶
Index ¶
- Variables
- type Cache
- type Entry
- type LRUCache
- func (c *LRUCache[K, T]) Capacity() int
- func (c *LRUCache[K, T]) Clear()
- func (c *LRUCache[K, T]) Delete(key K) bool
- func (c *LRUCache[K, T]) Get(key K) (T, bool)
- func (c *LRUCache[K, T]) Len() int
- func (c *LRUCache[K, T]) Put(key K, value T)
- func (c *LRUCache[K, T]) Resize(capacity int) (int, error)
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCacheCapacity is returned when a cache is created or resized with a // capacity that is not strictly positive. ErrCacheCapacity = errors.New("cache: invalid capacity") )
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[K comparable, T any] interface { // Capacity returns the maximum number of entries the cache will hold. Capacity() int // Resize changes the cache's capacity to capacity, evicting entries as // needed to fit the new bound, and returns the number of entries evicted. // It returns ErrCacheCapacity if capacity is not strictly positive. Resize(capacity int) (int, error) // Put inserts or updates the value stored under key. If adding a new key // would exceed the capacity, an existing entry is evicted to make room. Put(key K, value T) // Get returns the value stored under key and true if present, or the zero // value and false otherwise. A successful lookup counts as a use of the // entry (relevant to usage-based eviction policies). Get(key K) (T, bool) // Delete removes key from the cache, returning true if it was present and // false if it was not. Delete(key K) bool // Len returns the current number of entries held in the cache. Len() int // Clear removes all entries from the cache. Clear() }
Cache is a fixed-capacity key/value store. Implementations decide which entry to evict when an insertion would exceed the capacity (for example, the least-recently-used entry). Implementations are expected to be safe for concurrent use.
type Entry ¶
type Entry[K comparable, T any] struct { Key K Value T }
Entry is a single key/value pair held by a Cache.
type LRUCache ¶
type LRUCache[K comparable, T any] struct { // contains filtered or unexported fields }
func NewLRUCache ¶
func NewLRUCache[K comparable, T any](capacity int) (*LRUCache[K, T], error)
NewLRUCache returns a new LRU cache with the given capacity. Capacity must be > 0; it returns ErrCacheCapacity otherwise.
func (*LRUCache[K, T]) Capacity ¶
Capacity returns the maximum number of entries the cache will hold.
func (*LRUCache[K, T]) Clear ¶
func (c *LRUCache[K, T]) Clear()
Clear removes all entries from the cache.
func (*LRUCache[K, T]) Delete ¶
Delete removes key from the cache. Returns true if the key was present, false if it wasn't.
func (*LRUCache[K, T]) Get ¶
Get returns the value for key and true if present, or zero value and false otherwise. Get marks the entry as most recently used.