Struct lru_mem::LruCache

source ·
pub struct LruCache<K, V, S = DefaultHashBuilder> { /* private fields */ }
Expand description

An LRU (least-recently-used) cache that stores values associated with keys. Insertion, retrieval, and removal all have average-case complexity in O(1). The cache has an upper memory bound, which is set at construction time. This is enforced using estimates on the memory requirement of each key-value-pair. Note that some auxiliary data structures may allocate more memory. So, this data structure may require more than the given limit.

Each time a new entry is added with LruCache::insert, it is checked whether it fits in the given memory bound. If it does not, the least-recently-used element is dropped from the cache, until the new entry fits.

Note that both the key type K and the value type V must implement the MemSize trait to allow for size estimation in normal usage. In addition, the key type K is required to implement Hash and Eq for most meaningful operations.

Furthermore, the hasher type S must implement the BuildHasher trait for non-trivial functionality.

Mutable access is not allowed directly, since it may change the size of an entry. It must be done either by removing the element using LruCache::remove and inserting it again, or passing a mutating closure to LruCache::mutate.

Implementations§

source§

impl<K, V> LruCache<K, V>

source

pub fn new(max_size: usize) -> LruCache<K, V>

Creates a new, empty LRU cache with the given maximum memory size.

Arguments
  • max_size: The maximum number of bytes that the sum of the memory estimates of all entries may occupy. It is important to note that this bound may be exceeded in total memory requirement of the created data structure.
Example
use lru_mem::LruCache;

// Create an LRU cache with 16 KiB memory limit
let cache: LruCache<String, String> = LruCache::new(16 * 1024);
source

pub fn with_capacity(max_size: usize, capacity: usize) -> LruCache<K, V>

Creates a new, empty LRU cache with the given maximum memory size and the specified initial capacity.

Arguments
  • max_size: The maximum number of bytes that the sum of the memory estimates of all entries may occupy. It is important to note that this bound may be exceeded in total memory requirement of the created data structure.
  • capacity: A lower bound on the number of elements that the cache will be able to hold without reallocating.
Example
use lru_mem::LruCache;

// Create an LRU with 4 KiB memory limit that can hold at least 8
// elements without reallocating.
let cache: LruCache<String, String> = LruCache::with_capacity(4096, 8);
source§

impl<K, V, S> LruCache<K, V, S>

source

pub fn with_hasher(max_size: usize, hash_builder: S) -> LruCache<K, V, S>

Creates a new, empty LRU cache with the given maximum memory size which will use the given hash builder to hash keys.

Arguments
  • max_size: The maximum number of bytes that the sum of the memory estimates of all entries may occupy. It is important to note that this bound may be exceeded in total memory requirement of the created data structure.
  • hash_builder: The hasher used to hash keys. It should implement the BuildHasher trait to allow operations being applied to the cache.
Example
use hashbrown::hash_map::DefaultHashBuilder;
use lru_mem::LruCache;

// Create an LRU with 4 KiB memory limit that uses s for hashing keys.
let s = DefaultHashBuilder::default();
let cache: LruCache<String, String> = LruCache::with_hasher(4096, s);
source

pub fn with_capacity_and_hasher( max_size: usize, capacity: usize, hash_builder: S ) -> LruCache<K, V, S>

Creates a new, empty LRU cache with the given maximum memory size and the specified initial capacity which will use the given hash builder to hash keys.

Arguments
  • max_size: The maximum number of bytes that the sum of the memory estimates of all entries may occupy. It is important to note that this bound may be exceeded in total memory requirement of the created data structure.
  • capacity: A lower bound on the number of elements that the cache will be able to hold without reallocating.
  • hash_builder: The hasher used to hash keys. It should implement the BuildHasher trait to allow operations being applied to the cache.
Example
use hashbrown::hash_map::DefaultHashBuilder;
use lru_mem::LruCache;

// Create an LRU with 4 KiB memory limit that can hold at least 8
// elements without reallocating that uses s for hashing keys.
let s = DefaultHashBuilder::default();
let cache: LruCache<String, String> =
    LruCache::with_capacity_and_hasher(4096, 8, s);
