Rollup merge of #139533 - jogru0:130711, r=Mark-Simulacrum

add next_index to Enumerate

Proposal: https://github.com/rust-lang/libs-team/issues/435
Tracking Issue: #130711

This basically just reopens #130682 but squashed and with the new function and the feature gate renamed to `next_index.`

There are two questions I have already:
- Shouldn't we add test coverage for that? I'm happy to provide some, but I might need a pointer to where these test would be.
  - Maybe I could actually also add a doctest?
- For now, I just renamed the feature name in the unstable attribute to `next_index`, as well, so it matches the new name of the function. Is that okay? And can I just do that and use any string, or is there a sealed list of features defined somewhere where I also need to change the name?
This commit is contained in:
Chris Denton 2025-04-19 19:30:47 +00:00 committed by GitHub
commit 92adbd323a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 44 additions and 0 deletions

View file

@ -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")]

View file

@ -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);
}

View file

@ -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)]