LoadingCache

Struct LoadingCache 

Source
pub struct LoadingCache<K: Clone + Eq + Hash + Send, V: Clone + Sized + Send, E: Debug + Clone + Send, B: CacheBacking<K, CacheEntry<V, E>>> { /* private fields */ }

Implementations§

Source§

impl<K: Eq + Hash + Clone + Send + 'static, V: Clone + Sized + Send + 'static, E: Clone + Sized + Send + Debug + 'static> LoadingCache<K, V, E, HashMapBacking<K, CacheEntry<V, E>>>

Source

pub fn new<T, F>( loader: T, ) -> LoadingCache<K, V, E, HashMapBacking<K, CacheEntry<V, E>>>
where F: Future<Output = Result<V, E>> + Sized + Send + 'static, T: Fn(K) -> F + Send + 'static,

Creates a new instance of a LoadingCache with the default HashMapBacking

§Arguments
  • loader - A function which returns a Future<Output=Option>
§Return Value

This method returns a tuple, with: 0 - The instance of the LoadingCache 1 - The CacheHandle which is a JoinHandle<()> and represents the task which operates the cache

§Examples
use cache_loader_async::cache_api::LoadingCache;
use std::collections::HashMap;
async fn example() {
    let static_db: HashMap<String, u32> =
        vec![("foo".into(), 32), ("bar".into(), 64)]
            .into_iter()
            .collect();

    let cache = LoadingCache::new(move |key: String| {
        let db_clone = static_db.clone();
        async move {
            db_clone.get(&key).cloned().ok_or(1)
        }
    });

    let result = cache.get("foo".to_owned()).await.unwrap();

    assert_eq!(result, 32);
}
Source§

impl<K: Eq + Hash + Clone + Send + 'static, V: Clone + Sized + Send + 'static, E: Clone + Sized + Send + Debug + 'static, B: CacheBacking<K, CacheEntry<V, E>> + Send + 'static> LoadingCache<K, V, E, B>

Source

pub fn with_backing<T, F>(backing: B, loader: T) -> LoadingCache<K, V, E, B>
where F: Future<Output = Result<V, E>> + Sized + Send + 'static, T: Fn(K) -> F + Send + 'static,

Creates a new instance of a LoadingCache with a custom CacheBacking

§Arguments
  • backing - The custom backing which the cache should use
  • loader - A function which returns a Future<Output=Result<V, E>>
§Return Value

This method returns a tuple, with: 0 - The instance of the LoadingCache 1 - The CacheHandle which is a JoinHandle<()> and represents the task which operates the cache

§Examples
use cache_loader_async::cache_api::LoadingCache;
use std::collections::HashMap;
use cache_loader_async::backing::HashMapBacking;
async fn example() {
    let static_db: HashMap<String, u32> =
        vec![("foo".into(), 32), ("bar".into(), 64)]
            .into_iter()
            .collect();

    let cache = LoadingCache::with_backing(
        HashMapBacking::new(), // this is the default implementation of `new`
        move |key: String| {
            let db_clone = static_db.clone();
            async move {
                db_clone.get(&key).cloned().ok_or(1)
            }
        }
    );

    let result = cache.get("foo".to_owned()).await.unwrap();

    assert_eq!(result, 32);
}
Source

pub fn with_meta_loader<T, F>(backing: B, loader: T) -> LoadingCache<K, V, E, B>
where F: Future<Output = Result<DataWithMeta<K, V, E, B>, E>> + Sized + Send + 'static, T: Fn(K) -> F + Send + 'static,

Creates a new instance of a LoadingCache with a custom CacheBacking and an optional Meta loader.

§Arguments
  • backing - The custom backing which the cache should use
  • loader - A function which returns a Future<Output=Result<MetaWithData<K, V, E, B>, E>>
§Return Value

This method returns a tuple, with: 0 - The instance of the LoadingCache 1 - The CacheHandle which is a JoinHandle<()> and represents the task which operates the cache