source

pub fn max_size(&self) -> usize

Gets the maximum number of bytes that the sum of the memory estimates of all entries may occupy. It is important to note that this bound may be exceeded in total memory requirement of the created data structure.

Example
use lru_mem::LruCache;

let cache: LruCache<String, String> = LruCache::new(65536);
assert_eq!(65536, cache.max_size());
source

pub fn current_size(&self) -> usize

Gets the current estimated memory of all entries contained in this cache, in bytes.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> = LruCache::new(1024);
assert_eq!(0, cache.current_size());

// The exact amount of occupied memory depends not only on the values,
// but also some auxiliary data of the internal structures.
cache.insert("hello".to_owned(), "world".to_owned()).unwrap();
assert!(cache.current_size() > 0);
source

pub fn len(&self) -> usize

Gets the number of entries contained in this cache.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> = LruCache::new(1024);
assert_eq!(0, cache.len());

cache.insert("apple".to_owned(), "banana".to_owned()).unwrap();
assert_eq!(1, cache.len());
source

pub fn is_empty(&self) -> bool

Indicates whether this cache is empty, i.e. its length (LruCache::len) is zero.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> = LruCache::new(1024);
assert!(cache.is_empty());

cache.insert("apple".to_owned(), "banana".to_owned()).unwrap();
assert!(!cache.is_empty());
source

pub fn capacity(&self) -> usize

Returns the number of elements the cache can hold without reallocating.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> =
    LruCache::with_capacity(1024, 10);
assert!(cache.capacity() >= 10);
source

pub fn hasher(&self) -> &S

Returns a reference to the cache’s BuildHasher.

Example
use hashbrown::hash_map::DefaultHashBuilder;
use lru_mem::LruCache;

let hasher = DefaultHashBuilder::default();
let cache: LruCache<String, String> =
    LruCache::with_hasher(4096, hasher);
let hasher: &DefaultHashBuilder = cache.hasher();
source

pub fn clear(&mut self)

Removes all elements from this cache.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.clear();

assert_eq!(None, cache.get("lemon"));
assert_eq!(0, cache.len());
assert_eq!(0, cache.current_size());
source

pub fn iter(&self) -> Iter<'_, K, V>

Creates an iterator over the entries (keys and values) contained in this cache, ordered from least- to most-recently-used. The values are not touched, i.e. the usage history is not altered in any way. That is, the semantics are as in LruCache::peek.

The memory requirement for any key or value may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut iter = cache.iter();

assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    iter.next());
assert_eq!(Some((&"grapefruit".to_owned(), &"bitter".to_owned())),
    iter.next_back());
assert_eq!(Some((&"lemon".to_owned(), &"sour".to_owned())),
    iter.next());
assert_eq!(None, iter.next());
assert_eq!(None, iter.next_back());
source

pub fn keys(&self) -> Keys<'_, K, V>

Creates an iterator over the keys contained in this cache, ordered from least- to most-recently-used. The values are not touched, i.e. the usage history is not altered in any way. That is, the semantics are as in LruCache::peek.

The memory requirement for any key may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut keys = cache.keys();

assert_eq!(Some(&"apple".to_owned()), keys.next());
assert_eq!(Some(&"grapefruit".to_owned()), keys.next_back());
assert_eq!(Some(&"lemon".to_owned()), keys.next());
assert_eq!(None, keys.next());
assert_eq!(None, keys.next_back());
source

pub fn values(&self) -> Values<'_, K, V>

Creates an iterator over the values contained in this cache, ordered from least- to most-recently-used. The values are not touched, i.e. the usage history is not altered in any way. That is, the semantics are as in LruCache::peek.

The memory requirement for any value may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut values = cache.values();

assert_eq!(Some(&"sweet".to_owned()), values.next());
assert_eq!(Some(&"bitter".to_owned()), values.next_back());
assert_eq!(Some(&"sour".to_owned()), values.next());
assert_eq!(None, values.next());
assert_eq!(None, values.next_back());
source

