Skip to content

Commit 3aed617

Browse files
Potential fixes for 2 code quality findings (#35)
* Apply suggested fix to src/store/weight.rs from Copilot Autofix * WeightStore invariant add to ensure total_weight is not less than entry.weight * saturating_sub used to ensure no overflow --------- Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
1 parent 1fafd5b commit 3aed617

1 file changed

Lines changed: 14 additions & 1 deletion

File tree

src/store/weight.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,16 @@ where
501501
pub fn try_insert(&mut self, key: K, value: Arc<V>) -> Result<Option<Arc<V>>, StoreFull> {
502502
let new_weight = self.compute_weight(value.as_ref());
503503
if let Some(entry) = self.map.get_mut(&key) {
504-
let next_total = self.total_weight - entry.weight + new_weight;
504+
debug_assert!(
505+
self.total_weight >= entry.weight,
506+
"WeightStore invariant violated: total_weight ({}) is less than entry.weight ({})",
507+
self.total_weight,
508+
entry.weight
509+
);
510+
let next_total = self
511+
.total_weight
512+
.saturating_sub(entry.weight)
513+
.saturating_add(new_weight);
505514
if next_total > self.capacity_weight {
506515
return Err(StoreFull);
507516
}
@@ -551,6 +560,10 @@ where
551560
/// ```
552561
pub fn remove(&mut self, key: &K) -> Option<Arc<V>> {
553562
let entry = self.map.remove(key)?;
563+
debug_assert!(
564+
self.total_weight >= entry.weight,
565+
"total_weight underflow in remove"
566+
);
554567
self.total_weight = self.total_weight.saturating_sub(entry.weight);
555568
self.metrics.inc_remove();
556569
Some(entry.value)

0 commit comments

Comments
 (0)