Skip to content

Commit

Permalink
Use fetch_update in find_first/last
Browse files Browse the repository at this point in the history
Its manual `compare_exchange_weak` loop was exactly what `fetch_update`
does internally, and we can also improve on the case where the current
best index was already equal.
  • Loading branch information
cuviper committed Jan 26, 2024
1 parent 926aed3 commit a4da641
Showing 1 changed file with 11 additions and 19 deletions.
30 changes: 11 additions & 19 deletions src/iter/find_first_last/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,25 +181,17 @@ impl<'p, P: 'p + Fn(&T) -> bool, T> Folder<T> 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
Expand Down

0 comments on commit a4da641

Please sign in to comment.