pub trait CacheableWithState<S: Send + Sync + Any>: Serialize + DeserializeOwned + Hash + Eq + Send + Sync + Any {
    type Output: Send + Sync + Serialize + DeserializeOwned;
    type Error: Send + Sync;

    // Required method
    fn generate_with_state(&self, state: S) -> Result<Self::Output, Self::Error>;
}
Expand description

A cacheable object whose generator needs to store state.

§Examples

use std::sync::{Arc, Mutex};
use cache::CacheableWithState;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Clone, Hash, Eq, PartialEq)]
pub struct Params {
    param1: u64,
    param2: String,
};

#[derive(Clone)]
pub struct Log(Arc<Mutex<Vec<Params>>>);

impl CacheableWithState<Log> for Params {
    type Output = u64;
    type Error = anyhow::Error;

    fn generate_with_state(&self, state: Log) -> anyhow::Result<u64> {
        println!("Logging parameters...");
        state.0.lock().unwrap().push(self.clone());

        println!("Executing an expensive computation...");

        // ...

        if error_condition {
            anyhow::bail!("an error occured during computation");
        }

        Ok(computation_result)
    }
}

Required Associated Types§

source

type Output: Send + Sync + Serialize + DeserializeOwned

The output produced by generating the object.

source

type Error: Send + Sync

The error type returned by CacheableWithState::generate_with_state.

Required Methods§

source

fn generate_with_state(&self, state: S) -> Result<Self::Output, Self::Error>

Generates the output of the cacheable object using state.

Note: The state is not used to determine whether the object should be regenerated. As such, it should not impact the output of this function but rather should only be used to store collateral or reuse computation from other function calls.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<S: Send + Sync + Any, T: CacheableWithState<S>> CacheableWithState<S> for Arc<T>

§

type Output = <T as CacheableWithState<S>>::Output

§

type Error = <T as CacheableWithState<S>>::Error

source§

fn generate_with_state(&self, state: S) -> Result<Self::Output, Self::Error>

Implementors§