Cache

Struct Cache 

Source
pub struct Cache<Key, Val, We = UnitWeighter, B = DefaultHashBuilder, L = DefaultLifecycle<Key, Val>> {
    hash_builder: B,
    shards: Box<[RwLock<CacheShard<Key, Val, We, B, L, Arc<Placeholder<Val>>>>]>,
    shards_mask: u64,
    lifecycle: L,
}
Expand description

A concurrent cache

The concurrent cache is internally composed of equally sized shards, each of which is independently synchronized. This allows for low contention when multiple threads are accessing the cache but limits the maximum weight capacity of each shard.

§Value

Cache values are cloned when fetched. Users should wrap their values with Arc<_> if necessary to avoid expensive clone operations. If interior mutability is required Arc<Mutex<_>> or Arc<RwLock<_>> can also be used.

§Thread Safety and Concurrency

The cache instance can wrapped with an Arc (or equivalent) and shared between threads. All methods are accessible via non-mut references so no further synchronization (e.g. Mutex) is needed.

Fields§

§hash_builder: B§shards: Box<[RwLock<CacheShard<Key, Val, We, B, L, Arc<Placeholder<Val>>>>]>§shards_mask: u64§lifecycle: L

Implementations§

Source§

impl<Key: Eq + Hash, Val: Clone> Cache<Key, Val>

Source

pub fn new(items_capacity: usize) -> Self

Creates a new cache with holds up to items_capacity items (approximately).

Source§

impl<Key: Eq + Hash, Val: Clone, We: Weighter<Key, Val> + Clone> Cache<Key, Val, We>

Source

pub fn with_weighter( estimated_items_capacity: usize, weight_capacity: u64, weighter: We, ) -> Self

Source§

impl<Key: Eq + Hash, Val: Clone, We: Weighter<Key, Val> + Clone, B: BuildHasher + Clone, L: Lifecycle<Key, Val> + Clone> Cache<Key, Val, We, B, L>

Source

pub fn with( estimated_items_capacity: usize, weight_capacity: u64, weighter: We, hash_builder: B, lifecycle: L, ) -> Self

Creates a new cache that can hold up to weight_capacity in weight. estimated_items_capacity is the estimated number of items the cache is expected to hold, roughly equivalent to weight_capacity / average item weight.

Source

pub fn with_options( options: Options, weighter: We, hash_builder: B, lifecycle: L, ) -> Self

Constructs a cache based on OptionsBuilder.

§Example
use quick_cache::{sync::{Cache, DefaultLifecycle}, OptionsBuilder, UnitWeighter, DefaultHashBuilder};

Cache::<(String, u64), String>::with_options(
  OptionsBuilder::new()
    .estimated_items_capacity(10000)
    .weight_capacity(10000)
    .build()
    .unwrap(),
    UnitWeighter,
    DefaultHashBuilder::default(),
    DefaultLifecycle::default(),
);
Source

pub fn is_empty(&self) -> bool

Returns whether the cache is empty

Source

pub fn len(&self) -> usize

Returns the number of cached items

Source

pub fn weight(&self) -> u64

Returns the total weight of cached items

Source

pub fn capacity(&self) -> u64

Returns the total maximum weight capacity of cached items. Note that the cache may be composed of multiple shards and each shard has its own maximum weight capacity, see Self::shard_capacity.

Source

pub fn shard_capacity(&self) -> u64

Returns the maximum weight capacity of each shard.

Source

pub fn num_shards(&self) -> usize

Returns the number of shards.

Source

fn shard_for<Q>( &self, key: &Q, ) -> Option<(&RwLock<CacheShard<Key, Val, We, B, L, Arc<Placeholder<Val>>>>, u64)>
where Q: Hash + Equivalent<Key> + ?Sized,

Source

pub fn reserve(&self, additional: usize)

Reserver additional space for additional entries. Note that this is counted in entries, and is not weighted.

Source

pub fn contains_key<Q>(&self, key: &Q) -> bool
where Q: Hash + Equivalent<Key> + ?Sized,

Check if a key exist in the cache.

Source

pub fn get<Q>(&self, key: &Q) -> Option<Val>
where Q: Hash + Equivalent<Key> + ?Sized,

Fetches an item from the cache whose key is key.

Source

pub fn peek<Q>(&self, key: &Q) -> Option<Val>
where Q: Hash + Equivalent<Key> + ?Sized,

Peeks an item from the cache whose key is key. Contrary to gets, peeks don’t alter the key “hotness”.

Source

pub fn remove<Q>(&self, key: &Q) -> Option<(Key, Val)>
where Q: Hash + Equivalent<Key> + ?Sized,

Remove an item from the cache whose key is key. Returns the removed entry, if any.

Source

pub fn remove_if<Q, F>(&self, key: &Q, f: F) -> Option<(Key, Val)>
where Q: Hash + Equivalent<Key> + ?Sized, F: FnOnce(&Val) -> bool,

Remove an item from the cache whose key is key if f(&value) returns true for that entry. Compared to peek and remove, this method guarantees that no new value was inserted in-between.

Returns the removed entry, if any.

Source

pub fn replace( &self, key: Key, value: Val, soft: bool, ) -> Result<(), (Key, Val)>