pub fn drain(&mut self) -> Drain<'_, K, V, S>

Creates an iterator that drains entries from this cache. Both key and value of each entry are returned. The cache is cleared afterward.

Note it is important for the drain to be dropped in order to ensure integrity of the data structure. Preventing it from being dropped, e.g. using mem::forget, can result in unexpected behavior of the cache.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut vec = cache.drain().collect::<Vec<_>>();

assert_eq!(&("apple".to_owned(), "sweet".to_owned()), &vec[0]);
assert_eq!(&("lemon".to_owned(), "sour".to_owned()), &vec[1]);
assert_eq!(&("grapefruit".to_owned(), "bitter".to_owned()), &vec[2]);
assert!(cache.is_empty());
source

pub fn into_keys(self) -> IntoKeys<K, V, S>

Creates an iterator that takes ownership of the cache and iterates over its keys, ordered from least- to most-recently-used.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut keys = cache.into_keys().collect::<Vec<_>>();

assert_eq!(&"apple".to_owned(), &keys[0]);
assert_eq!(&"lemon".to_owned(), &keys[1]);
assert_eq!(&"grapefruit".to_owned(), &keys[2]);
source

pub fn into_values(self) -> IntoValues<K, V, S>

Creates an iterator that takes ownership of the cache and iterates over its values, ordered from least- to most-recently-used.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("grapefruit".to_owned(), "bitter".to_owned()).unwrap();
let mut values = cache.into_values().collect::<Vec<_>>();

assert_eq!(&"sweet".to_owned(), &values[0]);
assert_eq!(&"sour".to_owned(), &values[1]);
assert_eq!(&"bitter".to_owned(), &values[2]);
source§

impl<K, V, S> LruCache<K, V, S>where K: Eq + Hash, S: BuildHasher,

source

pub fn remove_lru(&mut self) -> Option<(K, V)>

Removes the least-recently-used value from this cache. This returns both key and value of the removed value. If this cache is empty, None is returned.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some(("apple".to_owned(), "sweet".to_owned())),
    cache.remove_lru());
assert_eq!(1, cache.len());
source

pub fn get_lru(&mut self) -> Option<(&K, &V)>

Gets a reference to the least-recently-used entry from this cache. This returns both key and value of the entry. If the cache is empty, None is returned.

This method also marks the value as most-recently-used. If you want the usage history to not be updated, use LruCache::peek_lru instead.

The memory requirement of the key and value may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    cache.get_lru());
assert_eq!(Some((&"lemon".to_owned(), &"sour".to_owned())),
    cache.get_lru());
source

pub fn peek_lru(&self) -> Option<(&K, &V)>

Gets a reference to the least-recently-used entry from this cache. This returns both key and value of the entry. If the cache is empty, None is returned.

This method does not mark the value as most-recently-used. If you want the usage history to be updated, use LruCache::get_lru instead.

The memory requirement of the key and value may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    cache.peek_lru());
assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    cache.peek_lru());
source

pub fn remove_mru(&mut self) -> Option<(K, V)>

Removes the most-recently-used value from the cache. This returns both key and value of the removed entry. If the cache is empty, None is returned.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some(("lemon".to_owned(), "sour".to_owned())),
    cache.remove_mru());
assert_eq!(1, cache.len());
source

pub fn peek_mru(&self) -> Option<(&K, &V)>

Gets a reference to the most-recently-used entry from this cache. This returns both key and value of the entry. If the cache is empty, None is returned.

Note that, for the most-recently-used entry, it does not matter whether the usage history is updated, since it was most-recently-used before. So, there is no need for a get_mru method.

The memory requirement of the key and value may not be changed.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some((&"lemon".to_owned(), &"sour".to_owned())),
    cache.peek_mru());
source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional new entries to be inserted into the cache. The collection may reserve more space to avoid frequent reallocations.

Arguments
  • additional: The number of new entries beyond the ones already contained in the cache for which space should be reserved.
Panics

