LruMap

Struct LruMap 

Source
pub struct LruMap<K, V>
where K: Eq + Hash,
{ /* private fields */ }
Expand description

A HashMap which maintains an internal least recently used nodes list.

Implementations§

Source§

impl<K, V> LruMap<K, V>
where K: Eq + Hash,

Source

pub fn new() -> Self

Create a new LRU HashMap, without node expiry TTL.

Source

pub fn with_ttl(dur: Duration) -> Self

Create a new LRU HashMap, with node TTL’s.

An LruMap with a TTL can call LruMap::drain_timedout() to return an iterator that will return items that have become stale.

Source

pub fn is_empty(&self) -> bool

Return true if the container is empty. Return false otherwise.

use qlrumap::LruMap;

let mut map = LruMap::new();
assert_eq!(map.is_empty(), true);
map.insert(1, 1);
assert_eq!(map.is_empty(), false);
Source

pub fn len(&self) -> usize

Return the number of elements in the container.

use qlrumap::LruMap;

let mut map = LruMap::new();
assert_eq!(map.len(), 0);
map.insert(1, 1);
assert_eq!(map.len(), 1);
Source

pub fn clear(&mut self)

Remove all nodes from the LruMap.

Source

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

Add a new entry to the container. New nodes will be the least recently used node.

Adding a new node:

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
assert_eq!(map.len(), 1);

Adding an already existing key will replace the value, and return the old one:

use qlrumap::LruMap;

// Create a new LruMap, and insert a test node, make sure length == 1.
let mut map = LruMap::new();
map.insert(1, 1);
assert_eq!(map.len(), 1);

// Insert another value, with the same key, make sure length is
// unchanged and make sure the returned value is the old value.
let v = map.insert(1, 2);
assert_eq!(map.len(), 1);
assert_eq!(v, Some(1));

// Make sure the stored value is the new value.
let v = map.get(&1);
assert_eq!(v, Some(&2));
Source

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

Given a reference to a key return a reference to the value associated with it. The map entry will be moved to the front of the internal lru list. If the LruMap has a TTL configured, the node’s timeout will be reset.

Source

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

Given a reference to a key return a mutable reference to the value associated with it. The map entry will be moved to the front of the internal lru list. If the LruMap has a TTL configured, the node’s timeout will be reset.

Source

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

Remove a node from the map based on its key. Returns the value if its key was found in the map.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
let v = map.remove(&1);
assert_eq!(v, Some(1));
assert!(map.is_empty());
Source

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

Move a node to the front of the LRU list given a key.

Returns true if the key exists in the map. Returns false otherwise.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
assert_eq!(map.oldest(), Some((&1, &1)));
map.touch(&1);
assert_eq!(map.oldest(), Some((&2, &2)));
Source

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

Remove and return the oldest node.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
assert_eq!(map.pop(), Some((1, 1)));
assert_eq!(map.pop(), Some((2, 2)));
assert_eq!(map.pop(), None);
assert!(map.is_empty());
Source

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

Remove and return the youngest node.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
assert_eq!(map.pop_youngest(), Some((2, 2)));
assert_eq!(map.pop_youngest(), Some((1, 1)));
assert_eq!(map.pop_youngest(), None);
assert!(map.is_empty());
Source

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

Get the least recently used (youngest) node.

Does not update the node’s timestamp.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
assert_eq!(map.youngest(), Some((&2, &2)));
Source

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

Get the oldest node.

Does not update the node’s timestamp.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
assert_eq!(map.oldest(), Some((&1, &1)));
Source

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

Returns an iterator visiting all key-value pairs in order from youngest to oldest. The iterator element type is (&'a K, &'a V).

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);

// The iterator will yield items from youngest to oldest.
let mut iter = map.iter();
assert_eq!(iter.next(), Some((&"c", &3)));
assert_eq!(iter.next(), Some((&"b", &2)));
assert_eq!(iter.next(), Some((&"a", &1)));
assert_eq!(iter.next(), None);
Source

pub const fn iter_mut(&mut self) -> IterMut<'_, K, V>

Returns a mutable iterator visiting all key-value pairs in order from youngest to oldest. The iterator element type is (&'a K, &'a mut V).

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert("a", 1);
map.insert("b", 2);

for (k, v) in map.iter_mut() {
  if *k == "a" {
    *v = 10;
  }
}

assert_eq!(map.get(&"a"), Some(&10));
Source

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

Return an iterator that will yield all the elements of the LruMap.

The iterator will remove elements from the map and return them as the iterator is progressed. If the Drain iterator is dropped before the LruMap has been drained, the remaining entries will be removed.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, "elena");
map.insert(2, "sully");
let v: Vec<(i32, &str)> = map.drain().collect();
assert!(map.is_empty());
assert_eq!(v.len(), 2)
Source

