From cbe8f4a0d98a1e7629ed0db5063904fa4aa80608 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Mon, 16 Nov 2026 10:06:53 +0100 Subject: [PATCH 1/4] Release placeholder keys when unsync loaders fail --- src/unsync.rs | 26 +++++++----- tests/loader_cleanup.rs | 89 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 10 deletions(-) create mode 100644 tests/loader_cleanup.rs diff --git a/src/unsync.rs b/src/unsync.rs index 7e9a5c7..2cf2b08 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -278,11 +278,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 + let idx = plh.idx; + let guard = Guard { + cache: self, + placeholder: plh, + inserted: false, + }; + guard.insert(with()?); + idx } }; Ok(self.shard.peek_token(idx)) @@ -303,11 +306,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 + let idx = plh.idx; + let guard = Guard { + cache: self, + placeholder: plh, + inserted: false, + }; + guard.insert(with()?); + idx } }; Ok(self.shard.peek_token_mut(idx).map(RefMut)) 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) + ); +} From e334d8d3e2376307be666ab9090dd11e7c63cbda Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sun, 22 Nov 2026 11:37:33 +0100 Subject: [PATCH 2/4] Refactor unsync convenience loaders --- src/unsync.rs | 51 +++++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/src/unsync.rs b/src/unsync.rs index 2cf2b08..bc11cea 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -263,31 +263,42 @@ impl, B: BuildHasher, L: Lifecycle( + fn get_or_insert_token( &mut self, key: &Q, with: impl FnOnce() -> Result, - ) -> Result, E> + ) -> Result where Q: Hash + Equivalent + ToOwned + ?Sized, { - let idx = match self.shard.get_or_placeholder(self.shard.hash(key), key) { - Ok((idx, _)) => idx, - Err((plh, _)) => { - let idx = plh.idx; + match self.shard.get_or_placeholder(self.shard.hash(key), key) { + Ok((idx, _)) => Ok(idx), + Err((placeholder, _)) => { + let idx = placeholder.idx; let guard = Guard { cache: self, - placeholder: plh, + placeholder, inserted: false, }; guard.insert(with()?); - idx + Ok(idx) } - }; + } + } + + /// Gets or inserts an item in the cache with key `key`. + /// Returns a reference to the inserted `value` if it was admitted to the cache. + /// + /// See also `get_ref_or_guard`. + pub fn get_or_insert_with( + &mut self, + key: &Q, + with: impl FnOnce() -> Result, + ) -> Result, E> + where + Q: Hash + Equivalent + ToOwned + ?Sized, + { + let idx = self.get_or_insert_token(key, with)?; Ok(self.shard.peek_token(idx)) } @@ -303,19 +314,7 @@ 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 idx = plh.idx; - let guard = Guard { - cache: self, - placeholder: plh, - inserted: false, - }; - guard.insert(with()?); - idx - } - }; + let idx = self.get_or_insert_token(key, with)?; Ok(self.shard.peek_token_mut(idx).map(RefMut)) } From 62fcb34c19314ff192838bde221df8c963755902 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sun, 22 Nov 2026 12:11:34 +0100 Subject: [PATCH 3/4] Avoid redundant lookup on unsync loader hits --- src/unsync.rs | 49 +++++++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/src/unsync.rs b/src/unsync.rs index bc11cea..b99deca 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -263,16 +263,24 @@ impl, B: BuildHasher, L: Lifecycle( + /// Gets or inserts an item in the cache with key `key`. + /// Returns a reference to the inserted `value` if it was admitted to the cache. + /// + /// See also `get_ref_or_guard`. + pub fn get_or_insert_with( &mut self, key: &Q, with: impl FnOnce() -> Result, - ) -> Result + ) -> Result, E> where Q: Hash + Equivalent + ToOwned + ?Sized, { - match self.shard.get_or_placeholder(self.shard.hash(key), key) { - Ok((idx, _)) => Ok(idx), + let idx = match self.shard.get_or_placeholder(self.shard.hash(key), key) { + 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 { @@ -281,24 +289,9 @@ impl, B: BuildHasher, L: Lifecycle( - &mut self, - key: &Q, - with: impl FnOnce() -> Result, - ) -> Result, E> - where - Q: Hash + Equivalent + ToOwned + ?Sized, - { - let idx = self.get_or_insert_token(key, with)?; + }; Ok(self.shard.peek_token(idx)) } @@ -314,7 +307,19 @@ impl, B: BuildHasher, L: Lifecycle + ToOwned + ?Sized, { - let idx = self.get_or_insert_token(key, with)?; + let idx = match self.shard.get_or_placeholder(self.shard.hash(key), key) { + Ok((idx, _)) => idx, + Err((placeholder, _)) => { + let idx = placeholder.idx; + let guard = Guard { + cache: self, + placeholder, + inserted: false, + }; + guard.insert(with()?); + idx + } + }; Ok(self.shard.peek_token_mut(idx).map(RefMut)) } From 9e173dd302183f8bf3b0f803a598f3932716a9e6 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sun, 22 Nov 2026 12:47:31 +0100 Subject: [PATCH 4/4] Cache the value pointer in unsync RefMut Deref borrows the resident value through the cached pointer. The weight guard uses the slot token to recompute weight on drop. Exercise shared and mutable reborrows on a guard moved by value and check weight accounting when a live guard drops during unwind. --- src/lib.rs | 28 ++++++++++++++++++++++------ src/shard.rs | 41 ++++++++++++++++------------------------- src/unsync.rs | 2 +- 3 files changed, 39 insertions(+), 32 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 635b21a..2e83d23 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -321,6 +321,7 @@ pub struct ItemStats { mod tests { use std::{ hash::Hash, + panic::{catch_unwind, AssertUnwindSafe}, sync::{atomic::AtomicUsize, Arc}, time::Duration, }; @@ -389,19 +390,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 7b110a1..69b1dc8 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -619,8 +619,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, @@ -642,8 +644,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, @@ -1401,8 +1405,8 @@ impl, B, L, Plh: SharedPlaceholder> 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); @@ -1420,36 +1424,23 @@ impl, B, L, Plh: SharedPlaceholder> 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, Plh: SharedPlaceholder> { - guard: WeightGuard, + value: *mut Val, + _guard: WeightGuard, _phantom: std::marker::PhantomData<&'cache mut CacheShard>, } impl, B, L, Plh: SharedPlaceholder> RefMut<'_, Key, Val, We, B, L, Plh> { - 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 b99deca..921f5f9 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -526,7 +526,7 @@ impl, B, L> std::ops::Deref for RefMut<'_, Key, #[inline] fn deref(&self) -> &Self::Target { - self.0.pair().1 + self.0.value() } }