expire_cache 0.1.13

Efficient double-buffered expiration cache / 高效双缓冲过期缓存
Documentation
use std::{borrow::Borrow, future::Future, sync::atomic::Ordering};

use crate::Map;

pub trait GetOrInitAsync: Map {
  fn get_or_init_async<'a, E: Send, F: Future<Output = Result<Self::Val, E>>>(
    &'a self,
    key: &Self::Key,
    func: impl FnOnce(&Self::Key) -> F,
  ) -> impl Future<Output = Result<Self::RefVal<'a>, E>>;
}

impl<T: GetOrInitAsync + 'static> crate::Expire<T> {
  pub async fn get_or_init_async<'a, E: Send, F: Future<Output = Result<T::Val, E>>>(
    &'a self,
    key: impl Borrow<T::Key> + Send,
    func: impl FnOnce(&T::Key) -> F + Send,
  ) -> Result<T::RefVal<'a>, E> {
    let inner = unsafe { &*self.inner };
    let key_ref = key.borrow();
    let pos = inner.pos.load(Ordering::Relaxed);
    if let Some(v) = inner.cache[1 - pos].get(key_ref) {
      return Ok(v);
    }
    inner.cache[pos].get_or_init_async(key_ref, func).await
  }
}