§Examples
use cache_loader_async::cache_api::{LoadingCache, WithMeta};
use std::collections::HashMap;
use cache_loader_async::backing::HashMapBacking;
async fn example() {
    let static_db: HashMap<String, u32> =
        vec![("foo".into(), 32), ("bar".into(), 64)]
            .into_iter()
            .collect();

    let cache = LoadingCache::with_meta_loader(
        HashMapBacking::new(), // this is the default implementation of `new`
        move |key: String| {
            let db_clone = static_db.clone();
            async move {
                db_clone.get(&key).cloned().ok_or(1)
                    .with_meta(None)
            }
        }
    );

    let result = cache.get("foo".to_owned()).await.unwrap();

    assert_eq!(result, 32);
}
Source

pub async fn get(&self, key: K) -> Result<V, CacheLoadingError<E>>

Retrieves or loads the value for specified key from either cache or loader function

§Arguments
  • key - The key which should be loaded
§Return Value

Returns a Result with: Ok - Value of type V Err - Error of type CacheLoadingError

Source

pub async fn get_with_meta( &self, key: K, ) -> Result<ResultMeta<V>, CacheLoadingError<E>>

Retrieves or loads the value for specified key from either cache or loader function with meta information, i.e. if the key was loaded from cache or from the loader function

§Arguments
  • key - The key which should be loaded
§Return Value

Returns a Result with: Ok - Value of type ResultMeta Err - Error of type CacheLoadingError

Source

pub async fn set_with_meta( &self, key: K, value: V, meta: Option<B::Meta>, ) -> Result<Option<V>, CacheLoadingError<E>>

Sets the value for specified key and bypasses eventual currently ongoing loads If a key has been set programmatically, eventual concurrent loads will not change the value of the key.

§Arguments
  • key - The key which should be set
  • value - The value which should be set
  • meta - The meta which should be attached to the key
§Return Value

Returns a Result with: Ok - Previous value of type V wrapped in an Option depending whether there was a previous value Err - Error of type CacheLoadingError

Source

pub async fn set( &self, key: K, value: V, ) -> Result<Option<V>, CacheLoadingError<E>>

Sets the value for specified key and bypasses eventual currently ongoing loads If a key has been set programmatically, eventual concurrent loads will not change the value of the key.

§Arguments
  • key - The key which should be set
  • value - The value which should be set
§Return Value

Returns a Result with: Ok - Previous value of type V wrapped in an Option depending whether there was a previous value Err - Error of type CacheLoadingError

Source

pub async fn get_if_present( &self, key: K, ) -> Result<Option<V>, CacheLoadingError<E>>

Loads the value for the specified key from the cache and returns None if not present

§Arguments
  • key - The key which should be loaded
§Return Value

Returns a Result with: Ok - Value of type Option Err - Error of type CacheLoadingError

Source

pub async fn exists(&self, key: K) -> Result<bool, CacheLoadingError<E>>

Checks whether a specific value is mapped for the given key

§Arguments
  • key - The key which should be checked
§Return Value

Returns a Result with: Ok - bool Err - Error of type CacheLoadingError

Source

pub async fn remove(&self, key: K) -> Result<Option<V>, CacheLoadingError<E>>

Removes a specific key-value mapping from the cache and returns the previous result if there was any or None

§Arguments
  • key - The key which should be evicted
§Return Value

Returns a Result with: Ok - Value of type Option Err - Error of type CacheLoadingError

Source

pub async fn remove_if<P: Fn((&K, Option<&V>)) -> bool + Send + Sync + 'static>( &self, predicate: P, ) -> Result<(), CacheLoadingError<E>>

Removes all entries which match the specified predicate

§Arguments
  • predicate - The predicate to test all entries against
§Return Value

Returns a Result with: Ok - Nothing, the removed values are discarded Err - Error of type CacheLoadingError -> the values were not discarded

Source

pub async fn clear(&self) -> Result<(), CacheLoadingError<E>>

