Skip to content
Merged
Show file tree
Hide file tree
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
28 changes: 22 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ pub struct ItemStats {
mod tests {
use std::{
hash::Hash,
panic::{catch_unwind, AssertUnwindSafe},
sync::{atomic::AtomicUsize, Arc},
time::Duration,
};
Expand Down Expand Up @@ -416,19 +417,34 @@ mod tests {
cache.insert(1, "1".to_string());
assert_eq!(cache.get(&1).unwrap(), "1");
assert_eq!(cache.weight(), 1);
let _old = cache.get_mut(&1).map(|mut v| {
assert_eq!(&*v, "1");
let old = std::mem::replace(&mut *v, "11".to_string());
assert_eq!(&*v, "11");
old
});
assert_eq!(cache.weight(), 2);
let _old = {
cache
.get_mut(&1)
.map(|mut v| std::mem::replace(&mut *v, "11".to_string()))
};
let _old = {
cache
.get_mut(&1)
.peek_mut(&1)
.map(|mut v| std::mem::replace(&mut *v, "".to_string()))
};
assert_eq!(cache.get(&1).unwrap(), "");
assert_eq!(cache.weight(), 0);
cache.validate(false);

let result = catch_unwind(AssertUnwindSafe(|| {
let mut value = cache
.get_mut_or_insert_with::<_, ()>(&1, || panic!("resident hit"))
.unwrap()
.unwrap();
value.push('1');
panic!("after mutating the resident value");
}));
assert!(result.is_err());
assert_eq!(cache.get(&1).unwrap(), "1");
assert_eq!(cache.weight(), 1);
cache.validate(false);
}

#[derive(Debug, Hash)]
Expand Down
41 changes: 16 additions & 25 deletions src/shard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,8 +702,10 @@ impl<
record_hit_mut!(self, resident);

let old_weight = self.weighter.weight(&resident.key, &resident.value);
let value = &raw mut resident.value;
Some(RefMut {
guard: WeightGuard {
value,
_guard: WeightGuard {
shard: self as *mut _,
idx,
old_weight,
Expand All @@ -725,8 +727,10 @@ impl<
pub fn peek_token_mut(&mut self, token: Token) -> Option<RefMut<'_, Key, Val, We, B, L, Id>> {
if let Some((Entry::Resident(resident), _)) = self.entries.get_mut(token) {
let old_weight = self.weighter.weight(&resident.key, &resident.value);
let value = &raw mut resident.value;
Some(RefMut {
guard: WeightGuard {
value,
_guard: WeightGuard {
shard: self as *mut _,
idx: token,
old_weight,
Expand Down Expand Up @@ -1530,8 +1534,8 @@ impl<Key, Val, We: Weighter<Key, Val>, B, L, Id: PlaceholderId<Val>> Drop
for WeightGuard<Key, Val, We, B, L, Id>
{
fn drop(&mut self) {
// SAFETY: shard pointer is valid — guard is created and dropped within
// entry_or_placeholder which holds &mut CacheShard.
// SAFETY: The caller keeps the slot resident and holds exclusive access
// to the shard until the weight guard drops.
unsafe {
let shard = &mut *self.shard;
let (entry, _) = shard.entries.get_unchecked(self.idx);
Expand All @@ -1549,36 +1553,23 @@ impl<Key, Val, We: Weighter<Key, Val>, B, L, Id: PlaceholderId<Val>> Drop
/// Structure wrapping a mutable reference to a cached item.
/// On drop, recomputes weight via the inner [`WeightGuard`].
pub struct RefMut<'cache, Key, Val, We: Weighter<Key, Val>, B, L, Id: PlaceholderId<Val>> {
guard: WeightGuard<Key, Val, We, B, L, Id>,
value: *mut Val,
_guard: WeightGuard<Key, Val, We, B, L, Id>,
_phantom: std::marker::PhantomData<&'cache mut CacheShard<Key, Val, We, B, L, Id>>,
}

impl<Key, Val, We: Weighter<Key, Val>, B, L, Id: PlaceholderId<Val>>
RefMut<'_, Key, Val, We, B, L, Id>
{
pub(crate) fn pair(&self) -> (&Key, &Val) {
// SAFETY: RefMut is only constructed from a valid &mut CacheShard with a
// Resident entry at idx, and we hold exclusive access via the lifetime.
unsafe {
let shard = &*self.guard.shard;
let (entry, _) = shard.entries.get_unchecked(self.guard.idx);
let Entry::Resident(Resident { key, value, .. }) = entry else {
core::hint::unreachable_unchecked()
};
(key, value)
}
pub(crate) fn value(&self) -> &Val {
// SAFETY: The shard borrow keeps the resident in place until the guard drops.
unsafe { &*self.value }
}

pub(crate) fn value_mut(&mut self) -> &mut Val {
// SAFETY: same as pair(), plus we have &mut self so exclusive access is guaranteed.
unsafe {
let shard = &mut *self.guard.shard;
let (entry, _) = shard.entries.get_mut_unchecked(self.guard.idx);
let Entry::Resident(Resident { value, .. }) = entry else {
core::hint::unreachable_unchecked()
};
value
}
// SAFETY: The slot stays live as in value(), and the mutable guard borrow
// gives exclusive access to the value.
unsafe { &mut *self.value }
}
}

Expand Down
36 changes: 22 additions & 14 deletions src/unsync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,19 @@ impl<Key: Eq + Hash, Val, We: Weighter<Key, Val>, B: BuildHasher, L: Lifecycle<K
Q: Hash + Equivalent<Key> + ToOwned<Owned = Key> + ?Sized,
{
let idx = match self.shard.get_or_placeholder(self.shard.hash(key), key) {
Ok((idx, _)) => idx,
Err((plh, _)) => {
let v = with()?;
let mut lcs = Default::default();
let replaced = self.shard.replace_placeholder(&mut lcs, &plh, false, v);
debug_assert!(replaced.is_ok(), "unsync replace_placeholder can't fail");
plh.idx
Ok((_, value)) => {
let value: *const Val = value;
// Safety: the returned reference is valid while the mutable cache borrow is held.
return Ok(Some(unsafe { &*value }));
}
Err((placeholder, _)) => {
let idx = placeholder.idx;
let guard = Guard {
cache: self,
placeholder: Some(placeholder),
};
guard.insert(with()?);
idx
}
};
Ok(self.shard.peek_token(idx))
Expand All @@ -285,12 +291,14 @@ impl<Key: Eq + Hash, Val, We: Weighter<Key, Val>, B: BuildHasher, L: Lifecycle<K
{
let idx = match self.shard.get_or_placeholder(self.shard.hash(key), key) {
Ok((idx, _)) => idx,
Err((plh, _)) => {
let v = with()?;
let mut lcs = Default::default();
let replaced = self.shard.replace_placeholder(&mut lcs, &plh, false, v);
debug_assert!(replaced.is_ok(), "unsync replace_placeholder can't fail");
plh.idx
Err((placeholder, _)) => {
let idx = placeholder.idx;
let guard = Guard {
cache: self,
placeholder: Some(placeholder),
};
guard.insert(with()?);
idx
}
};
Ok(self.shard.peek_token_mut(idx).map(RefMut))
Expand Down Expand Up @@ -496,7 +504,7 @@ impl<Key, Val, We: Weighter<Key, Val>, B, L> std::ops::Deref for RefMut<'_, Key,

#[inline]
fn deref(&self) -> &Self::Target {
self.0.pair().1
self.0.value()
}
}

Expand Down
89 changes: 89 additions & 0 deletions tests/loader_cleanup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use quick_cache::unsync::Cache;
use std::{
panic::{catch_unwind, AssertUnwindSafe},
sync::Arc,
};

#[test]
fn failed_ref_loader_releases_key() {
let mut cache = Cache::<Arc<str>, u64>::new(100);
let key: Arc<str> = Arc::from("failed-ref-load");
assert_eq!(
cache.get_or_insert_with(&key, || Err::<u64, _>("failed")),
Err("failed")
);
assert_eq!(cache.len(), 0);
assert_eq!(
Arc::strong_count(&key),
1,
"failed loader retains its owned key"
);
assert_eq!(
cache.get_or_insert_with(&key, || Ok::<_, ()>(42)),
Ok(Some(&42))
);
}

#[test]
fn failed_mut_loader_releases_key() {
let mut cache = Cache::<Arc<str>, u64>::new(100);
let key: Arc<str> = Arc::from("failed-mut-load");
assert!(cache
.get_mut_or_insert_with(&key, || Err::<u64, _>("failed"))
.is_err());
assert_eq!(cache.len(), 0);
assert_eq!(
Arc::strong_count(&key),
1,
"failed mutable loader retains its owned key"
);
assert_eq!(
cache
.get_mut_or_insert_with(&key, || Ok::<_, ()>(42))
.unwrap()
.map(|v| *v),
Some(42)
);
}

#[test]
fn panicking_ref_loader_releases_key() {
let mut cache = Cache::<Arc<str>, u64>::new(100);
let key: Arc<str> = Arc::from("panicking-ref-load");
let result = catch_unwind(AssertUnwindSafe(|| {
let _ = cache.get_or_insert_with(&key, || -> Result<u64, ()> { panic!("loader panic") });
}));
assert!(result.is_err());
assert_eq!(
Arc::strong_count(&key),
1,
"panicking loader retains its owned key"
);
assert_eq!(
cache.get_or_insert_with(&key, || Ok::<_, ()>(42)),
Ok(Some(&42))
);
}

#[test]
fn panicking_mut_loader_releases_key() {
let mut cache = Cache::<Arc<str>, u64>::new(100);
let key: Arc<str> = Arc::from("panicking-mut-load");
let result = catch_unwind(AssertUnwindSafe(|| {
let _ =
cache.get_mut_or_insert_with(&key, || -> Result<u64, ()> { panic!("loader panic") });
}));
assert!(result.is_err());
assert_eq!(
Arc::strong_count(&key),
1,
"panicking mutable loader retains its owned key"
);
assert_eq!(
cache
.get_mut_or_insert_with(&key, || Ok::<_, ()>(42))
.unwrap()
.map(|v| *v),
Some(42)
);
}
Loading