about summary refs log tree commit diff
path: root/src/liballoc/collections
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2019-05-12 06:24:10 +0000
committerbors <bors@rust-lang.org>2019-05-12 06:24:10 +0000
commit16e356ebdfa42b754c1497f1c58caacbe2f25d03 (patch)
treebad4da2fcfd6cda2059d84d8afbd8a97b4b7453d /src/liballoc/collections
parentd28e948b92d85b5b93f48075d010f799cf9642b6 (diff)
parent0545375ca6822b4b140cd853f368473d69b76227 (diff)
downloadrust-16e356ebdfa42b754c1497f1c58caacbe2f25d03.tar.gz
rust-16e356ebdfa42b754c1497f1c58caacbe2f25d03.zip
Auto merge of #60396 - cuviper:ordered-retain, r=scottmcm
Document the order of {Vec,VecDeque,String}::retain

It's natural for `retain` to work in order from beginning to end, but
this wasn't actually documented to be the case. If we actually promise
this, then the caller can do useful things like track the index of each
element being tested, as [discussed in the forum][1]. This is now
documented for `Vec`, `VecDeque`, and `String`.

[1]: https://users.rust-lang.org/t/vec-retain-by-index/27697

`HashMap` and `HashSet` also have `retain`, and the `hashbrown`
implementation does happen to use a plain `iter()` order too, but it's
not certain that this should always be the case for these types.

r? @scottmcm
Diffstat (limited to 'src/liballoc/collections')
-rw-r--r--src/liballoc/collections/vec_deque.rs18
1 files changed, 16 insertions, 2 deletions
diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs
index d65c24f7350..9a8d48083e6 100644
--- a/src/liballoc/collections/vec_deque.rs
+++ b/src/liballoc/collections/vec_deque.rs
@@ -1835,8 +1835,8 @@ impl<T> VecDeque<T> {
     /// Retains only the elements specified by the predicate.
     ///
     /// In other words, remove all elements `e` such that `f(&e)` returns false.
-    /// This method operates in place and preserves the order of the retained
-    /// elements.
+    /// This method operates in place, visiting each element exactly once in the
+    /// original order, and preserves the order of the retained elements.
     ///
     /// # Examples
     ///
@@ -1848,6 +1848,20 @@ impl<T> VecDeque<T> {
     /// buf.retain(|&x| x%2 == 0);
     /// assert_eq!(buf, [2, 4]);
     /// ```
+    ///
+    /// The exact order may be useful for tracking external state, like an index.
+    ///
+    /// ```
+    /// use std::collections::VecDeque;
+    ///
+    /// let mut buf = VecDeque::new();
+    /// buf.extend(1..6);
+    ///
+    /// let keep = [false, true, true, false, true];
+    /// let mut i = 0;
+    /// buf.retain(|_| (keep[i], i += 1).0);
+    /// assert_eq!(buf, [2, 3, 5]);
+    /// ```
     #[stable(feature = "vec_deque_retain", since = "1.4.0")]
     pub fn retain<F>(&mut self, mut f: F)
         where F: FnMut(&T) -> bool