Inserts an item in the cache, but only if an entry with key key already exists. If soft is set, the replace operation won’t affect the “hotness” of the entry, even if the value is replaced.

Returns Ok if the entry was admitted and Err(_) if it wasn’t.

Source

pub fn replace_with_lifecycle( &self, key: Key, value: Val, soft: bool, ) -> Result<L::RequestState, (Key, Val)>

Inserts an item in the cache, but only if an entry with key key already exists. If soft is set, the replace operation won’t affect the “hotness” of the entry, even if the value is replaced.

Returns Ok if the entry was admitted and Err(_) if it wasn’t.

Source

pub fn retain<F>(&self, f: F)
where F: Fn(&Key, &Val) -> bool,

Retains only the items specified by the predicate. In other words, remove all items for which f(&key, &value) returns false. The elements are visited in arbitrary order.

Source

pub fn insert(&self, key: Key, value: Val)

Inserts an item in the cache with key key.

Source

pub fn insert_with_lifecycle(&self, key: Key, value: Val) -> L::RequestState

Inserts an item in the cache with key key.

Source

pub fn clear(&self)

Clear all items from the cache

Source

pub fn iter(&self) -> Iter<'_, Key, Val, We, B, L>
where Key: Clone,

Iterates over the items in the cache returning cloned key value pairs.

The iterator is guaranteed to yield all items in the cache at the time of creation provided that they are not removed or evicted from the cache while iterating. The iterator may also yield items added to the cache after the iterator is created.

Source

pub fn drain(&self) -> Drain<'_, Key, Val, We, B, L>

Drains items from the cache.

The iterator is guaranteed to drain all items in the cache at the time of creation provided that they are not removed or evicted from the cache while draining. The iterator may also drain items added to the cache after the iterator is created. Due to the above, the cache may not be empty after the iterator is fully consumed if items are added to the cache while draining.

Note that dropping the iterator will not finish the draining process, unlike other drain methods.

Source

pub fn set_capacity(&self, new_weight_capacity: u64)

Sets the cache to a new weight capacity.

This will adjust the weight capacity of each shard proportionally. If the new capacity is smaller than the current weight, items will be evicted to bring the cache within the new limit.

Source

pub fn get_value_or_guard<Q>( &self, key: &Q, timeout: Option<Duration>, ) -> GuardResult<'_, Key, Val, We, B, L>
where Q: Hash + Equivalent<Key> + ToOwned<Owned = Key> + ?Sized,

Gets an item from the cache with key key .

If the corresponding value isn’t present in the cache, this functions returns a guard that can be used to insert the value once it’s computed. While the returned guard is alive, other calls with the same key using the get_value_guard or get_or_insert family of functions will wait until the guard is dropped or the value is inserted.

A None timeout means waiting forever. A Some(<zero>) timeout will return a Timeout error immediately if the value is not present and a guard is alive elsewhere.

Source

pub fn get_or_insert_with<Q, E>( &self, key: &Q, with: impl FnOnce() -> Result<Val, E>, ) -> Result<Val, E>
where Q: Hash + Equivalent<Key> + ToOwned<Owned = Key> + ?Sized,

Gets or inserts an item in the cache with key key.

See also get_value_or_guard and get_value_or_guard_async.

Source

pub async fn get_value_or_guard_async<'a, Q>( &'a self, key: &Q, ) -> Result<Val, PlaceholderGuard<'a, Key, Val, We, B, L>>
where Q: Hash + Equivalent<Key> + ToOwned<Owned = Key> + ?Sized,

Gets an item from the cache with key key.

If the corresponding value isn’t present in the cache, this functions returns a guard that can be used to insert the value once it’s computed. While the returned guard is alive, other calls with the same key using the get_value_guard or get_or_insert family of functions will wait until the guard is dropped or the value is inserted.

Source

pub async fn get_or_insert_async<Q, E>( &self, key: &Q, with: impl Future<Output = Result<Val, E>>, ) -> Result<Val, E>
where Q: Hash + Equivalent<Key> + ToOwned<Owned = Key> + ?Sized,

Gets or inserts an item in the cache with key key.

Source

pub fn memory_used(&self) -> MemoryUsed

Get total memory used by cache data structures

It should be noted that if cache key or value is some type like Vec<T>, the memory allocated in the heap will not be counted.

Trait Implementations§

Source§

impl<Key, Val, We, B, L> Debug for Cache<Key, Val, We, B, L>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Key, Val, We, B, L> Freeze for Cache<Key, Val, We, B, L>
where B: Freeze, L: Freeze,

§

impl<Key, Val, We, B, L> RefUnwindSafe for Cache<Key, Val, We, B, L>

§

impl<Key, Val, We, B, L> Send for Cache<Key, Val, We, B, L>
where B: Send, L: Send, We: Send, Key: Send, Val: Send + Sync,

§

impl<Key, Val, We, B, L> Sync for Cache<Key, Val, We, B, L>
where B: Sync + Send, L: Sync + Send, We: Send + Sync, Key: Send + Sync, Val: Send + Sync,

§

impl<Key, Val, We, B, L> Unpin for Cache<Key, Val, We, B, L>
where B: Unpin, L: Unpin,

§

impl<Key, Val, We, B, L> UnwindSafe for Cache<Key, Val, We, B, L>
where B: UnwindSafe, L: UnwindSafe,

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.