Auto merge of #56932 - clarcharr:iter_refactor, r=Centril
Refactor core::iter module A while back, I refactored `core::ops` in #42523 because the module had become a giant mess and was difficult to modify. Now, I'm doing the same with the `core::iter` module. Like the `core::ops` refactor, things have been split up into multiple commits to make rebasing easier, and so that you can follow changes. Although the diffs are hard to decipher, the only actual code changes I've made in the first few commits are to modify exports and imports. I save all of the actual code refactoring, e.g. modifying what methods are called, for the end.
This commit is contained in:
commit
da6ab956e1
260
src/libcore/iter/adapters/chain.rs
Normal file
260
src/libcore/iter/adapters/chain.rs
Normal file
@ -0,0 +1,260 @@
|
||||
use ops::Try;
|
||||
use usize;
|
||||
use super::super::{Iterator, DoubleEndedIterator, FusedIterator, TrustedLen};
|
||||
|
||||
/// An iterator that strings two iterators together.
|
||||
///
|
||||
/// This `struct` is created by the [`chain`] method on [`Iterator`]. See its
|
||||
/// documentation for more.
|
||||
///
|
||||
/// [`chain`]: trait.Iterator.html#method.chain
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
#[derive(Clone, Debug)]
|
||||
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub struct Chain<A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
state: ChainState,
|
||||
}
|
||||
impl<A, B> Chain<A, B> {
|
||||
pub(in super::super) fn new(a: A, b: B) -> Chain<A, B> {
|
||||
Chain { a, b, state: ChainState::Both }
|
||||
}
|
||||
}
|
||||
|
||||
// The iterator protocol specifies that iteration ends with the return value
|
||||
// `None` from `.next()` (or `.next_back()`) and it is unspecified what
|
||||
// further calls return. The chain adaptor must account for this since it uses
|
||||
// two subiterators.
|
||||
//
|
||||
// It uses three states:
|
||||
//
|
||||
// - Both: `a` and `b` are remaining
|
||||
// - Front: `a` remaining
|
||||
// - Back: `b` remaining
|
||||
//
|
||||
// The fourth state (neither iterator is remaining) only occurs after Chain has
|
||||
// returned None once, so we don't need to store this state.
|
||||
#[derive(Clone, Debug)]
|
||||
enum ChainState {
|
||||
// both front and back iterator are remaining
|
||||
Both,
|
||||
// only front is remaining
|
||||
Front,
|
||||
// only back is remaining
|
||||
Back,
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<A, B> Iterator for Chain<A, B> where
|
||||
A: Iterator,
|
||||
B: Iterator<Item = A::Item>
|
||||
{
|
||||
type Item = A::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<A::Item> {
|
||||
match self.state {
|
||||
ChainState::Both => match self.a.next() {
|
||||
elt @ Some(..) => elt,
|
||||
None => {
|
||||
self.state = ChainState::Back;
|
||||
self.b.next()
|
||||
}
|
||||
},
|
||||
ChainState::Front => self.a.next(),
|
||||
ChainState::Back => self.b.next(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[rustc_inherit_overflow_checks]
|
||||
fn count(self) -> usize {
|
||||
match self.state {
|
||||
ChainState::Both => self.a.count() + self.b.count(),
|
||||
ChainState::Front => self.a.count(),
|
||||
ChainState::Back => self.b.count(),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_fold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
|
||||
Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
let mut accum = init;
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Front => {
|
||||
accum = self.a.try_fold(accum, &mut f)?;
|
||||
if let ChainState::Both = self.state {
|
||||
self.state = ChainState::Back;
|
||||
}
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
if let ChainState::Back = self.state {
|
||||
accum = self.b.try_fold(accum, &mut f)?;
|
||||
}
|
||||
Try::from_ok(accum)
|
||||
}
|
||||
|
||||
fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
|
||||
where F: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
let mut accum = init;
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Front => {
|
||||
accum = self.a.fold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Back => {
|
||||
accum = self.b.fold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
accum
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, mut n: usize) -> Option<A::Item> {
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Front => {
|
||||
for x in self.a.by_ref() {
|
||||
if n == 0 {
|
||||
return Some(x)
|
||||
}
|
||||
n -= 1;
|
||||
}
|
||||
if let ChainState::Both = self.state {
|
||||
self.state = ChainState::Back;
|
||||
}
|
||||
}
|
||||
ChainState::Back => {}
|
||||
}
|
||||
if let ChainState::Back = self.state {
|
||||
self.b.nth(n)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
|
||||
P: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
match self.state {
|
||||
ChainState::Both => match self.a.find(&mut predicate) {
|
||||
None => {
|
||||
self.state = ChainState::Back;
|
||||
self.b.find(predicate)
|
||||
}
|
||||
v => v
|
||||
},
|
||||
ChainState::Front => self.a.find(predicate),
|
||||
ChainState::Back => self.b.find(predicate),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn last(self) -> Option<A::Item> {
|
||||
match self.state {
|
||||
ChainState::Both => {
|
||||
// Must exhaust a before b.
|
||||
let a_last = self.a.last();
|
||||
let b_last = self.b.last();
|
||||
b_last.or(a_last)
|
||||
},
|
||||
ChainState::Front => self.a.last(),
|
||||
ChainState::Back => self.b.last()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let (a_lower, a_upper) = self.a.size_hint();
|
||||
let (b_lower, b_upper) = self.b.size_hint();
|
||||
|
||||
let lower = a_lower.saturating_add(b_lower);
|
||||
|
||||
let upper = match (a_upper, b_upper) {
|
||||
(Some(x), Some(y)) => x.checked_add(y),
|
||||
_ => None
|
||||
};
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<A, B> DoubleEndedIterator for Chain<A, B> where
|
||||
A: DoubleEndedIterator,
|
||||
B: DoubleEndedIterator<Item=A::Item>,
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<A::Item> {
|
||||
match self.state {
|
||||
ChainState::Both => match self.b.next_back() {
|
||||
elt @ Some(..) => elt,
|
||||
None => {
|
||||
self.state = ChainState::Front;
|
||||
self.a.next_back()
|
||||
}
|
||||
},
|
||||
ChainState::Front => self.a.next_back(),
|
||||
ChainState::Back => self.b.next_back(),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_rfold<Acc, F, R>(&mut self, init: Acc, mut f: F) -> R where
|
||||
Self: Sized, F: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
let mut accum = init;
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Back => {
|
||||
accum = self.b.try_rfold(accum, &mut f)?;
|
||||
if let ChainState::Both = self.state {
|
||||
self.state = ChainState::Front;
|
||||
}
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
if let ChainState::Front = self.state {
|
||||
accum = self.a.try_rfold(accum, &mut f)?;
|
||||
}
|
||||
Try::from_ok(accum)
|
||||
}
|
||||
|
||||
fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc
|
||||
where F: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
let mut accum = init;
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Back => {
|
||||
accum = self.b.rfold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Front => {
|
||||
accum = self.a.rfold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
accum
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Note: *both* must be fused to handle double-ended iterators.
|
||||
#[stable(feature = "fused", since = "1.26.0")]
|
||||
impl<A, B> FusedIterator for Chain<A, B>
|
||||
where A: FusedIterator,
|
||||
B: FusedIterator<Item=A::Item>,
|
||||
{}
|
||||
|
||||
#[unstable(feature = "trusted_len", issue = "37572")]
|
||||
unsafe impl<A, B> TrustedLen for Chain<A, B>
|
||||
where A: TrustedLen, B: TrustedLen<Item=A::Item>,
|
||||
{}
|
||||
|
330
src/libcore/iter/adapters/flatten.rs
Normal file
330
src/libcore/iter/adapters/flatten.rs
Normal file
@ -0,0 +1,330 @@
|
||||
use fmt;
|
||||
use ops::Try;
|
||||
use super::super::{Iterator, DoubleEndedIterator, FusedIterator};
|
||||
use super::Map;
|
||||
|
||||
/// An iterator that maps each element to an iterator, and yields the elements
|
||||
/// of the produced iterators.
|
||||
///
|
||||
/// This `struct` is created by the [`flat_map`] method on [`Iterator`]. See its
|
||||
/// documentation for more.
|
||||
///
|
||||
/// [`flat_map`]: trait.Iterator.html#method.flat_map
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub struct FlatMap<I, U: IntoIterator, F> {
|
||||
inner: FlattenCompat<Map<I, F>, <U as IntoIterator>::IntoIter>
|
||||
}
|
||||
impl<I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U> FlatMap<I, U, F> {
|
||||
pub(in super::super) fn new(iter: I, f: F) -> FlatMap<I, U, F> {
|
||||
FlatMap { inner: FlattenCompat::new(iter.map(f)) }
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<I: Clone, U: Clone + IntoIterator, F: Clone> Clone for FlatMap<I, U, F>
|
||||
where <U as IntoIterator>::IntoIter: Clone
|
||||
{
|
||||
fn clone(&self) -> Self { FlatMap { inner: self.inner.clone() } }
|
||||
}
|
||||
|
||||
#[stable(feature = "core_impl_debug", since = "1.9.0")]
|
||||
impl<I: fmt::Debug, U: IntoIterator, F> fmt::Debug for FlatMap<I, U, F>
|
||||
where U::IntoIter: fmt::Debug
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_struct("FlatMap").field("inner", &self.inner).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<I: Iterator, U: IntoIterator, F> Iterator for FlatMap<I, U, F>
|
||||
where F: FnMut(I::Item) -> U,
|
||||
{
|
||||
type Item = U::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<U::Item> { self.inner.next() }
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
|
||||
|
||||
#[inline]
|
||||
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
self.inner.try_fold(init, fold)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.inner.fold(init, fold)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<I: DoubleEndedIterator, U, F> DoubleEndedIterator for FlatMap<I, U, F>
|
||||
where F: FnMut(I::Item) -> U,
|
||||
U: IntoIterator,
|
||||
U::IntoIter: DoubleEndedIterator
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<U::Item> { self.inner.next_back() }
|
||||
|
||||
#[inline]
|
||||
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
self.inner.try_rfold(init, fold)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.inner.rfold(init, fold)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "fused", since = "1.26.0")]
|
||||
impl<I, U, F> FusedIterator for FlatMap<I, U, F>
|
||||
where I: FusedIterator, U: IntoIterator, F: FnMut(I::Item) -> U {}
|
||||
|
||||
/// An iterator that flattens one level of nesting in an iterator of things
|
||||
/// that can be turned into iterators.
|
||||
///
|
||||
/// This `struct` is created by the [`flatten`] method on [`Iterator`]. See its
|
||||
/// documentation for more.
|
||||
///
|
||||
/// [`flatten`]: trait.Iterator.html#method.flatten
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
pub struct Flatten<I: Iterator>
|
||||
where I::Item: IntoIterator {
|
||||
inner: FlattenCompat<I, <I::Item as IntoIterator>::IntoIter>,
|
||||
}
|
||||
impl<I: Iterator> Flatten<I>
|
||||
where I::Item: IntoIterator {
|
||||
pub(in super::super) fn new(iter: I) -> Flatten<I> {
|
||||
Flatten { inner: FlattenCompat::new(iter) }
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
impl<I, U> fmt::Debug for Flatten<I>
|
||||
where I: Iterator + fmt::Debug, U: Iterator + fmt::Debug,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_struct("Flatten").field("inner", &self.inner).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
impl<I, U> Clone for Flatten<I>
|
||||
where I: Iterator + Clone, U: Iterator + Clone,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>,
|
||||
{
|
||||
fn clone(&self) -> Self { Flatten { inner: self.inner.clone() } }
|
||||
}
|
||||
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
impl<I, U> Iterator for Flatten<I>
|
||||
where I: Iterator, U: Iterator,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>
|
||||
{
|
||||
type Item = U::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<U::Item> { self.inner.next() }
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
|
||||
|
||||
#[inline]
|
||||
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
self.inner.try_fold(init, fold)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.inner.fold(init, fold)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
impl<I, U> DoubleEndedIterator for Flatten<I>
|
||||
where I: DoubleEndedIterator, U: DoubleEndedIterator,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<U::Item> { self.inner.next_back() }
|
||||
|
||||
#[inline]
|
||||
fn try_rfold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
self.inner.try_rfold(init, fold)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.inner.rfold(init, fold)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
impl<I, U> FusedIterator for Flatten<I>
|
||||
where I: FusedIterator, U: Iterator,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item> {}
|
||||
|
||||
/// Real logic of both `Flatten` and `FlatMap` which simply delegate to
|
||||
/// this type.
|
||||
#[derive(Clone, Debug)]
|
||||
struct FlattenCompat<I, U> {
|
||||
iter: I,
|
||||
frontiter: Option<U>,
|
||||
backiter: Option<U>,
|
||||
}
|
||||
impl<I, U> FlattenCompat<I, U> {
|
||||
/// Adapts an iterator by flattening it, for use in `flatten()` and `flat_map()`.
|
||||
fn new(iter: I) -> FlattenCompat<I, U> {
|
||||
FlattenCompat { iter, frontiter: None, backiter: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, U> Iterator for FlattenCompat<I, U>
|
||||
where I: Iterator, U: Iterator,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>
|
||||
{
|
||||
type Item = U::Item;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<U::Item> {
|
||||
loop {
|
||||
if let Some(ref mut inner) = self.frontiter {
|
||||
if let elt@Some(_) = inner.next() { return elt }
|
||||
}
|
||||
match self.iter.next() {
|
||||
None => return self.backiter.as_mut().and_then(|it| it.next()),
|
||||
Some(inner) => self.frontiter = Some(inner.into_iter()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
|
||||
let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
|
||||
let lo = flo.saturating_add(blo);
|
||||
match (self.iter.size_hint(), fhi, bhi) {
|
||||
((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
|
||||
_ => (lo, None)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_fold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
if let Some(ref mut front) = self.frontiter {
|
||||
init = front.try_fold(init, &mut fold)?;
|
||||
}
|
||||
self.frontiter = None;
|
||||
|
||||
{
|
||||
let frontiter = &mut self.frontiter;
|
||||
init = self.iter.try_fold(init, |acc, x| {
|
||||
let mut mid = x.into_iter();
|
||||
let r = mid.try_fold(acc, &mut fold);
|
||||
*frontiter = Some(mid);
|
||||
r
|
||||
})?;
|
||||
}
|
||||
self.frontiter = None;
|
||||
|
||||
if let Some(ref mut back) = self.backiter {
|
||||
init = back.try_fold(init, &mut fold)?;
|
||||
}
|
||||
self.backiter = None;
|
||||
|
||||
Try::from_ok(init)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.frontiter.into_iter()
|
||||
.chain(self.iter.map(IntoIterator::into_iter))
|
||||
.chain(self.backiter)
|
||||
.fold(init, |acc, iter| iter.fold(acc, &mut fold))
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, U> DoubleEndedIterator for FlattenCompat<I, U>
|
||||
where I: DoubleEndedIterator, U: DoubleEndedIterator,
|
||||
I::Item: IntoIterator<IntoIter = U, Item = U::Item>
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<U::Item> {
|
||||
loop {
|
||||
if let Some(ref mut inner) = self.backiter {
|
||||
if let elt@Some(_) = inner.next_back() { return elt }
|
||||
}
|
||||
match self.iter.next_back() {
|
||||
None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
|
||||
next => self.backiter = next.map(IntoIterator::into_iter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_rfold<Acc, Fold, R>(&mut self, mut init: Acc, mut fold: Fold) -> R where
|
||||
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
|
||||
{
|
||||
if let Some(ref mut back) = self.backiter {
|
||||
init = back.try_rfold(init, &mut fold)?;
|
||||
}
|
||||
self.backiter = None;
|
||||
|
||||
{
|
||||
let backiter = &mut self.backiter;
|
||||
init = self.iter.try_rfold(init, |acc, x| {
|
||||
let mut mid = x.into_iter();
|
||||
let r = mid.try_rfold(acc, &mut fold);
|
||||
*backiter = Some(mid);
|
||||
r
|
||||
})?;
|
||||
}
|
||||
self.backiter = None;
|
||||
|
||||
if let Some(ref mut front) = self.frontiter {
|
||||
init = front.try_rfold(init, &mut fold)?;
|
||||
}
|
||||
self.frontiter = None;
|
||||
|
||||
Try::from_ok(init)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
|
||||
where Fold: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
self.frontiter.into_iter()
|
||||
.chain(self.iter.map(IntoIterator::into_iter))
|
||||
.chain(self.backiter)
|
||||
.rfold(init, |acc, iter| iter.rfold(acc, &mut fold))
|
||||
}
|
||||
}
|
||||
|
2044
src/libcore/iter/adapters/mod.rs
Normal file
2044
src/libcore/iter/adapters/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
282
src/libcore/iter/adapters/zip.rs
Normal file
282
src/libcore/iter/adapters/zip.rs
Normal file
@ -0,0 +1,282 @@
|
||||
use cmp;
|
||||
use super::super::{Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, TrustedLen};
|
||||
|
||||
/// An iterator that iterates two other iterators simultaneously.
|
||||
///
|
||||
/// This `struct` is created by the [`zip`] method on [`Iterator`]. See its
|
||||
/// documentation for more.
|
||||
///
|
||||
/// [`zip`]: trait.Iterator.html#method.zip
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
#[derive(Clone, Debug)]
|
||||
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub struct Zip<A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
// index and len are only used by the specialized version of zip
|
||||
index: usize,
|
||||
len: usize,
|
||||
}
|
||||
impl<A: Iterator, B: Iterator> Zip<A, B> {
|
||||
pub(in super::super) fn new(a: A, b: B) -> Zip<A, B> {
|
||||
ZipImpl::new(a, b)
|
||||
}
|
||||
fn super_nth(&mut self, mut n: usize) -> Option<(A::Item, B::Item)> {
|
||||
while let Some(x) = Iterator::next(self) {
|
||||
if n == 0 { return Some(x) }
|
||||
n -= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<A, B> Iterator for Zip<A, B> where A: Iterator, B: Iterator
|
||||
{
|
||||
type Item = (A::Item, B::Item);
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
ZipImpl::next(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
ZipImpl::size_hint(self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
ZipImpl::nth(self, n)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<A, B> DoubleEndedIterator for Zip<A, B> where
|
||||
A: DoubleEndedIterator + ExactSizeIterator,
|
||||
B: DoubleEndedIterator + ExactSizeIterator,
|
||||
{
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<(A::Item, B::Item)> {
|
||||
ZipImpl::next_back(self)
|
||||
}
|
||||
}
|
||||
|
||||
// Zip specialization trait
|
||||
#[doc(hidden)]
|
||||
trait ZipImpl<A, B> {
|
||||
type Item;
|
||||
fn new(a: A, b: B) -> Self;
|
||||
fn next(&mut self) -> Option<Self::Item>;
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item>;
|
||||
fn next_back(&mut self) -> Option<Self::Item>
|
||||
where A: DoubleEndedIterator + ExactSizeIterator,
|
||||
B: DoubleEndedIterator + ExactSizeIterator;
|
||||
}
|
||||
|
||||
// General Zip impl
|
||||
#[doc(hidden)]
|
||||
impl<A, B> ZipImpl<A, B> for Zip<A, B>
|
||||
where A: Iterator, B: Iterator
|
||||
{
|
||||
type Item = (A::Item, B::Item);
|
||||
default fn new(a: A, b: B) -> Self {
|
||||
Zip {
|
||||
a,
|
||||
b,
|
||||
index: 0, // unused
|
||||
len: 0, // unused
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
default fn next(&mut self) -> Option<(A::Item, B::Item)> {
|
||||
self.a.next().and_then(|x| {
|
||||
self.b.next().and_then(|y| {
|
||||
Some((x, y))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
default fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
self.super_nth(n)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
default fn next_back(&mut self) -> Option<(A::Item, B::Item)>
|
||||
where A: DoubleEndedIterator + ExactSizeIterator,
|
||||
B: DoubleEndedIterator + ExactSizeIterator
|
||||
{
|
||||
let a_sz = self.a.len();
|
||||
let b_sz = self.b.len();
|
||||
if a_sz != b_sz {
|
||||
// Adjust a, b to equal length
|
||||
if a_sz > b_sz {
|
||||
for _ in 0..a_sz - b_sz { self.a.next_back(); }
|
||||
} else {
|
||||
for _ in 0..b_sz - a_sz { self.b.next_back(); }
|
||||
}
|
||||
}
|
||||
match (self.a.next_back(), self.b.next_back()) {
|
||||
(Some(x), Some(y)) => Some((x, y)),
|
||||
(None, None) => None,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
default fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let (a_lower, a_upper) = self.a.size_hint();
|
||||
let (b_lower, b_upper) = self.b.size_hint();
|
||||
|
||||
let lower = cmp::min(a_lower, b_lower);
|
||||
|
||||
let upper = match (a_upper, b_upper) {
|
||||
(Some(x), Some(y)) => Some(cmp::min(x,y)),
|
||||
(Some(x), None) => Some(x),
|
||||
(None, Some(y)) => Some(y),
|
||||
(None, None) => None
|
||||
};
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
impl<A, B> ZipImpl<A, B> for Zip<A, B>
|
||||
where A: TrustedRandomAccess, B: TrustedRandomAccess
|
||||
{
|
||||
fn new(a: A, b: B) -> Self {
|
||||
let len = cmp::min(a.len(), b.len());
|
||||
Zip {
|
||||
a,
|
||||
b,
|
||||
index: 0,
|
||||
len,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<(A::Item, B::Item)> {
|
||||
if self.index < self.len {
|
||||
let i = self.index;
|
||||
self.index += 1;
|
||||
unsafe {
|
||||
Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
|
||||
}
|
||||
} else if A::may_have_side_effect() && self.index < self.a.len() {
|
||||
// match the base implementation's potential side effects
|
||||
unsafe {
|
||||
self.a.get_unchecked(self.index);
|
||||
}
|
||||
self.index += 1;
|
||||
None
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.len - self.index;
|
||||
(len, Some(len))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
let delta = cmp::min(n, self.len - self.index);
|
||||
let end = self.index + delta;
|
||||
while self.index < end {
|
||||
let i = self.index;
|
||||
self.index += 1;
|
||||
if A::may_have_side_effect() {
|
||||
unsafe { self.a.get_unchecked(i); }
|
||||
}
|
||||
if B::may_have_side_effect() {
|
||||
unsafe { self.b.get_unchecked(i); }
|
||||
}
|
||||
}
|
||||
|
||||
self.super_nth(n - delta)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn next_back(&mut self) -> Option<(A::Item, B::Item)>
|
||||
where A: DoubleEndedIterator + ExactSizeIterator,
|
||||
B: DoubleEndedIterator + ExactSizeIterator
|
||||
{
|
||||
// Adjust a, b to equal length
|
||||
if A::may_have_side_effect() {
|
||||
let sz = self.a.len();
|
||||
if sz > self.len {
|
||||
for _ in 0..sz - cmp::max(self.len, self.index) {
|
||||
self.a.next_back();
|
||||
}
|
||||
}
|
||||
}
|
||||
if B::may_have_side_effect() {
|
||||
let sz = self.b.len();
|
||||
if sz > self.len {
|
||||
for _ in 0..sz - self.len {
|
||||
self.b.next_back();
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.index < self.len {
|
||||
self.len -= 1;
|
||||
let i = self.len;
|
||||
unsafe {
|
||||
Some((self.a.get_unchecked(i), self.b.get_unchecked(i)))
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<A, B> ExactSizeIterator for Zip<A, B>
|
||||
where A: ExactSizeIterator, B: ExactSizeIterator {}
|
||||
|
||||
#[doc(hidden)]
|
||||
unsafe impl<A, B> TrustedRandomAccess for Zip<A, B>
|
||||
where A: TrustedRandomAccess,
|
||||
B: TrustedRandomAccess,
|
||||
{
|
||||
unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) {
|
||||
(self.a.get_unchecked(i), self.b.get_unchecked(i))
|
||||
}
|
||||
|
||||
fn may_have_side_effect() -> bool {
|
||||
A::may_have_side_effect() || B::may_have_side_effect()
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "fused", since = "1.26.0")]
|
||||
impl<A, B> FusedIterator for Zip<A, B>
|
||||
where A: FusedIterator, B: FusedIterator, {}
|
||||
|
||||
#[unstable(feature = "trusted_len", issue = "37572")]
|
||||
unsafe impl<A, B> TrustedLen for Zip<A, B>
|
||||
where A: TrustedLen, B: TrustedLen,
|
||||
{}
|
||||
|
||||
/// An iterator whose items are random-accessible efficiently
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The iterator's .len() and size_hint() must be exact.
|
||||
/// `.len()` must be cheap to call.
|
||||
///
|
||||
/// .get_unchecked() must return distinct mutable references for distinct
|
||||
/// indices (if applicable), and must return a valid reference if index is in
|
||||
/// 0..self.len().
|
||||
pub(crate) unsafe trait TrustedRandomAccess : ExactSizeIterator {
|
||||
unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item;
|
||||
/// Returns `true` if getting an iterator element may have
|
||||
/// side effects. Remember to take inner iterators into account.
|
||||
fn may_have_side_effect() -> bool;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
225
src/libcore/iter/traits/accum.rs
Normal file
225
src/libcore/iter/traits/accum.rs
Normal file
@ -0,0 +1,225 @@
|
||||
use ops::{Mul, Add};
|
||||
use num::Wrapping;
|
||||
|
||||
/// Trait to represent types that can be created by summing up an iterator.
|
||||
///
|
||||
/// This trait is used to implement the [`sum`] method on iterators. Types which
|
||||
/// implement the trait can be generated by the [`sum`] method. Like
|
||||
/// [`FromIterator`] this trait should rarely be called directly and instead
|
||||
/// interacted with through [`Iterator::sum`].
|
||||
///
|
||||
/// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum
|
||||
/// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
|
||||
/// [`Iterator::sum`]: ../../std/iter/trait.Iterator.html#method.sum
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
pub trait Sum<A = Self>: Sized {
|
||||
/// Method which takes an iterator and generates `Self` from the elements by
|
||||
/// "summing up" the items.
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
fn sum<I: Iterator<Item=A>>(iter: I) -> Self;
|
||||
}
|
||||
|
||||
/// Trait to represent types that can be created by multiplying elements of an
|
||||
/// iterator.
|
||||
///
|
||||
/// This trait is used to implement the [`product`] method on iterators. Types
|
||||
/// which implement the trait can be generated by the [`product`] method. Like
|
||||
/// [`FromIterator`] this trait should rarely be called directly and instead
|
||||
/// interacted with through [`Iterator::product`].
|
||||
///
|
||||
/// [`product`]: ../../std/iter/trait.Product.html#tymethod.product
|
||||
/// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
|
||||
/// [`Iterator::product`]: ../../std/iter/trait.Iterator.html#method.product
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
pub trait Product<A = Self>: Sized {
|
||||
/// Method which takes an iterator and generates `Self` from the elements by
|
||||
/// multiplying the items.
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
fn product<I: Iterator<Item=A>>(iter: I) -> Self;
|
||||
}
|
||||
|
||||
// N.B., explicitly use Add and Mul here to inherit overflow checks
|
||||
macro_rules! integer_sum_product {
|
||||
(@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
|
||||
#[$attr]
|
||||
impl Sum for $a {
|
||||
fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
|
||||
iter.fold($zero, Add::add)
|
||||
}
|
||||
}
|
||||
|
||||
#[$attr]
|
||||
impl Product for $a {
|
||||
fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
|
||||
iter.fold($one, Mul::mul)
|
||||
}
|
||||
}
|
||||
|
||||
#[$attr]
|
||||
impl<'a> Sum<&'a $a> for $a {
|
||||
fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
|
||||
iter.fold($zero, Add::add)
|
||||
}
|
||||
}
|
||||
|
||||
#[$attr]
|
||||
impl<'a> Product<&'a $a> for $a {
|
||||
fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
|
||||
iter.fold($one, Mul::mul)
|
||||
}
|
||||
}
|
||||
)*);
|
||||
($($a:ty)*) => (
|
||||
integer_sum_product!(@impls 0, 1,
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")],
|
||||
$($a)+);
|
||||
integer_sum_product!(@impls Wrapping(0), Wrapping(1),
|
||||
#[stable(feature = "wrapping_iter_arith", since = "1.14.0")],
|
||||
$(Wrapping<$a>)+);
|
||||
);
|
||||
}
|
||||
|
||||
macro_rules! float_sum_product {
|
||||
($($a:ident)*) => ($(
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
impl Sum for $a {
|
||||
fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
|
||||
iter.fold(0.0, |a, b| a + b)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
impl Product for $a {
|
||||
fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
|
||||
iter.fold(1.0, |a, b| a * b)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
impl<'a> Sum<&'a $a> for $a {
|
||||
fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
|
||||
iter.fold(0.0, |a, b| a + *b)
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iter_arith_traits", since = "1.12.0")]
|
||||
impl<'a> Product<&'a $a> for $a {
|
||||
fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
|
||||
iter.fold(1.0, |a, b| a * *b)
|
||||
}
|
||||
}
|
||||
)*)
|
||||
}
|
||||
|
||||
integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
|
||||
float_sum_product! { f32 f64 }
|
||||
|
||||
/// An iterator adapter that produces output as long as the underlying
|
||||
/// iterator produces `Result::Ok` values.
|
||||
///
|
||||
/// If an error is encountered, the iterator stops and the error is
|
||||
/// stored. The error may be recovered later via `reconstruct`.
|
||||
struct ResultShunt<I, E> {
|
||||
iter: I,
|
||||
error: Option<E>,
|
||||
}
|
||||
|
||||
impl<I, T, E> ResultShunt<I, E>
|
||||
where I: Iterator<Item = Result<T, E>>
|
||||
{
|
||||
/// Process the given iterator as if it yielded a `T` instead of a
|
||||
/// `Result<T, _>`. Any errors will stop the inner iterator and
|
||||
/// the overall result will be an error.
|
||||
pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
|
||||
where F: FnMut(&mut Self) -> U
|
||||
{
|
||||
let mut shunt = ResultShunt::new(iter);
|
||||
let value = f(shunt.by_ref());
|
||||
shunt.reconstruct(value)
|
||||
}
|
||||
|
||||
fn new(iter: I) -> Self {
|
||||
ResultShunt {
|
||||
iter,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the adapter and rebuild a `Result` value. This should
|
||||
/// *always* be called, otherwise any potential error would be
|
||||
/// lost.
|
||||
fn reconstruct<U>(self, val: U) -> Result<U, E> {
|
||||
match self.error {
|
||||
None => Ok(val),
|
||||
Some(e) => Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, T, E> Iterator for ResultShunt<I, E>
|
||||
where I: Iterator<Item = Result<T, E>>
|
||||
{
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.iter.next() {
|
||||
Some(Ok(v)) => Some(v),
|
||||
Some(Err(e)) => {
|
||||
self.error = Some(e);
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
if self.error.is_some() {
|
||||
(0, Some(0))
|
||||
} else {
|
||||
let (_, upper) = self.iter.size_hint();
|
||||
(0, upper)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iter_arith_traits_result", since="1.16.0")]
|
||||
impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
|
||||
where T: Sum<U>,
|
||||
{
|
||||
/// Takes each element in the `Iterator`: if it is an `Err`, no further
|
||||
/// elements are taken, and the `Err` is returned. Should no `Err` occur,
|
||||
/// the sum of all elements is returned.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// This sums up every integer in a vector, rejecting the sum if a negative
|
||||
/// element is encountered:
|
||||
///
|
||||
/// ```
|
||||
/// let v = vec![1, 2];
|
||||
/// let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
|
||||
/// if x < 0 { Err("Negative element found") }
|
||||
/// else { Ok(x) }
|
||||
/// ).sum();
|
||||
/// assert_eq!(res, Ok(3));
|
||||
/// ```
|
||||
fn sum<I>(iter: I) -> Result<T, E>
|
||||
where I: Iterator<Item = Result<U, E>>,
|
||||
{
|
||||
ResultShunt::process(iter, |i| i.sum())
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "iter_arith_traits_result", since="1.16.0")]
|
||||
impl<T, U, E> Product<Result<U, E>> for Result<T, E>
|
||||
where T: Product<U>,
|
||||
{
|
||||
/// Takes each element in the `Iterator`: if it is an `Err`, no further
|
||||
/// elements are taken, and the `Err` is returned. Should no `Err` occur,
|
||||
/// the product of all elements is returned.
|
||||
fn product<I>(iter: I) -> Result<T, E>
|
||||
where I: Iterator<Item = Result<U, E>>,
|
||||
{
|
||||
ResultShunt::process(iter, |i| i.product())
|
||||
}
|
||||
}
|
349
src/libcore/iter/traits/collect.rs
Normal file
349
src/libcore/iter/traits/collect.rs
Normal file
@ -0,0 +1,349 @@
|
||||
/// Conversion from an `Iterator`.
|
||||
///
|
||||
/// By implementing `FromIterator` for a type, you define how it will be
|
||||
/// created from an iterator. This is common for types which describe a
|
||||
/// collection of some kind.
|
||||
///
|
||||
/// `FromIterator`'s [`from_iter`] is rarely called explicitly, and is instead
|
||||
/// used through [`Iterator`]'s [`collect`] method. See [`collect`]'s
|
||||
/// documentation for more examples.
|
||||
///
|
||||
/// [`from_iter`]: #tymethod.from_iter
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
/// [`collect`]: trait.Iterator.html#method.collect
|
||||
///
|
||||
/// See also: [`IntoIterator`].
|
||||
///
|
||||
/// [`IntoIterator`]: trait.IntoIterator.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// use std::iter::FromIterator;
|
||||
///
|
||||
/// let five_fives = std::iter::repeat(5).take(5);
|
||||
///
|
||||
/// let v = Vec::from_iter(five_fives);
|
||||
///
|
||||
/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
|
||||
/// ```
|
||||
///
|
||||
/// Using [`collect`] to implicitly use `FromIterator`:
|
||||
///
|
||||
/// ```
|
||||
/// let five_fives = std::iter::repeat(5).take(5);
|
||||
///
|
||||
/// let v: Vec<i32> = five_fives.collect();
|
||||
///
|
||||
/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
|
||||
/// ```
|
||||
///
|
||||
/// Implementing `FromIterator` for your type:
|
||||
///
|
||||
/// ```
|
||||
/// use std::iter::FromIterator;
|
||||
///
|
||||
/// // A sample collection, that's just a wrapper over Vec<T>
|
||||
/// #[derive(Debug)]
|
||||
/// struct MyCollection(Vec<i32>);
|
||||
///
|
||||
/// // Let's give it some methods so we can create one and add things
|
||||
/// // to it.
|
||||
/// impl MyCollection {
|
||||
/// fn new() -> MyCollection {
|
||||
/// MyCollection(Vec::new())
|
||||
/// }
|
||||
///
|
||||
/// fn add(&mut self, elem: i32) {
|
||||
/// self.0.push(elem);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // and we'll implement FromIterator
|
||||
/// impl FromIterator<i32> for MyCollection {
|
||||
/// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
|
||||
/// let mut c = MyCollection::new();
|
||||
///
|
||||
/// for i in iter {
|
||||
/// c.add(i);
|
||||
/// }
|
||||
///
|
||||
/// c
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Now we can make a new iterator...
|
||||
/// let iter = (0..5).into_iter();
|
||||
///
|
||||
/// // ... and make a MyCollection out of it
|
||||
/// let c = MyCollection::from_iter(iter);
|
||||
///
|
||||
/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
|
||||
///
|
||||
/// // collect works too!
|
||||
///
|
||||
/// let iter = (0..5).into_iter();
|
||||
/// let c: MyCollection = iter.collect();
|
||||
///
|
||||
/// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
#[rustc_on_unimplemented(
|
||||
message="a collection of type `{Self}` cannot be built from an iterator \
|
||||
over elements of type `{A}`",
|
||||
label="a collection of type `{Self}` cannot be built from `std::iter::Iterator<Item={A}>`",
|
||||
)]
|
||||
pub trait FromIterator<A>: Sized {
|
||||
/// Creates a value from an iterator.
|
||||
///
|
||||
/// See the [module-level documentation] for more.
|
||||
///
|
||||
/// [module-level documentation]: index.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// use std::iter::FromIterator;
|
||||
///
|
||||
/// let five_fives = std::iter::repeat(5).take(5);
|
||||
///
|
||||
/// let v = Vec::from_iter(five_fives);
|
||||
///
|
||||
/// assert_eq!(v, vec![5, 5, 5, 5, 5]);
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
|
||||
}
|
||||
|
||||
/// Conversion into an `Iterator`.
|
||||
///
|
||||
/// By implementing `IntoIterator` for a type, you define how it will be
|
||||
/// converted to an iterator. This is common for types which describe a
|
||||
/// collection of some kind.
|
||||
///
|
||||
/// One benefit of implementing `IntoIterator` is that your type will [work
|
||||
/// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
|
||||
///
|
||||
/// See also: [`FromIterator`].
|
||||
///
|
||||
/// [`FromIterator`]: trait.FromIterator.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let v = vec![1, 2, 3];
|
||||
/// let mut iter = v.into_iter();
|
||||
///
|
||||
/// assert_eq!(Some(1), iter.next());
|
||||
/// assert_eq!(Some(2), iter.next());
|
||||
/// assert_eq!(Some(3), iter.next());
|
||||
/// assert_eq!(None, iter.next());
|
||||
/// ```
|
||||
/// Implementing `IntoIterator` for your type:
|
||||
///
|
||||
/// ```
|
||||
/// // A sample collection, that's just a wrapper over Vec<T>
|
||||
/// #[derive(Debug)]
|
||||
/// struct MyCollection(Vec<i32>);
|
||||
///
|
||||
/// // Let's give it some methods so we can create one and add things
|
||||
/// // to it.
|
||||
/// impl MyCollection {
|
||||
/// fn new() -> MyCollection {
|
||||
/// MyCollection(Vec::new())
|
||||
/// }
|
||||
///
|
||||
/// fn add(&mut self, elem: i32) {
|
||||
/// self.0.push(elem);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // and we'll implement IntoIterator
|
||||
/// impl IntoIterator for MyCollection {
|
||||
/// type Item = i32;
|
||||
/// type IntoIter = ::std::vec::IntoIter<i32>;
|
||||
///
|
||||
/// fn into_iter(self) -> Self::IntoIter {
|
||||
/// self.0.into_iter()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Now we can make a new collection...
|
||||
/// let mut c = MyCollection::new();
|
||||
///
|
||||
/// // ... add some stuff to it ...
|
||||
/// c.add(0);
|
||||
/// c.add(1);
|
||||
/// c.add(2);
|
||||
///
|
||||
/// // ... and then turn it into an Iterator:
|
||||
/// for (i, n) in c.into_iter().enumerate() {
|
||||
/// assert_eq!(i as i32, n);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// It is common to use `IntoIterator` as a trait bound. This allows
|
||||
/// the input collection type to change, so long as it is still an
|
||||
/// iterator. Additional bounds can be specified by restricting on
|
||||
/// `Item`:
|
||||
///
|
||||
/// ```rust
|
||||
/// fn collect_as_strings<T>(collection: T) -> Vec<String>
|
||||
/// where T: IntoIterator,
|
||||
/// T::Item : std::fmt::Debug,
|
||||
/// {
|
||||
/// collection
|
||||
/// .into_iter()
|
||||
/// .map(|item| format!("{:?}", item))
|
||||
/// .collect()
|
||||
/// }
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub trait IntoIterator {
|
||||
/// The type of the elements being iterated over.
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
type Item;
|
||||
|
||||
/// Which kind of iterator are we turning this into?
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
type IntoIter: Iterator<Item=Self::Item>;
|
||||
|
||||
/// Creates an iterator from a value.
|
||||
///
|
||||
/// See the [module-level documentation] for more.
|
||||
///
|
||||
/// [module-level documentation]: index.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let v = vec![1, 2, 3];
|
||||
/// let mut iter = v.into_iter();
|
||||
///
|
||||
/// assert_eq!(Some(1), iter.next());
|
||||
/// assert_eq!(Some(2), iter.next());
|
||||
/// assert_eq!(Some(3), iter.next());
|
||||
/// assert_eq!(None, iter.next());
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn into_iter(self) -> Self::IntoIter;
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<I: Iterator> IntoIterator for I {
|
||||
type Item = I::Item;
|
||||
type IntoIter = I;
|
||||
|
||||
fn into_iter(self) -> I {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Extend a collection with the contents of an iterator.
|
||||
///
|
||||
/// Iterators produce a series of values, and collections can also be thought
|
||||
/// of as a series of values. The `Extend` trait bridges this gap, allowing you
|
||||
/// to extend a collection by including the contents of that iterator. When
|
||||
/// extending a collection with an already existing key, that entry is updated
|
||||
/// or, in the case of collections that permit multiple entries with equal
|
||||
/// keys, that entry is inserted.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// // You can extend a String with some chars:
|
||||
/// let mut message = String::from("The first three letters are: ");
|
||||
///
|
||||
/// message.extend(&['a', 'b', 'c']);
|
||||
///
|
||||
/// assert_eq!("abc", &message[29..32]);
|
||||
/// ```
|
||||
///
|
||||
/// Implementing `Extend`:
|
||||
///
|
||||
/// ```
|
||||
/// // A sample collection, that's just a wrapper over Vec<T>
|
||||
/// #[derive(Debug)]
|
||||
/// struct MyCollection(Vec<i32>);
|
||||
///
|
||||
/// // Let's give it some methods so we can create one and add things
|
||||
/// // to it.
|
||||
/// impl MyCollection {
|
||||
/// fn new() -> MyCollection {
|
||||
/// MyCollection(Vec::new())
|
||||
/// }
|
||||
///
|
||||
/// fn add(&mut self, elem: i32) {
|
||||
/// self.0.push(elem);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // since MyCollection has a list of i32s, we implement Extend for i32
|
||||
/// impl Extend<i32> for MyCollection {
|
||||
///
|
||||
/// // This is a bit simpler with the concrete type signature: we can call
|
||||
/// // extend on anything which can be turned into an Iterator which gives
|
||||
/// // us i32s. Because we need i32s to put into MyCollection.
|
||||
/// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
|
||||
///
|
||||
/// // The implementation is very straightforward: loop through the
|
||||
/// // iterator, and add() each element to ourselves.
|
||||
/// for elem in iter {
|
||||
/// self.add(elem);
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let mut c = MyCollection::new();
|
||||
///
|
||||
/// c.add(5);
|
||||
/// c.add(6);
|
||||
/// c.add(7);
|
||||
///
|
||||
/// // let's extend our collection with three more numbers
|
||||
/// c.extend(vec![1, 2, 3]);
|
||||
///
|
||||
/// // we've added these elements onto the end
|
||||
/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub trait Extend<A> {
|
||||
/// Extends a collection with the contents of an iterator.
|
||||
///
|
||||
/// As this is the only method for this trait, the [trait-level] docs
|
||||
/// contain more details.
|
||||
///
|
||||
/// [trait-level]: trait.Extend.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// // You can extend a String with some chars:
|
||||
/// let mut message = String::from("abc");
|
||||
///
|
||||
/// message.extend(['d', 'e', 'f'].iter());
|
||||
///
|
||||
/// assert_eq!("abcdef", &message);
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
|
||||
}
|
||||
|
||||
#[stable(feature = "extend_for_unit", since = "1.28.0")]
|
||||
impl Extend<()> for () {
|
||||
fn extend<T: IntoIterator<Item = ()>>(&mut self, iter: T) {
|
||||
iter.into_iter().for_each(drop)
|
||||
}
|
||||
}
|
297
src/libcore/iter/traits/double_ended.rs
Normal file
297
src/libcore/iter/traits/double_ended.rs
Normal file
@ -0,0 +1,297 @@
|
||||
use ops::Try;
|
||||
use iter::LoopState;
|
||||
|
||||
/// An iterator able to yield elements from both ends.
|
||||
///
|
||||
/// Something that implements `DoubleEndedIterator` has one extra capability
|
||||
/// over something that implements [`Iterator`]: the ability to also take
|
||||
/// `Item`s from the back, as well as the front.
|
||||
///
|
||||
/// It is important to note that both back and forth work on the same range,
|
||||
/// and do not cross: iteration is over when they meet in the middle.
|
||||
///
|
||||
/// In a similar fashion to the [`Iterator`] protocol, once a
|
||||
/// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
|
||||
/// may or may not ever return `Some` again. `next()` and `next_back()` are
|
||||
/// interchangeable for this purpose.
|
||||
///
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let numbers = vec![1, 2, 3, 4, 5, 6];
|
||||
///
|
||||
/// let mut iter = numbers.iter();
|
||||
///
|
||||
/// assert_eq!(Some(&1), iter.next());
|
||||
/// assert_eq!(Some(&6), iter.next_back());
|
||||
/// assert_eq!(Some(&5), iter.next_back());
|
||||
/// assert_eq!(Some(&2), iter.next());
|
||||
/// assert_eq!(Some(&3), iter.next());
|
||||
/// assert_eq!(Some(&4), iter.next());
|
||||
/// assert_eq!(None, iter.next());
|
||||
/// assert_eq!(None, iter.next_back());
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub trait DoubleEndedIterator: Iterator {
|
||||
/// Removes and returns an element from the end of the iterator.
|
||||
///
|
||||
/// Returns `None` when there are no more elements.
|
||||
///
|
||||
/// The [trait-level] docs contain more details.
|
||||
///
|
||||
/// [trait-level]: trait.DoubleEndedIterator.html
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let numbers = vec![1, 2, 3, 4, 5, 6];
|
||||
///
|
||||
/// let mut iter = numbers.iter();
|
||||
///
|
||||
/// assert_eq!(Some(&1), iter.next());
|
||||
/// assert_eq!(Some(&6), iter.next_back());
|
||||
/// assert_eq!(Some(&5), iter.next_back());
|
||||
/// assert_eq!(Some(&2), iter.next());
|
||||
/// assert_eq!(Some(&3), iter.next());
|
||||
/// assert_eq!(Some(&4), iter.next());
|
||||
/// assert_eq!(None, iter.next());
|
||||
/// assert_eq!(None, iter.next_back());
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn next_back(&mut self) -> Option<Self::Item>;
|
||||
|
||||
/// Returns the `n`th element from the end of the iterator.
|
||||
///
|
||||
/// This is essentially the reversed version of [`nth`]. Although like most indexing
|
||||
/// operations, the count starts from zero, so `nth_back(0)` returns the first value fro
|
||||
/// the end, `nth_back(1)` the second, and so on.
|
||||
///
|
||||
/// Note that all elements between the end and the returned element will be
|
||||
/// consumed, including the returned element. This also means that calling
|
||||
/// `nth_back(0)` multiple times on the same iterator will return different
|
||||
/// elements.
|
||||
///
|
||||
/// `nth_back()` will return [`None`] if `n` is greater than or equal to the length of the
|
||||
/// iterator.
|
||||
///
|
||||
/// [`None`]: ../../std/option/enum.Option.html#variant.None
|
||||
/// [`nth`]: ../../std/iter/trait.Iterator.html#method.nth
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(iter_nth_back)]
|
||||
/// let a = [1, 2, 3];
|
||||
/// assert_eq!(a.iter().nth_back(2), Some(&1));
|
||||
/// ```
|
||||
///
|
||||
/// Calling `nth_back()` multiple times doesn't rewind the iterator:
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(iter_nth_back)]
|
||||
/// let a = [1, 2, 3];
|
||||
///
|
||||
/// let mut iter = a.iter();
|
||||
///
|
||||
/// assert_eq!(iter.nth_back(1), Some(&2));
|
||||
/// assert_eq!(iter.nth_back(1), None);
|
||||
/// ```
|
||||
///
|
||||
/// Returning `None` if there are less than `n + 1` elements:
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(iter_nth_back)]
|
||||
/// let a = [1, 2, 3];
|
||||
/// assert_eq!(a.iter().nth_back(10), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable(feature = "iter_nth_back", issue = "56995")]
|
||||
fn nth_back(&mut self, mut n: usize) -> Option<Self::Item> {
|
||||
for x in self.rev() {
|
||||
if n == 0 { return Some(x) }
|
||||
n -= 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// This is the reverse version of [`try_fold()`]: it takes elements
|
||||
/// starting from the back of the iterator.
|
||||
///
|
||||
/// [`try_fold()`]: trait.Iterator.html#method.try_fold
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let a = ["1", "2", "3"];
|
||||
/// let sum = a.iter()
|
||||
/// .map(|&s| s.parse::<i32>())
|
||||
/// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
|
||||
/// assert_eq!(sum, Ok(6));
|
||||
/// ```
|
||||
///
|
||||
/// Short-circuiting:
|
||||
///
|
||||
/// ```
|
||||
/// let a = ["1", "rust", "3"];
|
||||
/// let mut it = a.iter();
|
||||
/// let sum = it
|
||||
/// .by_ref()
|
||||
/// .map(|&s| s.parse::<i32>())
|
||||
/// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
|
||||
/// assert!(sum.is_err());
|
||||
///
|
||||
/// // Because it short-circuited, the remaining elements are still
|
||||
/// // available through the iterator.
|
||||
/// assert_eq!(it.next_back(), Some(&"1"));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
|
||||
fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(B, Self::Item) -> R,
|
||||
R: Try<Ok=B>
|
||||
{
|
||||
let mut accum = init;
|
||||
while let Some(x) = self.next_back() {
|
||||
accum = f(accum, x)?;
|
||||
}
|
||||
Try::from_ok(accum)
|
||||
}
|
||||
|
||||
/// An iterator method that reduces the iterator's elements to a single,
|
||||
/// final value, starting from the back.
|
||||
///
|
||||
/// This is the reverse version of [`fold()`]: it takes elements starting from
|
||||
/// the back of the iterator.
|
||||
///
|
||||
/// `rfold()` takes two arguments: an initial value, and a closure with two
|
||||
/// arguments: an 'accumulator', and an element. The closure returns the value that
|
||||
/// the accumulator should have for the next iteration.
|
||||
///
|
||||
/// The initial value is the value the accumulator will have on the first
|
||||
/// call.
|
||||
///
|
||||
/// After applying this closure to every element of the iterator, `rfold()`
|
||||
/// returns the accumulator.
|
||||
///
|
||||
/// This operation is sometimes called 'reduce' or 'inject'.
|
||||
///
|
||||
/// Folding is useful whenever you have a collection of something, and want
|
||||
/// to produce a single value from it.
|
||||
///
|
||||
/// [`fold()`]: trait.Iterator.html#method.fold
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let a = [1, 2, 3];
|
||||
///
|
||||
/// // the sum of all of the elements of a
|
||||
/// let sum = a.iter()
|
||||
/// .rfold(0, |acc, &x| acc + x);
|
||||
///
|
||||
/// assert_eq!(sum, 6);
|
||||
/// ```
|
||||
///
|
||||
/// This example builds a string, starting with an initial value
|
||||
/// and continuing with each element from the back until the front:
|
||||
///
|
||||
/// ```
|
||||
/// let numbers = [1, 2, 3, 4, 5];
|
||||
///
|
||||
/// let zero = "0".to_string();
|
||||
///
|
||||
/// let result = numbers.iter().rfold(zero, |acc, &x| {
|
||||
/// format!("({} + {})", x, acc)
|
||||
/// });
|
||||
///
|
||||
/// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable(feature = "iter_rfold", since = "1.27.0")]
|
||||
fn rfold<B, F>(mut self, accum: B, mut f: F) -> B
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(B, Self::Item) -> B,
|
||||
{
|
||||
self.try_rfold(accum, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
|
||||
}
|
||||
|
||||
/// Searches for an element of an iterator from the back that satisfies a predicate.
|
||||
///
|
||||
/// `rfind()` takes a closure that returns `true` or `false`. It applies
|
||||
/// this closure to each element of the iterator, starting at the end, and if any
|
||||
/// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
|
||||
/// `false`, it returns [`None`].
|
||||
///
|
||||
/// `rfind()` is short-circuiting; in other words, it will stop processing
|
||||
/// as soon as the closure returns `true`.
|
||||
///
|
||||
/// Because `rfind()` takes a reference, and many iterators iterate over
|
||||
/// references, this leads to a possibly confusing situation where the
|
||||
/// argument is a double reference. You can see this effect in the
|
||||
/// examples below, with `&&x`.
|
||||
///
|
||||
/// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
|
||||
/// [`None`]: ../../std/option/enum.Option.html#variant.None
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// let a = [1, 2, 3];
|
||||
///
|
||||
/// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
|
||||
///
|
||||
/// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
|
||||
/// ```
|
||||
///
|
||||
/// Stopping at the first `true`:
|
||||
///
|
||||
/// ```
|
||||
/// let a = [1, 2, 3];
|
||||
///
|
||||
/// let mut iter = a.iter();
|
||||
///
|
||||
/// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
|
||||
///
|
||||
/// // we can still use `iter`, as there are more elements.
|
||||
/// assert_eq!(iter.next_back(), Some(&1));
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable(feature = "iter_rfind", since = "1.27.0")]
|
||||
fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
P: FnMut(&Self::Item) -> bool
|
||||
{
|
||||
self.try_rfold((), move |(), x| {
|
||||
if predicate(&x) { LoopState::Break(x) }
|
||||
else { LoopState::Continue(()) }
|
||||
}).break_value()
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
|
||||
fn next_back(&mut self) -> Option<I::Item> {
|
||||
(**self).next_back()
|
||||
}
|
||||
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
|
||||
(**self).nth_back(n)
|
||||
}
|
||||
}
|
143
src/libcore/iter/traits/exact_size.rs
Normal file
143
src/libcore/iter/traits/exact_size.rs
Normal file
@ -0,0 +1,143 @@
|
||||
/// An iterator that knows its exact length.
|
||||
///
|
||||
/// Many [`Iterator`]s don't know how many times they will iterate, but some do.
|
||||
/// If an iterator knows how many times it can iterate, providing access to
|
||||
/// that information can be useful. For example, if you want to iterate
|
||||
/// backwards, a good start is to know where the end is.
|
||||
///
|
||||
/// When implementing an `ExactSizeIterator`, you must also implement
|
||||
/// [`Iterator`]. When doing so, the implementation of [`size_hint`] *must*
|
||||
/// return the exact size of the iterator.
|
||||
///
|
||||
/// [`Iterator`]: trait.Iterator.html
|
||||
/// [`size_hint`]: trait.Iterator.html#method.size_hint
|
||||
///
|
||||
/// The [`len`] method has a default implementation, so you usually shouldn't
|
||||
/// implement it. However, you may be able to provide a more performant
|
||||
/// implementation than the default, so overriding it in this case makes sense.
|
||||
///
|
||||
/// [`len`]: #method.len
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// // a finite range knows exactly how many times it will iterate
|
||||
/// let five = 0..5;
|
||||
///
|
||||
/// assert_eq!(5, five.len());
|
||||
/// ```
|
||||
///
|
||||
/// In the [module level docs][moddocs], we implemented an [`Iterator`],
|
||||
/// `Counter`. Let's implement `ExactSizeIterator` for it as well:
|
||||
///
|
||||
/// [moddocs]: index.html
|
||||
///
|
||||
/// ```
|
||||
/// # struct Counter {
|
||||
/// # count: usize,
|
||||
/// # }
|
||||
/// # impl Counter {
|
||||
/// # fn new() -> Counter {
|
||||
/// # Counter { count: 0 }
|
||||
/// # }
|
||||
/// # }
|
||||
/// # impl Iterator for Counter {
|
||||
/// # type Item = usize;
|
||||
/// # fn next(&mut self) -> Option<usize> {
|
||||
/// # self.count += 1;
|
||||
/// # if self.count < 6 {
|
||||
/// # Some(self.count)
|
||||
/// # } else {
|
||||
/// # None
|
||||
/// # }
|
||||
/// # }
|
||||
/// # }
|
||||
/// impl ExactSizeIterator for Counter {
|
||||
/// // We can easily calculate the remaining number of iterations.
|
||||
/// fn len(&self) -> usize {
|
||||
/// 5 - self.count
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // And now we can use it!
|
||||
///
|
||||
/// let counter = Counter::new();
|
||||
///
|
||||
/// assert_eq!(5, counter.len());
|
||||
/// ```
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
pub trait ExactSizeIterator: Iterator {
|
||||
/// Returns the exact number of times the iterator will iterate.
|
||||
///
|
||||
/// This method has a default implementation, so you usually should not
|
||||
/// implement it directly. However, if you can provide a more efficient
|
||||
/// implementation, you can do so. See the [trait-level] docs for an
|
||||
/// example.
|
||||
///
|
||||
/// This function has the same safety guarantees as the [`size_hint`]
|
||||
/// function.
|
||||
///
|
||||
/// [trait-level]: trait.ExactSizeIterator.html
|
||||
/// [`size_hint`]: trait.Iterator.html#method.size_hint
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// // a finite range knows exactly how many times it will iterate
|
||||
/// let five = 0..5;
|
||||
///
|
||||
/// assert_eq!(5, five.len());
|
||||
/// ```
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn len(&self) -> usize {
|
||||
let (lower, upper) = self.size_hint();
|
||||
// Note: This assertion is overly defensive, but it checks the invariant
|
||||
// guaranteed by the trait. If this trait were rust-internal,
|
||||
// we could use debug_assert!; assert_eq! will check all Rust user
|
||||
// implementations too.
|
||||
assert_eq!(upper, Some(lower));
|
||||
lower
|
||||
}
|
||||
|
||||
/// Returns whether the iterator is empty.
|
||||
///
|
||||
/// This method has a default implementation using `self.len()`, so you
|
||||
/// don't need to implement it yourself.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// Basic usage:
|
||||
///
|
||||
/// ```
|
||||
/// #![feature(exact_size_is_empty)]
|
||||
///
|
||||
/// let mut one_element = std::iter::once(0);
|
||||
/// assert!(!one_element.is_empty());
|
||||
///
|
||||
/// assert_eq!(one_element.next(), Some(0));
|
||||
/// assert!(one_element.is_empty());
|
||||
///
|
||||
/// assert_eq!(one_element.next(), None);
|
||||
/// ```
|
||||
#[inline]
|
||||
#[unstable(feature = "exact_size_is_empty", issue = "35428")]
|
||||
fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for &mut I {
|
||||
fn len(&self) -> usize {
|
||||
(**self).len()
|
||||
}
|
||||
fn is_empty(&self) -> bool {
|
||||
(**self).is_empty()
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,11 @@
|
||||
use cmp::Ordering;
|
||||
use ops::Try;
|
||||
|
||||
use super::LoopState;
|
||||
use super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse};
|
||||
use super::{Flatten, FlatMap, flatten_compat};
|
||||
use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
|
||||
use super::{Zip, Sum, Product};
|
||||
use super::{ChainState, FromIterator, ZipImpl};
|
||||
use super::super::LoopState;
|
||||
use super::super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse};
|
||||
use super::super::{Flatten, FlatMap};
|
||||
use super::super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
|
||||
use super::super::{Zip, Sum, Product, FromIterator};
|
||||
|
||||
fn _assert_is_object_safe(_: &dyn Iterator<Item=()>) {}
|
||||
|
||||
@ -367,8 +366,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "iterator_step_by", since = "1.28.0")]
|
||||
fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
|
||||
assert!(step != 0);
|
||||
StepBy{iter: self, step: step - 1, first_take: true}
|
||||
StepBy::new(self, step)
|
||||
}
|
||||
|
||||
/// Takes two iterators and creates a new iterator over both in sequence.
|
||||
@ -425,7 +423,7 @@ pub trait Iterator {
|
||||
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
|
||||
Self: Sized, U: IntoIterator<Item=Self::Item>,
|
||||
{
|
||||
Chain{a: self, b: other.into_iter(), state: ChainState::Both}
|
||||
Chain::new(self, other.into_iter())
|
||||
}
|
||||
|
||||
/// 'Zips up' two iterators into a single iterator of pairs.
|
||||
@ -560,7 +558,7 @@ pub trait Iterator {
|
||||
fn map<B, F>(self, f: F) -> Map<Self, F> where
|
||||
Self: Sized, F: FnMut(Self::Item) -> B,
|
||||
{
|
||||
Map { iter: self, f }
|
||||
Map::new(self, f)
|
||||
}
|
||||
|
||||
/// Calls a closure on each element of an iterator.
|
||||
@ -671,7 +669,7 @@ pub trait Iterator {
|
||||
fn filter<P>(self, predicate: P) -> Filter<Self, P> where
|
||||
Self: Sized, P: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
Filter {iter: self, predicate }
|
||||
Filter::new(self, predicate)
|
||||
}
|
||||
|
||||
/// Creates an iterator that both filters and maps.
|
||||
@ -728,7 +726,7 @@ pub trait Iterator {
|
||||
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
|
||||
Self: Sized, F: FnMut(Self::Item) -> Option<B>,
|
||||
{
|
||||
FilterMap { iter: self, f }
|
||||
FilterMap::new(self, f)
|
||||
}
|
||||
|
||||
/// Creates an iterator which gives the current iteration count as well as
|
||||
@ -772,7 +770,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn enumerate(self) -> Enumerate<Self> where Self: Sized {
|
||||
Enumerate { iter: self, count: 0 }
|
||||
Enumerate::new(self)
|
||||
}
|
||||
|
||||
/// Creates an iterator which can use `peek` to look at the next element of
|
||||
@ -818,7 +816,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn peekable(self) -> Peekable<Self> where Self: Sized {
|
||||
Peekable{iter: self, peeked: None}
|
||||
Peekable::new(self)
|
||||
}
|
||||
|
||||
/// Creates an iterator that [`skip`]s elements based on a predicate.
|
||||
@ -881,7 +879,7 @@ pub trait Iterator {
|
||||
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
|
||||
Self: Sized, P: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
SkipWhile { iter: self, flag: false, predicate }
|
||||
SkipWhile::new(self, predicate)
|
||||
}
|
||||
|
||||
/// Creates an iterator that yields elements based on a predicate.
|
||||
@ -961,7 +959,7 @@ pub trait Iterator {
|
||||
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
|
||||
Self: Sized, P: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
TakeWhile { iter: self, flag: false, predicate }
|
||||
TakeWhile::new(self, predicate)
|
||||
}
|
||||
|
||||
/// Creates an iterator that skips the first `n` elements.
|
||||
@ -983,7 +981,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
|
||||
Skip { iter: self, n }
|
||||
Skip::new(self, n)
|
||||
}
|
||||
|
||||
/// Creates an iterator that yields its first `n` elements.
|
||||
@ -1015,7 +1013,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn take(self, n: usize) -> Take<Self> where Self: Sized, {
|
||||
Take { iter: self, n }
|
||||
Take::new(self, n)
|
||||
}
|
||||
|
||||
/// An iterator adaptor similar to [`fold`] that holds internal state and
|
||||
@ -1060,7 +1058,7 @@ pub trait Iterator {
|
||||
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
|
||||
where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
|
||||
{
|
||||
Scan { iter: self, f, state: initial_state }
|
||||
Scan::new(self, initial_state, f)
|
||||
}
|
||||
|
||||
/// Creates an iterator that works like map, but flattens nested structure.
|
||||
@ -1098,7 +1096,7 @@ pub trait Iterator {
|
||||
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
|
||||
where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
|
||||
{
|
||||
FlatMap { inner: flatten_compat(self.map(f)) }
|
||||
FlatMap::new(self, f)
|
||||
}
|
||||
|
||||
/// Creates an iterator that flattens nested structure.
|
||||
@ -1166,7 +1164,7 @@ pub trait Iterator {
|
||||
#[stable(feature = "iterator_flatten", since = "1.29.0")]
|
||||
fn flatten(self) -> Flatten<Self>
|
||||
where Self: Sized, Self::Item: IntoIterator {
|
||||
Flatten { inner: flatten_compat(self) }
|
||||
Flatten::new(self)
|
||||
}
|
||||
|
||||
/// Creates an iterator which ends after the first [`None`].
|
||||
@ -1226,7 +1224,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn fuse(self) -> Fuse<Self> where Self: Sized {
|
||||
Fuse{iter: self, done: false}
|
||||
Fuse::new(self)
|
||||
}
|
||||
|
||||
/// Do something with each element of an iterator, passing the value on.
|
||||
@ -1309,7 +1307,7 @@ pub trait Iterator {
|
||||
fn inspect<F>(self, f: F) -> Inspect<Self, F> where
|
||||
Self: Sized, F: FnMut(&Self::Item),
|
||||
{
|
||||
Inspect { iter: self, f }
|
||||
Inspect::new(self, f)
|
||||
}
|
||||
|
||||
/// Borrows an iterator, rather than consuming it.
|
||||
@ -2183,7 +2181,7 @@ pub trait Iterator {
|
||||
#[inline]
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
|
||||
Rev{iter: self}
|
||||
Rev::new(self)
|
||||
}
|
||||
|
||||
/// Converts an iterator of pairs into a pair of containers.
|
||||
@ -2251,7 +2249,7 @@ pub trait Iterator {
|
||||
fn copied<'a, T: 'a>(self) -> Copied<Self>
|
||||
where Self: Sized + Iterator<Item=&'a T>, T: Copy
|
||||
{
|
||||
Copied { it: self }
|
||||
Copied::new(self)
|
||||
}
|
||||
|
||||
/// Creates an iterator which [`clone`]s all of its elements.
|
||||
@ -2280,7 +2278,7 @@ pub trait Iterator {
|
||||
fn cloned<'a, T: 'a>(self) -> Cloned<Self>
|
||||
where Self: Sized + Iterator<Item=&'a T>, T: Clone
|
||||
{
|
||||
Cloned { it: self }
|
||||
Cloned::new(self)
|
||||
}
|
||||
|
||||
/// Repeats an iterator endlessly.
|
||||
@ -2311,7 +2309,7 @@ pub trait Iterator {
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
#[inline]
|
||||
fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
|
||||
Cycle{orig: self.clone(), iter: self}
|
||||
Cycle::new(self)
|
||||
}
|
||||
|
||||
/// Sums the elements of an iterator.
|
44
src/libcore/iter/traits/marker.rs
Normal file
44
src/libcore/iter/traits/marker.rs
Normal file
@ -0,0 +1,44 @@
|
||||
/// An iterator that always continues to yield `None` when exhausted.
|
||||
///
|
||||
/// Calling next on a fused iterator that has returned `None` once is guaranteed
|
||||
/// to return [`None`] again. This trait should be implemented by all iterators
|
||||
/// that behave this way because it allows optimizing [`Iterator::fuse`].
|
||||
///
|
||||
/// Note: In general, you should not use `FusedIterator` in generic bounds if
|
||||
/// you need a fused iterator. Instead, you should just call [`Iterator::fuse`]
|
||||
/// on the iterator. If the iterator is already fused, the additional [`Fuse`]
|
||||
/// wrapper will be a no-op with no performance penalty.
|
||||
///
|
||||
/// [`None`]: ../../std/option/enum.Option.html#variant.None
|
||||
/// [`Iterator::fuse`]: ../../std/iter/trait.Iterator.html#method.fuse
|
||||
/// [`Fuse`]: ../../std/iter/struct.Fuse.html
|
||||
#[stable(feature = "fused", since = "1.26.0")]
|
||||
pub trait FusedIterator: Iterator {}
|
||||
|
||||
#[stable(feature = "fused", since = "1.26.0")]
|
||||
impl<I: FusedIterator + ?Sized> FusedIterator for &mut I {}
|
||||
|
||||
/// An iterator that reports an accurate length using size_hint.
|
||||
///
|
||||
/// The iterator reports a size hint where it is either exact
|
||||
/// (lower bound is equal to upper bound), or the upper bound is [`None`].
|
||||
/// The upper bound must only be [`None`] if the actual iterator length is
|
||||
/// larger than [`usize::MAX`]. In that case, the lower bound must be
|
||||
/// [`usize::MAX`], resulting in a [`.size_hint`] of `(usize::MAX, None)`.
|
||||
///
|
||||
/// The iterator must produce exactly the number of elements it reported
|
||||
/// or diverge before reaching the end.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// This trait must only be implemented when the contract is upheld.
|
||||
/// Consumers of this trait must inspect [`.size_hint`]’s upper bound.
|
||||
///
|
||||
/// [`None`]: ../../std/option/enum.Option.html#variant.None
|
||||
/// [`usize::MAX`]: ../../std/usize/constant.MAX.html
|
||||
/// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint
|
||||
#[unstable(feature = "trusted_len", issue = "37572")]
|
||||
pub unsafe trait TrustedLen : Iterator {}
|
||||
|
||||
#[unstable(feature = "trusted_len", issue = "37572")]
|
||||
unsafe impl<I: TrustedLen + ?Sized> TrustedLen for &mut I {}
|
13
src/libcore/iter/traits/mod.rs
Normal file
13
src/libcore/iter/traits/mod.rs
Normal file
@ -0,0 +1,13 @@
|
||||
mod iterator;
|
||||
mod double_ended;
|
||||
mod exact_size;
|
||||
mod collect;
|
||||
mod accum;
|
||||
mod marker;
|
||||
|
||||
pub use self::iterator::Iterator;
|
||||
pub use self::double_ended::DoubleEndedIterator;
|
||||
pub use self::exact_size::ExactSizeIterator;
|
||||
pub use self::collect::{FromIterator, IntoIterator, Extend};
|
||||
pub use self::accum::{Sum, Product};
|
||||
pub use self::marker::{FusedIterator, TrustedLen};
|
@ -216,7 +216,6 @@ pub mod task;
|
||||
pub mod alloc;
|
||||
|
||||
// note: does not need to be public
|
||||
mod iter_private;
|
||||
mod tuple;
|
||||
mod unit;
|
||||
|
||||
|
@ -34,7 +34,6 @@ use result::Result::{Ok, Err};
|
||||
use ptr;
|
||||
use mem;
|
||||
use marker::{Copy, Send, Sync, Sized, self};
|
||||
use iter_private::TrustedRandomAccess;
|
||||
|
||||
#[unstable(feature = "slice_internals", issue = "0",
|
||||
reason = "exposed from core to be reused in std; use the memchr crate")]
|
||||
|
@ -9,8 +9,7 @@ use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
|
||||
|
||||
use char;
|
||||
use fmt;
|
||||
use iter::{Map, Cloned, FusedIterator, TrustedLen, Filter};
|
||||
use iter_private::TrustedRandomAccess;
|
||||
use iter::{Map, Cloned, FusedIterator, TrustedLen, TrustedRandomAccess, Filter};
|
||||
use slice::{self, SliceIndex, Split as SliceSplit};
|
||||
use mem;
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user