If the new allocation size overflows usize.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> = LruCache::new(1024);
cache.insert("key".to_owned(), "value".to_owned()).unwrap();
cache.reserve(10);
assert!(cache.capacity() >= 11);
source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional new entries to be inserted into the cache. The collection may reserve more space to avoid frequent reallocations.

Arguments
  • additional: The number of new entries beyond the ones already contained in the cache for which space should be reserved.
Errors

If the capacity overflows, or the allocator reports an error, then an error is returned.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> = LruCache::new(1024);
cache.insert("key".to_owned(), "value".to_owned()).unwrap();
cache.try_reserve(10).expect("out of memory");
assert!(cache.capacity() >= 11);
source

pub fn shrink_to(&mut self, min_capacity: usize)

Shrinks the capacity of the cache with a lower bound. The capacity will remain at least as large as both the length and the given lower bound while maintaining internal constraints of the hash table.

If the capacity is less than the given lower bound, this method is no-op.

Arguments
  • min_capacity: A lower bound on the capacity after the operation.
Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> =
    LruCache::with_capacity(1024, 10);
assert!(cache.capacity() >= 10);
cache.shrink_to(5);
assert!(cache.capacity() >= 5);
source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the cache as much as possible. It will drop down as much as possible while maintaining internal constraints of the hash table.

Example
use lru_mem::LruCache;

let mut cache: LruCache<String, String> =
    LruCache::with_capacity(1024, 10);
cache.insert("key".to_owned(), "value".to_owned()).unwrap();
cache.shrink_to_fit();
assert!(cache.capacity() >= 1);
source

pub fn set_max_size(&mut self, max_size: usize)

Sets a new memory limit for this cache. If this is below the current size (see LruCache::current_size), the least-recently-used element will be repeatedly ejected until the limit is satisfied.

Note that reducing the memory limit to a small fraction of the previous maximum may lead to large amounts of unused capacity in the underlying data structure. If this is a problem, use LruCache::shrink_to or LruCache::shrink_to_fit to avoid this.

Arguments
  • max_size: The new maximum number of bytes that the sum of the memory estimates of all entries may occupy.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.set_max_size(cache.current_size() - 1);

assert_eq!(1, cache.len());
assert!(cache.max_size() < 1024);
source

pub fn touch<Q>(&mut self, key: &Q)where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Sets the entry with the given key as most-recently-used, i.e. all other entries currently contained in the cached will be dropped before this one (unless others are touched/used afterwards). If there is no value associated with the given key, this method is no-op.

Arguments
  • key: The key of the entry to touch.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.touch(&"apple".to_owned());

assert_eq!(Some(("lemon".to_owned(), "sour".to_owned())),
    cache.remove_lru());
source

pub fn get_entry<Q>(&mut self, key: &Q) -> Option<(&K, &V)>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Gets references to the key and value of the entry associated with the given key. If there is no entry for that key, None is returned.

This method also marks the entry as most-recently-used (see LruCache::touch). If you do not want the usage history to be updated, use LruCache::peek_entry instead.

The memory requirement of the key and value may not be changed.

Arguments
  • key: The key of the entry to get.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    cache.get_entry("apple"));
assert_eq!(Some(("lemon".to_owned(), "sour".to_owned())),
    cache.remove_lru());
source

pub fn get<Q>(&mut self, key: &Q) -> Option<&V>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Gets a reference to the value associated with the given key. If there is no value for that key, None is returned.

This method also marks the value as most-recently-used (see LruCache::touch). If you do not want the usage history to be updated, use LruCache::peek instead.

The memory requirement of the value may not be changed.

Arguments
  • key: The key of the value to get.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some(&"sweet".to_owned()), cache.get("apple"));
assert_eq!(Some(("lemon".to_owned(), "sour".to_owned())),
    cache.remove_lru());
source

pub fn peek_entry<Q>(&self, key: &Q) -> Option<(&K, &V)>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Gets references to the key and value of the entry associated with the given key. If there is no entry for that key, None is returned.

This method does not mark the value as most-recently-used. If you want the usage history to be updated, use LruCache::get_entry instead.

