Struct caches::RawLRU

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

A fixed size RawLRU Cache

Example

  • Use RawLRU with default noop callback.
use caches::{RawLRU, PutResult, Cache};

let mut cache = RawLRU::new(2).unwrap();
// fill the cache
assert_eq!(cache.put(1, 1), PutResult::Put);
assert_eq!(cache.put(2, 2), PutResult::Put);

// put 3, should evict the entry (1, 1)
assert_eq!(cache.put(3, 3), PutResult::Evicted {key: 1,value: 1});

// put 4, should evict the entry (2, 2)
assert_eq!(cache.put(4, 4), PutResult::Evicted {key: 2,value: 2});

// get 3, should update the recent-ness
assert_eq!(cache.get(&3), Some(&3));

// put 5, should evict the entry (4, 4)
assert_eq!(cache.put(5, 5), PutResult::Evicted {key: 4,value: 4});
  • Use RawLRU with a custom callback.
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use caches::{OnEvictCallback, RawLRU, PutResult, Cache};

// EvictedCounter is a callback which is used to record the number of evicted entries.
struct EvictedCounter {
    ctr: Arc<AtomicU64>,
}

impl EvictedCounter {
    pub fn new(ctr: Arc<AtomicU64>) -> Self {
        Self {
            ctr,
        }
    }
}

impl OnEvictCallback for EvictedCounter {
    fn on_evict<K, V>(&self, _: &K, _: &V) {
        self.ctr.fetch_add(1, Ordering::SeqCst);
    }
}

let counter = Arc::new(AtomicU64::new(0));

let mut cache: RawLRU<u64, u64, EvictedCounter> = RawLRU::with_on_evict_cb(2, EvictedCounter::new(counter.clone())).unwrap();

// fill the cache
assert_eq!(cache.put(1, 1), PutResult::Put);
assert_eq!(cache.put(2, 2), PutResult::Put);

// put 3, should evict the entry (1, 1)
assert_eq!(cache.put(3, 3), PutResult::Evicted {key: 1,value: 1});

// put 4, should evict the entry (2, 2)
assert_eq!(cache.put(4, 4), PutResult::Evicted {key: 2,value: 2});

// get 3, should update the recent-ness
assert_eq!(cache.get(&3), Some(&3));

// put 5, should evict the entry (4, 4)
assert_eq!(cache.put(5, 5), PutResult::Evicted {key: 4,value: 4});

assert_eq!(counter.load(Ordering::SeqCst), 3);

Implementations

Creates a new LRU Cache that holds at most cap items.

Example
use caches::{Cache, RawLRU};
let mut cache: RawLRU<isize, &str> = RawLRU::new(10).unwrap();

Creates a new LRU Cache that holds at most cap items and uses the provided hash builder to hash keys.

Example
use caches::{RawLRU, DefaultHashBuilder};

let s = DefaultHashBuilder::default();
let mut cache: RawLRU<isize, &str> = RawLRU::with_hasher(10, s).unwrap();

Creates a new LRU Cache that holds at most cap items and uses the provided evict callback.

Example
use caches::{RawLRU, OnEvictCallback};
use std::sync::atomic::{AtomicU64, Ordering};

struct EvictedCounter {
    ctr: AtomicU64,
}

impl Default for EvictedCounter {
    fn default() -> Self {
        Self {
            ctr: AtomicU64::new(0),
        }
    }
}

impl OnEvictCallback for EvictedCounter {
    fn on_evict<K, V>(&self, _: &K, _: &V) {
        self.ctr.fetch_add(1, Ordering::SeqCst);
    }
}

let mut cache: RawLRU<isize, &str, EvictedCounter> = RawLRU::with_on_evict_cb(10, EvictedCounter::default()).unwrap();

Creates a new LRU Cache that holds at most cap items and uses the provided evict callback and the provided hash builder to hash keys.

