Skip to content

Commit

Permalink
Merge pull request #445 from Swatinem/rm-async-trait
Browse files Browse the repository at this point in the history
Remove needless traits along with `async-trait` usage
  • Loading branch information
tatsuya6502 authored Aug 25, 2024
2 parents a2123dc + 103ef62 commit e854989
Show file tree
Hide file tree
Showing 10 changed files with 161 additions and 359 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ default = ["atomic64", "quanta"]
sync = []

# Enable this feature to use `moka::future::Cache`.
future = ["async-lock", "async-trait", "event-listener", "futures-util"]
future = ["async-lock", "event-listener", "futures-util"]

# Enable this feature to activate optional logging from caches.
# Currently cache will emit log only when it encounters a panic in user provided
Expand Down Expand Up @@ -60,7 +60,6 @@ quanta = { version = "0.12.2", optional = true }

# Optional dependencies (future)
async-lock = { version = "3.3", optional = true }
async-trait = { version = "0.1.58", optional = true }
event-listener = { version = "5.3", optional = true }
futures-util = { version = "0.3.17", optional = true }

Expand Down
94 changes: 12 additions & 82 deletions src/future/base_cache.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
housekeeper::{Housekeeper, InnerSync},
invalidator::{GetOrRemoveEntry, Invalidator, KeyDateLite, PredicateFun},
housekeeper::Housekeeper,
invalidator::{Invalidator, KeyDateLite, PredicateFun},
key_lock::{KeyLock, KeyLockMap},
notifier::RemovalNotifier,
InterruptedOp, PredicateId,
Expand Down Expand Up @@ -36,7 +36,6 @@ use crate::{
use common::concurrent::debug_counters::CacheDebugStats;

use async_lock::{Mutex, MutexGuard, RwLock};
use async_trait::async_trait;
use crossbeam_channel::{Receiver, Sender, TrySendError};
use crossbeam_utils::atomic::AtomicCell;
use futures_util::future::BoxFuture;
Expand Down Expand Up @@ -384,7 +383,7 @@ where

#[inline]
pub(crate) async fn apply_reads_writes_if_needed(
inner: &Arc<impl InnerSync + Send + Sync + 'static>,
inner: &Arc<Inner<K, V, S>>,
ch: &Sender<WriteOp<K, V>>,
now: Instant,
housekeeper: Option<&HouseKeeperArc>,
Expand Down Expand Up @@ -620,7 +619,7 @@ where

#[inline]
pub(crate) async fn schedule_write_op(
inner: &Arc<impl InnerSync + Send + Sync + 'static>,
inner: &Arc<Inner<K, V, S>>,
ch: &Sender<WriteOp<K, V>>,
ch_ready_event: &event_listener::Event<()>,
op: WriteOp<K, V>,
Expand Down Expand Up @@ -1042,15 +1041,15 @@ pub(crate) struct Inner<K, V, S> {
max_capacity: Option<u64>,
entry_count: AtomicCell<u64>,
weighted_size: AtomicCell<u64>,
cache: CacheStore<K, V, S>,
pub(crate) cache: CacheStore<K, V, S>,
build_hasher: S,
deques: Mutex<Deques<K>>,
timer_wheel: Mutex<TimerWheel<K>>,
frequency_sketch: RwLock<FrequencySketch>,
frequency_sketch_enabled: AtomicBool,
read_op_ch: Receiver<ReadOp<K, V>>,
write_op_ch: Receiver<WriteOp<K, V>>,
write_op_ch_ready_event: event_listener::Event,
pub(crate) write_op_ch_ready_event: event_listener::Event,
eviction_policy: EvictionPolicyConfig,
expiration_policy: ExpirationPolicy<K, V>,
valid_after: AtomicInstant,
Expand Down Expand Up @@ -1101,7 +1100,7 @@ impl<K, V, S> Inner<K, V, S> {
}

#[inline]
fn is_removal_notifier_enabled(&self) -> bool {
pub(crate) fn is_removal_notifier_enabled(&self) -> bool {
self.removal_notifier.is_some()
}

Expand All @@ -1118,7 +1117,7 @@ impl<K, V, S> Inner<K, V, S> {
)
}

fn maybe_key_lock(&self, key: &Arc<K>) -> Option<KeyLock<'_, K, S>>
pub(crate) fn maybe_key_lock(&self, key: &Arc<K>) -> Option<KeyLock<'_, K, S>>
where
K: Hash + Eq,
S: BuildHasher,
Expand All @@ -1127,7 +1126,7 @@ impl<K, V, S> Inner<K, V, S> {
}

#[inline]
fn current_time_from_expiration_clock(&self) -> Instant {
pub(crate) fn current_time_from_expiration_clock(&self) -> Instant {
if self.clocks.has_expiration_clock.load(Ordering::Relaxed) {
Instant::new(
self.clocks
Expand Down Expand Up @@ -1191,7 +1190,7 @@ impl<K, V, S> Inner<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Send + Sync + 'static,
S: BuildHasher + Clone,
S: BuildHasher + Send + Sync + Clone + 'static,
{
// Disable a Clippy warning for having more than seven arguments.
// https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments
Expand Down Expand Up @@ -1354,83 +1353,14 @@ where
}
}

#[async_trait]
impl<K, V, S> GetOrRemoveEntry<K, V> for Inner<K, V, S>
where
K: Hash + Eq,
S: BuildHasher + Send + Sync + 'static,
{
fn get_value_entry(&self, key: &Arc<K>, hash: u64) -> Option<TrioArc<ValueEntry<K, V>>> {
self.cache.get(hash, |k| k == key)
}

async fn remove_key_value_if<F>(
&self,
key: &Arc<K>,
hash: u64,
condition: F,
) -> Option<TrioArc<ValueEntry<K, V>>>
where
K: Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
F: for<'a, 'b> FnMut(&'a Arc<K>, &'b TrioArc<ValueEntry<K, V>>) -> bool + Send,
{
// Lock the key for removal if blocking removal notification is enabled.
let kl = self.maybe_key_lock(key);
let _klg = if let Some(lock) = &kl {
Some(lock.lock().await)
} else {
None
};

let maybe_entry = self.cache.remove_if(hash, |k| k == key, condition);
if let Some(entry) = &maybe_entry {
if self.is_removal_notifier_enabled() {
self.notify_single_removal(Arc::clone(key), entry, RemovalCause::Explicit)
.await;
}
}
maybe_entry
}
}

#[async_trait]
impl<K, V, S> InnerSync for Inner<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
/// Runs the pending tasks. Returns `true` if there are more entries to evict.
async fn run_pending_tasks(
&self,
timeout: Option<Duration>,
max_log_sync_repeats: u32,
eviction_batch_size: u32,
) -> bool {
self.do_run_pending_tasks(timeout, max_log_sync_repeats, eviction_batch_size)
.await
}

/// Notifies all the async tasks waiting in `BaseCache::schedule_write_op` method
/// for the write op channel to have enough room.
fn notify_write_op_ch_is_ready(&self) {
self.write_op_ch_ready_event.notify(usize::MAX);
}

fn now(&self) -> Instant {
self.current_time_from_expiration_clock()
}
}

impl<K, V, S> Inner<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
/// Runs the pending tasks. Returns `true` if there are more entries to evict.
async fn do_run_pending_tasks(
pub(crate) async fn do_run_pending_tasks(
&self,
timeout: Option<Duration>,
max_log_sync_repeats: u32,
Expand Down Expand Up @@ -2643,7 +2573,7 @@ where
K: Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
{
async fn notify_single_removal(
pub(crate) async fn notify_single_removal(
&self,
key: Arc<K>,
entry: &TrioArc<ValueEntry<K, V>>,
Expand Down
52 changes: 9 additions & 43 deletions src/future/cache.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{
base_cache::BaseCache,
value_initializer::{GetOrInsert, InitResult, ValueInitializer},
value_initializer::{InitResult, ValueInitializer},
CacheBuilder, CancelGuard, Iter, OwnedKeyEntrySelector, PredicateId, RefKeyEntrySelector,
WriteOp,
};
Expand All @@ -15,7 +15,6 @@ use crate::{
#[cfg(feature = "unstable-debug-counters")]
use crate::common::concurrent::debug_counters::CacheDebugStats;

use async_trait::async_trait;
use std::{
borrow::Borrow,
collections::hash_map::RandomState,
Expand Down Expand Up @@ -631,7 +630,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
/// [builder-name-method]: ./struct.CacheBuilder.html#method.name
///
pub struct Cache<K, V, S = RandomState> {
base: BaseCache<K, V, S>,
pub(crate) base: BaseCache<K, V, S>,
value_initializer: Arc<ValueInitializer<K, V, S>>,

#[cfg(test)]
Expand Down Expand Up @@ -1806,7 +1805,7 @@ where
}
}

async fn insert_with_hash(&self, key: Arc<K>, hash: u64, value: V) {
pub(crate) async fn insert_with_hash(&self, key: Arc<K>, hash: u64, value: V) {
if self.base.is_map_disabled() {
return;
}
Expand Down Expand Up @@ -1901,7 +1900,12 @@ where
}
}

async fn invalidate_with_hash<Q>(&self, key: &Q, hash: u64, need_value: bool) -> Option<V>
pub(crate) async fn invalidate_with_hash<Q>(
&self,
key: &Q,
hash: u64,
need_value: bool,
) -> Option<V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
Expand Down Expand Up @@ -2015,44 +2019,6 @@ where
}
}

#[async_trait]
impl<K, V, S> GetOrInsert<K, V> for Cache<K, V, S>
where
K: Hash + Eq + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
S: BuildHasher + Clone + Send + Sync + 'static,
{
async fn get_without_recording<I>(
&self,
key: &Arc<K>,
hash: u64,
replace_if: Option<&mut I>,
) -> Option<V>
where
I: for<'i> FnMut(&'i V) -> bool + Send,
{
self.base
.get_with_hash(key, hash, replace_if, false, false)
.await
.map(Entry::into_value)
}

async fn get_entry(&self, key: &Arc<K>, hash: u64) -> Option<Entry<K, V>> {
let ignore_if = None as Option<&mut fn(&V) -> bool>;
self.base
.get_with_hash(key, hash, ignore_if, true, true)
.await
}

async fn insert(&self, key: Arc<K>, hash: u64, value: V) {
self.insert_with_hash(key.clone(), hash, value).await;
}

async fn remove(&self, key: &Arc<K>, hash: u64) -> Option<V> {
self.invalidate_with_hash(key, hash, true).await
}
}

// For unit tests.
// For unit tests.
#[cfg(test)]
Expand Down
Loading

0 comments on commit e854989

Please sign in to comment.