The memory requirement of the key and value may not be changed.

Arguments
  • key: The key of the entry to peek.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some((&"apple".to_owned(), &"sweet".to_owned())),
    cache.peek_entry("apple"));
assert_eq!(Some(("apple".to_owned(), "sweet".to_owned())),
    cache.remove_lru());
source

pub fn peek<Q>(&self, key: &Q) -> Option<&V>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Gets a reference to the value associated with the given key. If there is no value for that key, None is returned.

This method does not mark the value as most-recently-used. If you want the usage history to be updated, use LruCache::get instead.

The memory requirement of the value may not be changed.

Arguments
  • key: The key of the value to peek.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some(&"sweet".to_owned()), cache.peek("apple"));
assert_eq!(Some(("apple".to_owned(), "sweet".to_owned())),
    cache.remove_lru());
source

pub fn contains<Q>(&self, key: &Q) -> boolwhere K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Indicates whether this cache contains an entry associated with the given key. If there is one, it is not marked as most-recently-used.

Arguments
  • key: The key of the value to search.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();

assert!(cache.contains("apple"));
assert!(!cache.contains("banana"));
source

pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Removes the entry associated with the given key from this cache. If the cache does not contain the given key, None is returned.

Arguments
  • key: The key of the value to remove.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.remove("apple");

assert_eq!(0, cache.len());
source

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>where K: Borrow<Q>, Q: Eq + Hash + ?Sized,

Removes and returns the value associated with the given key from this cache. If there is no such value, None is returned.

Argument
  • key: The key of the value to remove.
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Some("sour".to_owned()), cache.remove("lemon"));
assert_eq!(1, cache.len());
source

pub fn retain<F>(&mut self, pred: F)where F: FnMut(&K, &V) -> bool,

Retains only the elements which satisfy the predicate. In other words, removes all entries (k, v) such that pred(&k, &v) returns false. The elements are visited ordered from least-recently-used to most-recently-used.

For all retained entries, i.e. those where pred returns true, the memory requirement of the key and value may not be changed.

Arguments
  • pred: A function which takes as input references to the key and value of an entry and decides whether it should remain in the map (true) or not (false).
Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();
cache.insert("banana".to_owned(), "sweet".to_owned()).unwrap();
cache.retain(|_, v| v.as_str() == "sweet");

assert_eq!(2, cache.len());
assert!(cache.get("apple").is_some());
assert!(cache.get("lemon").is_none());
assert!(cache.get("banana").is_some());
source§

impl<K, V, S> LruCache<K, V, S>where K: Eq + Hash + MemSize, V: MemSize, S: BuildHasher,

source

pub fn insert( &mut self, key: K, value: V ) -> Result<Option<V>, InsertError<K, V>>

Inserts a new entry into this cache. This is initially the most-recently-used entry. If there was an entry with the given key before, it is removed and its value returned. Otherwise, None is returned. If inserting this entry would violate the memory limit, the least-recently-used values are ejected from the cache until it fits.

If you want to know before calling this method whether elements would be ejected, you can use entry_size to obtain the memory usage that would be assigned to the created entry and check using LruCache::current_size and LruCache::max_size whether it fits.

Arguments
  • key: The key by which the inserted entry will be identified.
  • value: The value to store in the inserted entry.
Errors

Raises an InsertError::EntryTooLarge if the entry alone would already be too large to fit inside the cache’s size limit. That is, even if all other entries were ejected, it still would not be able to be inserted. If this occurs, the entry was not inserted.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(2, cache.len());
source

pub fn try_insert( &mut self, key: K, value: V ) -> Result<(), TryInsertError<K, V>>

Tries to insert a new entry into this cache. This is initially the most-recently-used entry. If there was an entry with the given key before or it does not fit within the memory requirement, an appropriate error is raised (see below).

Arguments
  • key: The key by which the inserted entry will be identified.
  • value: The value to store in the inserted entry.
Errors