Removes all entries from the underlying backing

§Return Value

Returns a Result with: Ok - Nothing, the removed values are discarded Err - Error of type CacheLoadingError -> the values were not discarded

Source

pub async fn update<U>( &self, key: K, update_fn: U, ) -> Result<V, CacheLoadingError<E>>
where U: FnOnce(V) -> V + Send + 'static,

Updates a key on the cache with the given update function and returns the updated value

If the key is not present yet, it’ll be loaded using the loader function and will be updated once this loader function completes. In case the key was manually updated via set during the loader function the update will take place on the manually updated value, so user-controlled input takes precedence over the loader function

§Arguments
  • key - The key which should be updated
  • update_fn - A FnOnce(V) -> V which has the current value as parameter and should return the updated value
§Return Value

Returns a Result with: Ok - Value of type V which is the previously mapped value Err - Error of type CacheLoadingError

Source

pub async fn update_if_exists<U>( &self, key: K, update_fn: U, ) -> Result<Option<V>, CacheLoadingError<E>>
where U: FnOnce(V) -> V + Send + 'static,

Updates a key on the cache with the given update function and returns the updated value if it existed

If the key is not present yet, it’ll be ignored. This also counts for keys in LOADING state.

§Arguments
  • key - The key which should be updated
  • update_fn - A FnOnce(V) -> V which has the current value as parameter and should return the updated value
§Return Value

Returns a Result with: Ok - Optional value of type V which is the previously mapped value Err - Error of type CacheLoadingError

Source

pub async fn update_mut<U>( &self, key: K, update_fn: U, ) -> Result<V, CacheLoadingError<E>>
where U: FnMut(&mut V) + Send + 'static,

Updates a key on the cache with the given update function and returns the updated value

If the key is not present yet, it’ll be loaded using the loader function and will be updated once this loader function completes. In case the key was manually updated via set during the loader function the update will take place on the manually updated value, so user-controlled input takes precedence over the loader function

§Arguments
  • key - The key which should be updated
  • update_fn - A FnMut(&mut V) -> () which has the current value as parameter and should update it accordingly
§Return Value

Returns a Result with: Ok - Value of type V Err - Error of type CacheLoadingError

Source

pub async fn update_mut_if_exists<U>( &self, key: K, update_fn: U, ) -> Result<Option<V>, CacheLoadingError<E>>
where U: FnMut(&mut V) + Send + 'static,

Updates a key on the cache with the given update function and returns the updated value if it existed

If the key is not present yet, it’ll be ignored. Keys in LOADING state will still be updated as they get available.

§Arguments
  • key - The key which should be updated
  • update_fn - A FnMut(&mut V) -> () which has the current value as parameter and should update it accordingly
§Return Value

Returns a Result with: Ok - Optional value of type V Err - Error of type CacheLoadingError

Trait Implementations§

Source§

impl<K: Eq + Hash + Clone + Send + 'static, V: Clone + Sized + Send + 'static, E: Clone + Sized + Send + Debug + 'static, B: CacheBacking<K, CacheEntry<V, E>> + Send + 'static> Clone for LoadingCache<K, V, E, B>

Source§

fn clone(&self) -> Self

Returns a duplicate 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 + Clone + Eq + Hash + Send, V: Debug + Clone + Sized + Send, E: Debug + Debug + Clone + Send, B: Debug + CacheBacking<K, CacheEntry<V, E>>> Debug for LoadingCache<K, V, E, B>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<K, V, E, B> Freeze for LoadingCache<K, V, E, B>

§

impl<K, V, E, B> RefUnwindSafe for LoadingCache<K, V, E, B>

§

impl<K, V, E, B> Send for LoadingCache<K, V, E, B>

§

impl<K, V, E, B> Sync for LoadingCache<K, V, E, B>

§

impl<K, V, E, B> Unpin for LoadingCache<K, V, E, B>

§

impl<K, V, E, B> UnwindSafe for LoadingCache<K, V, E, B>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

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 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.