pub const fn drain_ordered(&mut self) -> DrainOrdered<'_, K, V>

Return an iterator that will yield all the elements of the LruMap, ordered.

The youngest node will be returned first.

If the DrainOrdered iterator is dropped before the LruMap has been drained, the remaining entries will be removed.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, "elena");
map.insert(2, "chloe");
map.insert(3, "drake");

// make second entry the youngest
map.touch(&2);

let v: Vec<(u32, &str)> = map.drain_ordered().collect();
assert_eq!(v[0], (2, "chloe"));
assert_eq!(v[1], (3, "drake"));
assert_eq!(v[2], (1, "elena"));

assert!(map.is_empty());
Source

pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, K, V, F>
where F: FnMut(&K, &mut V) -> bool,

Drain nodes using a closure to validate notes to be drained.

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);
map.insert(3, 3);
let mut it = map.drain_filter(|k, v| {
  // drain second element
  *k == 2 && *v == 2
});

assert_eq!(it.next(), Some((2, 2)));
assert_eq!(it.next(), None);
drop(it);

assert_eq!(map.len(), 2);
assert_eq!(map.oldest(), Some((&1, &1)));
assert_eq!(map.youngest(), Some((&3, &3)));
Source

pub fn drain_timedout(&mut self) -> DrainTimedout<'_, K, V>

Drain entries that have timed out.

To cap the number of elements in the LruMap and also remove stale elements in one call, use LruMap::drain_old().

§Notes
  • The timestamp used to check if nodes have expired is generated and stored in the iterator when it is created. This implies that expiration candidacy is effectively determined when drain_timeout() is called, and not when the iterator’s next() method is called.
Source

pub fn drain_overflow(&mut self, lim: usize) -> DrainOverflow<'_, K, V>

Cap the number of entries in the map.

Creates a draining iterator which will return the oldest entries until there are lim remaining entries in the map.

To cap the number of elements in the LruMap and also remove stale elements in one call, use LruMap::drain_old().

use qlrumap::LruMap;

let mut map = LruMap::new();
map.insert(1, 1);
map.insert(2, 2);

let mut drain = map.drain_overflow(2);
assert_eq!(drain.next(), None);
drop(drain);

map.insert(3, 3);

let mut drain = map.drain_overflow(2);
assert_eq!(drain.next(), Some((1, 1)));
assert_eq!(drain.next(), None);
Source

pub fn drain_old(&mut self, cap: Option<usize>) -> DrainOld<'_, K, V>

Remove old entries and return them in an iterator.

If the cap parameter is set then the oldest node will be removed until the number of elements is equal to or lower than this value.

use std::time::Duration;
use qlrumap::LruMap;

let mut map = LruMap::with_ttl(Duration::from_secs(10));
map.insert(1, "elena");
map.insert(2, "chloe");
map.insert(3, "drake");

map.touch(&1);
map.touch(&2);

// Limit map to 2 entries, use current time as expiry
let mut drain = map.drain_old(Some(2));

assert_eq!(drain.next(), Some((3, "drake")));
assert_eq!(drain.next(), None);
Source

pub fn remove_old(&mut self, cap: Option<usize>)

Remove old entries.

If the cap parameter is set then the oldest node will be removed until the number of elements is equal to or lower than this value.

use std::time::Duration;
use qlrumap::LruMap;

let mut map = LruMap::with_ttl(Duration::from_secs(10));
map.insert(1, "elena");
map.insert(2, "chloe");
map.insert(3, "drake");

map.touch(&1);
map.touch(&2);

// Limit map to 2 entries, use current time as expiry
map.remove_old(Some(2));

assert_eq!(map.len(), 2);

Trait Implementations§

Source§

impl<K, V> Default for LruMap<K, V>
where K: Eq + Hash,

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<K, V> Drop for LruMap<K, V>
where K: Eq + Hash,

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<'a, K, V> IntoIterator for &'a LruMap<K, V>
where K: Eq + Hash,

Source§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, K, V>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K, V> IntoIterator for &'a mut LruMap<K, V>
where K: Eq + Hash,

Source§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, K, V>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K, V> IntoIterator for LruMap<K, V>
where K: Eq + Hash,

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K, V> Send for LruMap<K, V>
where K: Hash + Eq,

Source§

impl<K, V> Sync for LruMap<K, V>
where K: Hash + Eq,

Auto Trait Implementations§

§

impl<K, V> Freeze for LruMap<K, V>

§

impl<K, V> RefUnwindSafe for LruMap<K, V>

§

impl<K, V> Unpin for LruMap<K, V>
where K: Unpin, V: Unpin,

§

impl<K, V> UnwindSafe for LruMap<K, V>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where 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 T
where 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

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 T
where U: TryFrom<T>,

Source§

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.