If any error was raised, the entry was not inserted into the cache.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
let result = cache.try_insert("apple".to_owned(), "sweet".to_owned());
assert!(result.is_ok());
let result = cache.try_insert("apple".to_owned(), "sour".to_owned());
assert!(!result.is_ok());
source

pub fn mutate<Q, R, F>( &mut self, key: &Q, op: F ) -> Result<Option<R>, MutateError<K, V>>where K: Borrow<Q>, Q: Eq + Hash + ?Sized, F: FnOnce(&mut V) -> R,

Applies a mutating function to the value associated with the given key. The result of that function is returned. If there is no value for the given key, None is returned, and the operation is never called. Otherwise, the entry is marked as most-recently-used by this method.

Note that the operation may also change the size of the value. After it terminates, the internal sizes are updated and, if necessary, least-recently-used entries are ejected to restore the memory requirement. If the operation increases the size beyond the limit of this cache, an error is raised (see below).

Arguments
  • key: The key of the value to mutate.
  • op: An operation that takes as input a mutable reference to the value, mutates it, and returns the desired result. This is forwarded by this method to the caller.
Errors

Raises an MutateError::EntryTooLarge if the operation expanded the value so much that the entry no longer fit inside the memory limit of the cache. If that is the case, the entry is removed and its parts returned in the error data.

Example
use lru_mem::LruCache;

let mut cache = LruCache::new(1024);
cache.insert("apple".to_owned(), "sweet".to_owned()).unwrap();
cache.insert("lemon".to_owned(), "sour".to_owned()).unwrap();

assert_eq!(Ok(Some(())),
    cache.mutate("apple", |s| s.push_str(" and sour")));
assert_eq!(Some(&"sweet and sour".to_owned()), cache.peek("apple"));

Trait Implementations§

source§

impl<K, V, S> Clone for LruCache<K, V, S>where K: Clone + Eq + Hash, V: Clone, S: BuildHasher + Clone,

source§

fn clone(&self) -> LruCache<K, V, S>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<K: Debug, V: Debug, S> Debug for LruCache<K, V, S>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<K, V, S> Drop for LruCache<K, V, S>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<K, V, S> IntoIterator for LruCache<K, V, S>

§

type Item = (K, V)

The type of the elements being iterated over.
§

type IntoIter = IntoIter<K, V, S>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> IntoIter<K, V, S>

Creates an iterator from a value. Read more
source§

impl<K: Send, V: Send, S: Send> Send for LruCache<K, V, S>

source§

impl<K: Sync, V: Sync, S: Sync> Sync for LruCache<K, V, S>

Auto Trait Implementations§

§

impl<K, V, S> RefUnwindSafe for LruCache<K, V, S>where K: RefUnwindSafe, S: RefUnwindSafe, V: RefUnwindSafe,

§

impl<K, V, S> Unpin for LruCache<K, V, S>where K: Unpin, S: Unpin, V: Unpin,

§

impl<K, V, S> UnwindSafe for LruCache<K, V, S>where K: UnwindSafe + RefUnwindSafe, S: UnwindSafe, V: UnwindSafe + RefUnwindSafe,

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> ValueSize for T

source§

fn value_size(&self) -> usize

The size of this value in bytes, excluding allocated data. Read more
source§

fn value_size_sum_iter<'item>(iterator: impl Iterator<Item = &'item T>) -> usizewhere T: 'item,

The total sum of the sizes of all values in the given iterator, in bytes. This is default-implemented by computing ValueSize::value_size on every element and summing them. For Sized types, a more potentially efficient implementation using Iterator::count is provided. If you are implementing this trait manually, it is unlikely to be more efficient to provide a manual implementation here. Read more
source§

fn value_size_sum_exact_size_iter<'item>( iterator: impl ExactSizeIterator<Item = &'item T> ) -> usizewhere T: 'item,

The total sum of the sizes of all values in the given exact-size-iterator, in bytes. This is default-implemented by using ValueSize::value_size_sum_iter. For Sized types, a usually more efficient implementation using ExactSizeIterator::len is provided. If you are implementing this trait manually, it is unlikely to be more efficient to provide a manual implementation here. Read more