Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add load_if_changed to Cache to return a value only if it has changed #91

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,20 +150,34 @@ where
self.load_no_revalidate()
}

/// Loads a new value if available
///
/// This first checks if the cached value is up to date. This check is very cheap.
///
/// If it is up to date, `None` is returned. If it is outdated, a load is done on the underlying shared storage. The newly loaded value is then
/// stored in the cache and returned as `Some`.
#[inline]
pub fn load_if_changed(&mut self) -> Option<&T> {
self.revalidate().then(move || self.load_no_revalidate())
}

#[inline]
fn load_no_revalidate(&self) -> &T {
&self.cached
}

#[inline]
fn revalidate(&mut self) {
fn revalidate(&mut self) -> bool {
let cached_ptr = RefCnt::as_ptr(&self.cached);
// Node: Relaxed here is fine. We do not synchronize any data through this, we already have
// it synchronized in self.cache. We just want to check if it changed, if it did, the
// load_full will be responsible for any synchronization needed.
let shared_ptr = self.arc_swap.ptr.load(Ordering::Relaxed);
if cached_ptr != shared_ptr {
self.cached = self.arc_swap.load_full();
true
} else {
false
}
}

Expand Down Expand Up @@ -285,9 +299,12 @@ mod tests {

assert_eq!(42, **c1.load());
assert_eq!(42, **c2.load());

assert_eq!(None, c1.load_if_changed());
assert_eq!(None, c2.load_if_changed());
a.store(Arc::new(43));
assert_eq!(42, **c1.load_no_revalidate());
assert_eq!(43, **c1.load_if_changed().unwrap());

assert_eq!(43, **c1.load());
}

Expand Down