diff --git a/src/lib.rs b/src/lib.rs index 1c6811d..6dbbe93 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -348,6 +348,7 @@ pub struct ItemStats { mod tests { use std::{ hash::Hash, + panic::{catch_unwind, AssertUnwindSafe}, sync::{atomic::AtomicUsize, Arc}, time::Duration, }; @@ -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)] diff --git a/src/shard.rs b/src/shard.rs index c05e0aa..8327026 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -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, @@ -725,8 +727,10 @@ impl< pub fn peek_token_mut(&mut self, token: Token) -> Option> { 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, @@ -1530,8 +1534,8 @@ impl, B, L, Id: PlaceholderId> Drop for WeightGuard { 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); @@ -1549,36 +1553,23 @@ impl, B, L, Id: PlaceholderId> 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, B, L, Id: PlaceholderId> { - guard: WeightGuard, + value: *mut Val, + _guard: WeightGuard, _phantom: std::marker::PhantomData<&'cache mut CacheShard>, } impl, B, L, Id: PlaceholderId> 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 } } } diff --git a/src/unsync.rs b/src/unsync.rs index 12939cd..4cf3998 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -259,13 +259,19 @@ impl, B: BuildHasher, L: Lifecycle + ToOwned + ?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)) @@ -285,12 +291,14 @@ impl, B: BuildHasher, L: Lifecycle 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)) @@ -496,7 +504,7 @@ impl, B, L> std::ops::Deref for RefMut<'_, Key, #[inline] fn deref(&self) -> &Self::Target { - self.0.pair().1 + self.0.value() } } diff --git a/tests/loader_cleanup.rs b/tests/loader_cleanup.rs new file mode 100644 index 0000000..b1a53c7 --- /dev/null +++ b/tests/loader_cleanup.rs @@ -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::, u64>::new(100); + let key: Arc = Arc::from("failed-ref-load"); + assert_eq!( + cache.get_or_insert_with(&key, || Err::("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::, u64>::new(100); + let key: Arc = Arc::from("failed-mut-load"); + assert!(cache + .get_mut_or_insert_with(&key, || Err::("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::, u64>::new(100); + let key: Arc = Arc::from("panicking-ref-load"); + let result = catch_unwind(AssertUnwindSafe(|| { + let _ = cache.get_or_insert_with(&key, || -> Result { 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::, u64>::new(100); + let key: Arc = Arc::from("panicking-mut-load"); + let result = catch_unwind(AssertUnwindSafe(|| { + let _ = + cache.get_mut_or_insert_with(&key, || -> Result { 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) + ); +}