diff --git a/src/iter/find_first_last/mod.rs b/src/iter/find_first_last/mod.rs index e5da8f0dd..a241373f9 100644 --- a/src/iter/find_first_last/mod.rs +++ b/src/iter/find_first_last/mod.rs @@ -181,25 +181,17 @@ impl<'p, P: 'p + Fn(&T) -> bool, T> Folder for FindFolder<'p, T, P> { }; if !found_best_in_range && (self.find_op)(&item) { - // Continuously try to set best_found until we succeed or we - // discover a better match was already found. - let mut current = self.best_found.load(Ordering::Relaxed); - loop { - if better_position(current, self.boundary, self.match_position) { - break; - } - match self.best_found.compare_exchange_weak( - current, - self.boundary, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => { - self.item = Some(item); - break; - } - Err(v) => current = v, - } + // Update the best found index if ours is better. + let update = + self.best_found + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| { + better_position(self.boundary, current, self.match_position) + .then_some(self.boundary) + }); + + // Save this item if our index was better or equal. + if update.is_ok() || update == Err(self.boundary) { + self.item = Some(item); } } self diff --git a/src/iter/par_bridge.rs b/src/iter/par_bridge.rs index 17bc15bf4..9927f4f6b 100644 --- a/src/iter/par_bridge.rs +++ b/src/iter/par_bridge.rs @@ -109,24 +109,11 @@ impl UnindexedProducer for &IterParallelProducer<'_, Iter type Item = Iter::Item; fn split(self) -> (Self, Option) { - let mut count = self.split_count.load(Ordering::SeqCst); - - loop { - // Check if the iterator is exhausted - if let Some(new_count) = count.checked_sub(1) { - match self.split_count.compare_exchange_weak( - count, - new_count, - Ordering::SeqCst, - Ordering::SeqCst, - ) { - Ok(_) => return (self, Some(self)), - Err(last_count) => count = last_count, - } - } else { - return (self, None); - } - } + // Check if the iterator is exhausted + let update = self + .split_count + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |c| c.checked_sub(1)); + (self, update.is_ok().then_some(self)) } fn fold_with(self, mut folder: F) -> F