Skip to content

Commit 2a4381d

Browse files
authored
Rollup merge of #89621 - digama0:patch-2, r=yaahc
doc: guarantee call order for sort_by_cached_key `slice::sort_by_cached_key` takes a caching function `f: impl FnMut(&T) -> K`, which means that the order that calls to the caching function are made is user-visible. This adds a clause to the documentation to promise the current behavior, which is that `f` is called on all elements of the slice from left to right, unless the slice has len < 2 in which case `f` is not called. For example, this can be used to ensure that the following code is a correct way to involve the index of the element in the sort key: ```rust let mut index = 0; slice.sort_by_cached_key(|x| (my_key(index, x), index += 1).0); ```
2 parents 5d2928f + 06b17a2 commit 2a4381d

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

library/alloc/src/slice.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,10 @@ impl<T> [T] {
375375

376376
/// Sorts the slice with a key extraction function.
377377
///
378-
/// During sorting, the key function is called only once per element.
378+
/// During sorting, the key function is called at most once per element, by using
379+
/// temporary storage to remember the results of key evaluation.
380+
/// The order of calls to the key function is unspecified and may change in future versions
381+
/// of the standard library.
379382
///
380383
/// This sort is stable (i.e., does not reorder equal elements) and *O*(*m* \* *n* + *n* \* log(*n*))
381384
/// worst-case, where the key function is *O*(*m*).

0 commit comments

Comments
 (0)