Skip to main content

Lifecycle

Trait Lifecycle 

Source
pub trait Lifecycle: Send + Sync {
    // Required method
    fn on_evict(&self, key: &dyn Any);

    // Provided methods
    fn on_remove(&self, key: &dyn Any) { ... }
    fn on_clear(&self, key: &dyn Any) { ... }
}
Expand description

Hooks into the lifetime of cache items.

The functions should be small and very fast, otherwise the cache performance might be negatively affected. Lifecycle methods are called synchronously after releasing the shard lock.

§Type Erasure

Because the cache supports heterogeneous key types via type erasure, the lifecycle methods receive type-erased &dyn Any references. Use downcast_ref to recover the concrete types:

fn on_evict(&self, key: &dyn Any) {
    if let Some(key) = key.downcast_ref::<MyKey>() {
        // Handle eviction of MyKey
    }
}

Required Methods§

Source

fn on_evict(&self, key: &dyn Any)

Called when an item is evicted from the cache due to capacity pressure.

This is called during eviction triggered by insert operations that need space.

§Arguments
  • key - Reference to the evicted key (downcast to your key type)

Provided Methods§

Source

fn on_remove(&self, key: &dyn Any)

Called when an item is explicitly removed via cache.remove().

By default, this calls [on_evict]. Override if you need different behavior for explicit removals vs automatic evictions.

§Arguments
  • key - Reference to the removed key (downcast to your key type)
Source

fn on_clear(&self, key: &dyn Any)

Called when the cache is cleared via cache.clear().

By default, this calls [on_evict] for each entry. Override if you need bulk cleanup logic instead of per-entry callbacks.

§Arguments
  • key - Reference to the cleared key (downcast to your key type)

Implementations on Foreign Types§

Source§

impl<L: Lifecycle> Lifecycle for Arc<L>

Lifecycle implementation that wraps an Arc<L> for shared ownership.

This is used internally when the cache needs to clone the lifecycle.

Source§

fn on_evict(&self, key: &dyn Any)

Source§

fn on_remove(&self, key: &dyn Any)

Source§

fn on_clear(&self, key: &dyn Any)

Implementors§

Source§

impl Lifecycle for DefaultLifecycle

Source§

impl<K, F> Lifecycle for TypedLifecycle<K, F>
where K: Clone + Send + Sync + 'static, F: Fn(K) + Send + Sync,