Skip to content

Commit c44e1d6

Browse files
authored
Rollup merge of rust-lang#135734 - nk9:extract_if-doc-equivalent, r=tgross35
Correct `extract_if` sample equivalent. Tracking issue: rust-lang#43244 Original PR: rust-lang#133265 The sample code marked as equivalent in the doc comment isn't currently equivalent. Given the same predicate and range, if your vector were `[1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6]`, then all of the 3s would be removed. `i` is only incremented when an element is dropped, but `range.end` is unchanged, so the items shift down. I got very confused when reading the docs and trying to square this sample code with the explanation of how the function works. Fortunately, the real `extract_if()` does not have this problem. I've added an `end` variable to align the behavior. I've also taken the opportunity to simplify the predicate, which now just matches odd numbers, and to pad out the vec of numbers to line up the zero-indexed range with the integers in the vec. r? the8472
2 parents 2958d89 + 52d806a commit c44e1d6

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

library/alloc/src/vec/mod.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -3666,21 +3666,27 @@ impl<T, A: Allocator> Vec<T, A> {
36663666
/// Using this method is equivalent to the following code:
36673667
///
36683668
/// ```
3669-
/// # use std::cmp::min;
3670-
/// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
3671-
/// # let mut vec = vec![1, 2, 3, 4, 5, 6];
3672-
/// # let range = 1..4;
3669+
/// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
3670+
/// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
3671+
/// # let mut vec2 = vec.clone();
3672+
/// # let range = 1..5;
36733673
/// let mut i = range.start;
3674-
/// while i < min(vec.len(), range.end) {
3674+
/// let end_items = vec.len() - range.end;
3675+
/// # let mut extracted = vec![];
3676+
///
3677+
/// while i < vec.len() - end_items {
36753678
/// if some_predicate(&mut vec[i]) {
36763679
/// let val = vec.remove(i);
3680+
/// # extracted.push(val);
36773681
/// // your code here
36783682
/// } else {
36793683
/// i += 1;
36803684
/// }
36813685
/// }
36823686
///
3683-
/// # assert_eq!(vec, vec![1, 4, 5]);
3687+
/// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
3688+
/// # assert_eq!(vec, vec2);
3689+
/// # assert_eq!(extracted, extracted2);
36843690
/// ```
36853691
///
36863692
/// But `extract_if` is easier to use. `extract_if` is also more efficient,

0 commit comments

Comments
 (0)