Example
use caches::{RawLRU, OnEvictCallback, DefaultHashBuilder};
use std::sync::atomic::{AtomicU64, Ordering};

struct EvictedCounter {
    ctr: AtomicU64,
}

impl Default for EvictedCounter {
    fn default() -> Self {
        Self {
            ctr: AtomicU64::new(0),
        }
    }
}

impl OnEvictCallback for EvictedCounter {
    fn on_evict<K, V>(&self, _: &K, _: &V) {
        self.ctr.fetch_add(1, Ordering::SeqCst);
    }
}

let cache: RawLRU<isize, &str, EvictedCounter, DefaultHashBuilder> = RawLRU::with_on_evict_cb_and_hasher(10, EvictedCounter::default(), DefaultHashBuilder::default()).unwrap();

Returns the least recent used entry(&K, &V) in the cache or None if the cache is empty.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put("apple", 8);
cache.put("banana", 4);
cache.put("banana", 6);
cache.put("pear", 2);

assert_eq!(cache.get_lru(), Some((&"banana", &6)));

Returns the most recent used entry(&K, &V) in the cache or None if the cache is empty.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put("apple", 8);
cache.put("banana", 4);
cache.put("banana", 6);
cache.put("pear", 2);

assert_eq!(cache.get_mru(), Some((&"pear", &2)));

Returns the least recent used entry(&K, &mut V) in the cache or None if the cache is empty.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put("apple", 8);
cache.put("banana", 4);
cache.put("banana", 6);
cache.put("pear", 2);

assert_eq!(cache.get_lru_mut(), Some((&"banana", &mut 6)));

Returns the most recent used entry (&K, &mut V) in the cache or None if the cache is empty.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put("apple", 8);
cache.put("banana", 4);
cache.put("banana", 6);
cache.put("pear", 2);

assert_eq!(cache.get_mru_mut(), Some((&"pear", &mut 2)));

peek_or_put peeks if a key is in the cache without updating the recent-ness or deleting it for being stale, and if not, adds the value. Returns whether found and whether a PutResult.

Example
use caches::{RawLRU, PutResult, Cache};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.put(3, "c");

assert_eq!(cache.peek_or_put(2, "B"), (Some(&"b"), None));
assert_eq!(cache.peek_or_put(1, "A"), (None, Some(PutResult::Evicted { key: 2, value: "b",})));

peek_mut_or_put peeks if a key is in the cache without updating the recent-ness or deleting it for being stale, and if not, adds the value. Returns whether found and whether a PutResult.

Example
use caches::{RawLRU, PutResult, Cache};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.put(3, "c");

assert_eq!(cache.peek_mut_or_put(2, "B"), (Some(&mut "b"), None));
assert_eq!(cache.peek_mut_or_put(1, "A"), (None, Some(PutResult::Evicted { key: 2, value: "b",})));

Returns the value corresponding to the least recently used item or None if the cache is empty. Like peek, peek_lru does not update the LRU list so the item’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek_lru(), Some((&1, &"a")));

Returns the value corresponding to the least recently used item or None if the cache is empty. Like peek, peek_lru does not update the LRU list so the item’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek_lru_mut(), Some((&1, &mut "a")));

Returns the value corresponding to the most recently used item or None if the cache is empty. Like peek, peek_lru does not update the LRU list so the item’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek_mru(), Some((&2, &"b")));

Returns the mutable value corresponding to the most recently used item or None if the cache is empty. Like peek, peek_lru does not update the LRU list so the item’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek_mru_mut(), Some((&2, &mut "b")));

contains_or_put checks if a key is in the cache without updating the recent-ness or deleting it for being stale, and if not, adds the value. Returns whether found and whether a PutResult.

Example
use caches::{RawLRU, PutResult, Cache};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.put(3, "c");

assert_eq!(cache.contains_or_put(2, "B"), (true, None));
assert_eq!(cache.contains_or_put(1, "A"), (false, Some(PutResult::Evicted { key: 2, value: "b",})));

