about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--library/core/src/iter/adapters/enumerate.rs33
-rw-r--r--library/coretests/tests/iter/adapters/enumerate.rs10
-rw-r--r--library/coretests/tests/lib.rs1
3 files changed, 44 insertions, 0 deletions
diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs
index bd093e279c3..f7b9f0b7a5e 100644
--- a/library/core/src/iter/adapters/enumerate.rs
+++ b/library/core/src/iter/adapters/enumerate.rs
@@ -23,6 +23,39 @@ impl<I> Enumerate<I> {
     pub(in crate::iter) fn new(iter: I) -> Enumerate<I> {
         Enumerate { iter, count: 0 }
     }
+
+    /// Retrieve the current position of the iterator.
+    ///
+    /// If the iterator has not advanced, the position returned will be 0.
+    ///
+    /// The position may also exceed the bounds of the iterator to allow for calculating
+    /// the displacement of the iterator from following calls to [`Iterator::next`].
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(next_index)]
+    ///
+    /// let arr = ['a', 'b'];
+    ///
+    /// let mut iter = arr.iter().enumerate();
+    ///
+    /// assert_eq!(iter.next_index(), 0);
+    /// assert_eq!(iter.next(), Some((0, &'a')));
+    ///
+    /// assert_eq!(iter.next_index(), 1);
+    /// assert_eq!(iter.next_index(), 1);
+    /// assert_eq!(iter.next(), Some((1, &'b')));
+    ///
+    /// assert_eq!(iter.next_index(), 2);
+    /// assert_eq!(iter.next(), None);
+    /// assert_eq!(iter.next_index(), 2);
+    /// ```
+    #[inline]
+    #[unstable(feature = "next_index", issue = "130711")]
+    pub fn next_index(&self) -> usize {
+        self.count
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/library/coretests/tests/iter/adapters/enumerate.rs b/library/coretests/tests/iter/adapters/enumerate.rs
index b57d51c077e..2294f856b58 100644
--- a/library/coretests/tests/iter/adapters/enumerate.rs
+++ b/library/coretests/tests/iter/adapters/enumerate.rs
@@ -120,3 +120,13 @@ fn test_double_ended_enumerate() {
     assert_eq!(it.next_back(), Some((2, 3)));
     assert_eq!(it.next(), None);
 }
+
+#[test]
+fn test_empty_iterator_enumerate_next_index() {
+    let mut it = empty::<i32>().enumerate();
+    assert_eq!(it.next_index(), 0);
+    assert_eq!(it.next_index(), 0);
+    assert_eq!(it.next(), None);
+    assert_eq!(it.next_index(), 0);
+    assert_eq!(it.next_index(), 0);
+}
diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs
index 1c43bfe0ed4..ac111575938 100644
--- a/library/coretests/tests/lib.rs
+++ b/library/coretests/tests/lib.rs
@@ -63,6 +63,7 @@
 #![feature(maybe_uninit_write_slice)]
 #![feature(min_specialization)]
 #![feature(never_type)]
+#![feature(next_index)]
 #![feature(numfmt)]
 #![feature(pattern)]
 #![feature(pointer_is_aligned_to)]