|
102 | 102 | //! |
103 | 103 | //! **Costs:** |
104 | 104 | //! - Weight function called on every insert/update |
105 | | -//! - Uses `Arc<V>` even for single-threaded store (needed for weight_fn) |
| 105 | +//! - Uses `Arc<V>` even for single-threaded store (cheap shared ownership for returned values) |
106 | 106 | //! - Slightly more state to track than simple HashMap stores |
107 | 107 | //! |
108 | 108 | //! ## When to Use |
@@ -299,7 +299,8 @@ impl StoreCounters { |
299 | 299 | /// |
300 | 300 | /// Enforces both a maximum number of entries and a maximum total weight. |
301 | 301 | /// Weight is computed via a caller-provided function and cached per entry. |
302 | | -/// Uses `Arc<V>` for values to enable weight function access. |
| 302 | +/// Uses `Arc<V>` for values to allow cheap shared ownership without requiring |
| 303 | +/// `V: Clone`. |
303 | 304 | /// |
304 | 305 | /// # Type Parameters |
305 | 306 | /// |
@@ -446,6 +447,8 @@ where |
446 | 447 | capacity_weight: usize, |
447 | 448 | weight_fn: F, |
448 | 449 | ) -> Result<Self, std::collections::TryReserveError> { |
| 450 | + // Build the map empty, then reserve fallibly so allocation errors are |
| 451 | + // returned instead of panicking in an infallible capacity constructor. |
449 | 452 | let mut map: FxHashMap<K, WeightEntry<V>> = FxHashMap::with_hasher(Default::default()); |
450 | 453 | map.try_reserve(capacity_entries)?; |
451 | 454 | Ok(Self { |
@@ -739,7 +742,7 @@ where |
739 | 742 | let base_total = self |
740 | 743 | .total_weight |
741 | 744 | .checked_sub(entry.weight) |
742 | | - .expect("WeightStore invariant violated: checked_sub failed after invariant check"); |
| 745 | + .expect("WeightStore invariant violated: total_weight must be >= entry.weight"); |
743 | 746 | let next_total = base_total.checked_add(new_weight).ok_or(StoreFull)?; |
744 | 747 | if next_total > self.capacity_weight { |
745 | 748 | return Err(StoreFull); |
@@ -806,7 +809,7 @@ where |
806 | 809 | self.total_weight = self |
807 | 810 | .total_weight |
808 | 811 | .checked_sub(entry.weight) |
809 | | - .expect("WeightStore invariant violated: checked_sub failed after invariant check"); |
| 812 | + .expect("WeightStore invariant violated: total_weight must be >= entry.weight"); |
810 | 813 | self.metrics.inc_remove(); |
811 | 814 | Some(entry.value) |
812 | 815 | } |
|
0 commit comments