Removes and returns the key and value corresponding to the least recently used item or None if the cache is empty.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(2, "a");
cache.put(3, "b");
cache.put(4, "c");
cache.get(&3);

assert_eq!(cache.remove_lru(), Some((4, "c")));
assert_eq!(cache.remove_lru(), Some((3, "b")));
assert_eq!(cache.remove_lru(), None);
assert_eq!(cache.len(), 0);

An iterator visiting all keys in most-recently used order. The iterator element type is &'a K.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for key in cache.keys() {
    println!("key: {}", key);
}

An iterator visiting all keys in less-recently used order. The iterator element type is &'a K.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for key in cache.keys_lru() {
    println!("key: {}", key);
}

An iterator visiting all values in most-recently used order. The iterator element type is &'a V.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for val in cache.values() {
    println!("val: {}",  val);
}

An iterator visiting all values in less-recently used order. The iterator element type is &'a V.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for val in cache.values_lru() {
    println!("val: {}", val);
}

An iterator visiting all values in most-recently used order. The iterator element type is &'a mut V.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for val in cache.values_mut() {
    println!("val: {}", val);
}

An iterator visiting all values in less-recently used order. The iterator element type is &'a mut V.

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for val in cache.values_lru_mut() {
    println!("val: {}", val);
}

An iterator visiting all entries in most-recently used order. The iterator element type is (&'a K, &'a V).

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for (key, val) in cache.iter() {
    println!("key: {} val: {}", key, val);
}

An iterator visiting all entries in less-recently used order. The iterator element type is (&'a K, &'a V).

Examples
use caches::{Cache, RawLRU};

let mut cache = RawLRU::new(3).unwrap();
cache.put("a", 1);
cache.put("b", 2);
cache.put("c", 3);

for (key, val) in cache.iter_lru() {
    println!("key: {} val: {}", key, val);
}

An iterator visiting all entries in most-recently-used order, giving a mutable reference on V. The iterator element type is (&'a K, &'a mut V).

Examples
use caches::{Cache, RawLRU};

struct HddBlock {
    dirty: bool,
    data: [u8; 512]
}

let mut cache = RawLRU::new(3).unwrap();
cache.put(0, HddBlock { dirty: false, data: [0x00; 512]});
cache.put(1, HddBlock { dirty: true,  data: [0x55; 512]});
cache.put(2, HddBlock { dirty: true,  data: [0x77; 512]});

// write dirty blocks to disk.
for (block_id, block) in cache.iter_mut() {
    if block.dirty {
        // write block to disk
        block.dirty = false
    }
}

An iterator visiting all entries in less-recently-used order, giving a mutable reference on V. The iterator element type is (&'a K, &'a mut V).

Examples
use caches::{Cache, RawLRU};

struct HddBlock {
    dirty: bool,
    data: [u8; 512]
}

let mut cache = RawLRU::new(3).unwrap();
cache.put(0, HddBlock { dirty: false, data: [0x00; 512]});
cache.put(1, HddBlock { dirty: true,  data: [0x55; 512]});
cache.put(2, HddBlock { dirty: true,  data: [0x77; 512]});

// write dirty blocks to disk.
for (block_id, block) in cache.iter_lru_mut() {
    if block.dirty {
        // write block to disk
        block.dirty = false
    }
}

Trait Implementations

Puts a key-value pair into cache, returns a PutResult.

Example
use caches::{RawLRU, PutResult, Cache};
let mut cache = RawLRU::new(2).unwrap();

assert_eq!(PutResult::Put, cache.put(1, "a"));
assert_eq!(PutResult::Put, cache.put(2, "b"));
assert_eq!(PutResult::Update("b"), cache.put(2, "beta"));
assert_eq!(PutResult::Evicted{ key: 1, value: "a"}, cache.put(3, "c"));

