LruCache
A map bounded to at most capacity entries: once full, inserting a new key evicts the least
recently used one.
“Used” means read with get or get_or_insert_with,
or written with insert; contains_key does not count,
so checking for a key without reading it never changes what gets evicted next.
Unlike ExpiringMap, entries never expire on their own: eviction is
only ever “the entry nobody has touched in the longest time”, driven purely by capacity.
A capacity of 0 is a documented degenerate case, not an error: the cache never stores
anything, and every insert is immediately evicted.
Import
Section titled “Import”Cargo feature cache (enabled by default). To compile only this module:
or in Cargo.toml:
Definition
Section titled “Definition”Examples
Section titled “Examples”Methods
Section titled “Methods”Creates an empty cache holding at most capacity entries.
Parameters
| Parameter | Type | Description |
|---|---|---|
capacity | usize | The most entries the cache holds before it starts evicting. |
Returns
Self — An empty cache.
The live value for key, marking it as just used.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | &K | The key to look up. |
Returns
Option<&V> — The value for key, or None when it is not present.
insert
Section titled “insert”Inserts value under key, marking it as just used.
Evicts the least recently used entry first when key is new and the cache is already at
capacity.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | K | The key to insert or update. |
value | V | The value to store. |
Returns
Option<V> — The previous value stored under key, if any.
contains_key
Section titled “contains_key”Whether key has a live entry, without affecting eviction order.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | &K | The key to check. |
Returns
bool — true when key has a live entry.
How many entries are currently stored.
Returns
usize — The number of live entries, at most capacity.
is_empty
Section titled “is_empty”Whether the cache holds no entries.
Returns
bool — true when len is 0.
capacity
Section titled “capacity”The capacity this cache was created with.
Returns
usize — The most entries the cache holds before it starts evicting.
Removes every entry.
Returns
()
get_or_insert_with
Section titled “get_or_insert_with”Returns the value for key, computing and storing it with f first if absent.
Bounded, single-key equivalent of Memoize: the same key
never recomputes while it stays in the cache, but an old key can be evicted to make room.
With a capacity of 0 the freshly computed value is still returned, but is not retained
(nothing is, see new): the next call recomputes it.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | K | The key to look up. |
f | impl FnOnce() -> V | Computes the value to store when key is absent. Not called when key is already present. |
Returns
V — The value for key.
Examples
