Skip to content

Add Iterator::single #55355

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/libcore/iter/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1875,6 +1875,55 @@ pub trait Iterator {
}).break_value()
}

/// Extracts the single remaining element out of the iterator.
///
/// [`next()`]: #method.next
/// [`by_ref()`]: #method.by_ref
/// [`Some(x)`]: ../../std/option/enum.Option.html#variant.Some
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// If [`next()`] will return [`Some(x)`] the first time, and then return
/// [`None`] the next time around, then `single()` will return `Some(x)`.
/// If there are no elements to extract or if there more than one,
/// then the iterator will will return `None`.
///
/// This method takes ownership of the iterator it is called on.
/// If you want to retain ownership, call [`by_ref()`] on the iterator
/// first before calling `single()`.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// #![feature(iterator_single)]
///
/// let zero: [u8; 0] = [];
/// let one: [u8; 1] = [42];
/// let two: [u8; 2] = [42, 24];
/// let three: [u8; 3] = [42, 24, 0];
///
/// assert_eq!(zero.iter().single(), None);
/// assert_eq!(one.iter().single(), Some(&42));
/// assert_eq!(two.iter().single(), None);
/// assert_eq!(three.iter().single(), None);
/// ```
///
/// # Invariants
///
/// If `count()` does not panic and returns `1`, then `single()` will
/// return `Some(element)`. Otherwise, `single()` will return `None`.
#[inline]
#[unstable(feature = "iterator_single", issue = "55354")]
fn single(mut self) -> Option<Self::Item> where Self: Sized {
if let x@Some(_) = self.next() {
if let None = self.next() {
return x
}
}
None
}

/// Searches for an element in an iterator, returning its index.
///
/// `position()` takes a closure that returns `true` or `false`. It applies
Expand Down