assert_eq!(cache.get(&1), None);
assert_eq!(cache.get(&2), Some(&"beta"));

Returns a reference to the value of the key in the cache or None if it is not present in the cache. Moves the key to the head of the LRU list if it exists.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.put(2, "c");
cache.put(3, "d");

assert_eq!(cache.get(&1), None);
assert_eq!(cache.get(&2), Some(&"c"));
assert_eq!(cache.get(&3), Some(&"d"));

Returns a mutable reference to the value of the key in the cache or None if it is not present in the cache. Moves the key to the head of the LRU list if it exists.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put("apple", 8);
cache.put("banana", 4);
cache.put("banana", 6);
cache.put("pear", 2);

assert_eq!(cache.get_mut(&"apple"), None);
assert_eq!(cache.get_mut(&"banana"), Some(&mut 6));
assert_eq!(cache.get_mut(&"pear"), Some(&mut 2));

Returns a reference to the value corresponding to the key in the cache or None if it is not present in the cache. Unlike get, peek does not update the LRU list so the key’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek(&1), Some(&"a"));
assert_eq!(cache.peek(&2), Some(&"b"));

Returns a mutable reference to the value corresponding to the key in the cache or None if it is not present in the cache. Unlike get_mut, peek_mut does not update the LRU list so the key’s position will be unchanged.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");

assert_eq!(cache.peek_mut(&1), Some(&mut "a"));
assert_eq!(cache.peek_mut(&2), Some(&mut "b"));

Returns a bool indicating whether the given key is in the cache. Does not update the LRU list.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.put(3, "c");

assert!(!cache.contains(&1));
assert!(cache.contains(&2));
assert!(cache.contains(&3));

Removes and returns the value corresponding to the key from the cache or None if it does not exist.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();

cache.put(2, "a");

assert_eq!(cache.remove(&1), None);
assert_eq!(cache.remove(&2), Some("a"));
assert_eq!(cache.remove(&2), None);
assert_eq!(cache.len(), 0);

Clears the contents of the cache.

Example
use caches::{Cache, RawLRU};
let mut cache: RawLRU<isize, &str> = RawLRU::new(2).unwrap();
assert_eq!(cache.len(), 0);

cache.put(1, "a");
assert_eq!(cache.len(), 1);

cache.put(2, "b");
assert_eq!(cache.len(), 2);

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

Returns the number of key-value pairs that are currently in the the cache.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();
assert_eq!(cache.len(), 0);

cache.put(1, "a");
assert_eq!(cache.len(), 1);

cache.put(2, "b");
assert_eq!(cache.len(), 2);

cache.put(3, "c");
assert_eq!(cache.len(), 2);

Returns the maximum number of key-value pairs the cache can hold.

Example
use caches::{Cache, RawLRU};
let mut cache: RawLRU<isize, &str> = RawLRU::new(2).unwrap();
assert_eq!(cache.cap(), 2);

Returns a bool indicating whether the cache is empty or not.

Example
use caches::{Cache, RawLRU};
let mut cache = RawLRU::new(2).unwrap();
assert!(cache.is_empty());

cache.put(1, "a");
assert!(!cache.is_empty());
Formats the value using the given formatter. Read more
Executes the destructor for this type. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Creates a value from an iterator. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more

Resizes the cache. If the new capacity is smaller than the size of the current cache any entries past the new capacity are discarded.

Example
use caches::{Cache, RawLRU, ResizableCache};
let mut cache: RawLRU<isize, &str> = RawLRU::new(2).unwrap();

cache.put(1, "a");
cache.put(2, "b");
cache.resize(4);
cache.put(3, "c");
cache.put(4, "d");

assert_eq!(cache.len(), 4);
assert_eq!(cache.get(&1), Some(&"a"));
assert_eq!(cache.get(&2), Some(&"b"));
assert_eq!(cache.get(&3), Some(&"c"));
assert_eq!(cache.get(&4), Some(&"d"));

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.