From 4161d9a2a5a1d3054948e1d3a189209a4fe01aa1 Mon Sep 17 00:00:00 2001 From: clostao <49268919+clostao@users.noreply.github.com> Date: Fri, 10 Jan 2025 15:53:42 +0100 Subject: [PATCH] Fix typo incrementing instead of decrementing (#595) * fix: typo incrementing instead of decrementing * Add tests for MostSeen decrement bug This bug requires a specific set of circumstances to trigger and become visible: 1. decrement a label that is non-zero but not first 2. repeat the decrement at least best_count()/2 times 3. increment that label 4. check the best count --------- Co-authored-by: teor --- backend/common/src/most_seen.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/common/src/most_seen.rs b/backend/common/src/most_seen.rs index 05e59872b..15f50ea69 100644 --- a/backend/common/src/most_seen.rs +++ b/backend/common/src/most_seen.rs @@ -124,7 +124,7 @@ impl MostSeen { // Item is in the map; not the best anyway. decrement count. if let Some(count) = self.others.get_mut(item) { - *count += 1; + *count = count.saturating_sub(1); } ChangeResult::NoChange } @@ -248,5 +248,11 @@ mod test { assert!(res.has_changed()); assert_eq!(a.best_count(), 2); assert_eq!(*a.best(), "First"); // First is now ahead + + a.remove(&"Third"); // 0, or 2 with bug #595 + a.remove(&"Third"); // 0, or 4 with bug #595 + a.insert(&"Third"); // 1, or 5 with bug #595 + assert_eq!(a.best_count(), 2); + assert_eq!(*a.best(), "First"); // First is still ahead } }