Auto merge of #33079 - bluss:split-iter, r=alexcrichton
Split core::iter module implementation into parts Split core::iter module implementation into parts split iter.rs into a directory of (implementation private) modules. + mod (adaptor structs whose private fields need to be available both for them and Iterator + iterator (Iterator trait) + traits (FromIterator, etc; all traits but Iterator itself) + range (range related) + sources (Repeat, Once, Empty)
This commit is contained in:
commit
887e947178
5012
src/libcore/iter.rs
5012
src/libcore/iter.rs
File diff suppressed because it is too large
Load Diff
2112
src/libcore/iter/iterator.rs
Normal file
2112
src/libcore/iter/iterator.rs
Normal file
File diff suppressed because it is too large
Load Diff
1657
src/libcore/iter/mod.rs
Normal file
1657
src/libcore/iter/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
548
src/libcore/iter/range.rs
Normal file
548
src/libcore/iter/range.rs
Normal file
@ -0,0 +1,548 @@
|
|||||||
|
// Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
|
||||||
|
// file at the top-level directory of this distribution and at
|
||||||
|
// http://rust-lang.org/COPYRIGHT.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||||
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||||
|
// option. This file may not be copied, modified, or distributed
|
||||||
|
// except according to those terms.
|
||||||
|
|
||||||
|
use clone::Clone;
|
||||||
|
use cmp::PartialOrd;
|
||||||
|
use mem;
|
||||||
|
use num::{Zero, One};
|
||||||
|
use ops::{self, Add, Sub};
|
||||||
|
use option::Option::{self, Some, None};
|
||||||
|
use marker::Sized;
|
||||||
|
use usize;
|
||||||
|
|
||||||
|
use super::{DoubleEndedIterator, ExactSizeIterator, Iterator};
|
||||||
|
|
||||||
|
/// Objects that can be stepped over in both directions.
|
||||||
|
///
|
||||||
|
/// The `steps_between` function provides a way to efficiently compare
|
||||||
|
/// two `Step` objects.
|
||||||
|
#[unstable(feature = "step_trait",
|
||||||
|
reason = "likely to be replaced by finer-grained traits",
|
||||||
|
issue = "27741")]
|
||||||
|
pub trait Step: PartialOrd + Sized {
|
||||||
|
/// Steps `self` if possible.
|
||||||
|
fn step(&self, by: &Self) -> Option<Self>;
|
||||||
|
|
||||||
|
/// Returns the number of steps between two step objects. The count is
|
||||||
|
/// inclusive of `start` and exclusive of `end`.
|
||||||
|
///
|
||||||
|
/// Returns `None` if it is not possible to calculate `steps_between`
|
||||||
|
/// without overflow.
|
||||||
|
fn steps_between(start: &Self, end: &Self, by: &Self) -> Option<usize>;
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! step_impl_unsigned {
|
||||||
|
($($t:ty)*) => ($(
|
||||||
|
#[unstable(feature = "step_trait",
|
||||||
|
reason = "likely to be replaced by finer-grained traits",
|
||||||
|
issue = "27741")]
|
||||||
|
impl Step for $t {
|
||||||
|
#[inline]
|
||||||
|
fn step(&self, by: &$t) -> Option<$t> {
|
||||||
|
(*self).checked_add(*by)
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
#[allow(trivial_numeric_casts)]
|
||||||
|
fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
|
||||||
|
if *by == 0 { return None; }
|
||||||
|
if *start < *end {
|
||||||
|
// Note: We assume $t <= usize here
|
||||||
|
let diff = (*end - *start) as usize;
|
||||||
|
let by = *by as usize;
|
||||||
|
if diff % by > 0 {
|
||||||
|
Some(diff / by + 1)
|
||||||
|
} else {
|
||||||
|
Some(diff / by)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Some(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)*)
|
||||||
|
}
|
||||||
|
macro_rules! step_impl_signed {
|
||||||
|
($($t:ty)*) => ($(
|
||||||
|
#[unstable(feature = "step_trait",
|
||||||
|
reason = "likely to be replaced by finer-grained traits",
|
||||||
|
issue = "27741")]
|
||||||
|
impl Step for $t {
|
||||||
|
#[inline]
|
||||||
|
fn step(&self, by: &$t) -> Option<$t> {
|
||||||
|
(*self).checked_add(*by)
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
#[allow(trivial_numeric_casts)]
|
||||||
|
fn steps_between(start: &$t, end: &$t, by: &$t) -> Option<usize> {
|
||||||
|
if *by == 0 { return None; }
|
||||||
|
let diff: usize;
|
||||||
|
let by_u: usize;
|
||||||
|
if *by > 0 {
|
||||||
|
if *start >= *end {
|
||||||
|
return Some(0);
|
||||||
|
}
|
||||||
|
// Note: We assume $t <= isize here
|
||||||
|
// Use .wrapping_sub and cast to usize to compute the
|
||||||
|
// difference that may not fit inside the range of isize.
|
||||||
|
diff = (*end as isize).wrapping_sub(*start as isize) as usize;
|
||||||
|
by_u = *by as usize;
|
||||||
|
} else {
|
||||||
|
if *start <= *end {
|
||||||
|
return Some(0);
|
||||||
|
}
|
||||||
|
diff = (*start as isize).wrapping_sub(*end as isize) as usize;
|
||||||
|
by_u = (*by as isize).wrapping_mul(-1) as usize;
|
||||||
|
}
|
||||||
|
if diff % by_u > 0 {
|
||||||
|
Some(diff / by_u + 1)
|
||||||
|
} else {
|
||||||
|
Some(diff / by_u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)*)
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! step_impl_no_between {
|
||||||
|
($($t:ty)*) => ($(
|
||||||
|
#[unstable(feature = "step_trait",
|
||||||
|
reason = "likely to be replaced by finer-grained traits",
|
||||||
|
issue = "27741")]
|
||||||
|
impl Step for $t {
|
||||||
|
#[inline]
|
||||||
|
fn step(&self, by: &$t) -> Option<$t> {
|
||||||
|
(*self).checked_add(*by)
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
fn steps_between(_a: &$t, _b: &$t, _by: &$t) -> Option<usize> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)*)
|
||||||
|
}
|
||||||
|
|
||||||
|
step_impl_unsigned!(usize u8 u16 u32);
|
||||||
|
step_impl_signed!(isize i8 i16 i32);
|
||||||
|
#[cfg(target_pointer_width = "64")]
|
||||||
|
step_impl_unsigned!(u64);
|
||||||
|
#[cfg(target_pointer_width = "64")]
|
||||||
|
step_impl_signed!(i64);
|
||||||
|
// If the target pointer width is not 64-bits, we
|
||||||
|
// assume here that it is less than 64-bits.
|
||||||
|
#[cfg(not(target_pointer_width = "64"))]
|
||||||
|
step_impl_no_between!(u64 i64);
|
||||||
|
|
||||||
|
/// An adapter for stepping range iterators by a custom amount.
|
||||||
|
///
|
||||||
|
/// The resulting iterator handles overflow by stopping. The `A`
|
||||||
|
/// parameter is the type being iterated over, while `R` is the range
|
||||||
|
/// type (usually one of `std::ops::{Range, RangeFrom, RangeInclusive}`.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
#[unstable(feature = "step_by", reason = "recent addition",
|
||||||
|
issue = "27741")]
|
||||||
|
pub struct StepBy<A, R> {
|
||||||
|
step_by: A,
|
||||||
|
range: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Step> ops::RangeFrom<A> {
|
||||||
|
/// Creates an iterator starting at the same point, but stepping by
|
||||||
|
/// the given amount at each iteration.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # #![feature(step_by)]
|
||||||
|
///
|
||||||
|
/// for i in (0u8..).step_by(2).take(10) {
|
||||||
|
/// println!("{}", i);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// This prints the first ten even natural integers (0 to 18).
|
||||||
|
#[unstable(feature = "step_by", reason = "recent addition",
|
||||||
|
issue = "27741")]
|
||||||
|
pub fn step_by(self, by: A) -> StepBy<A, Self> {
|
||||||
|
StepBy {
|
||||||
|
step_by: by,
|
||||||
|
range: self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Step> ops::Range<A> {
|
||||||
|
/// Creates an iterator with the same range, but stepping by the
|
||||||
|
/// given amount at each iteration.
|
||||||
|
///
|
||||||
|
/// The resulting iterator handles overflow by stopping.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// #![feature(step_by)]
|
||||||
|
///
|
||||||
|
/// for i in (0..10).step_by(2) {
|
||||||
|
/// println!("{}", i);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// This prints:
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// 0
|
||||||
|
/// 2
|
||||||
|
/// 4
|
||||||
|
/// 6
|
||||||
|
/// 8
|
||||||
|
/// ```
|
||||||
|
#[unstable(feature = "step_by", reason = "recent addition",
|
||||||
|
issue = "27741")]
|
||||||
|
pub fn step_by(self, by: A) -> StepBy<A, Self> {
|
||||||
|
StepBy {
|
||||||
|
step_by: by,
|
||||||
|
range: self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A: Step> ops::RangeInclusive<A> {
|
||||||
|
/// Creates an iterator with the same range, but stepping by the
|
||||||
|
/// given amount at each iteration.
|
||||||
|
///
|
||||||
|
/// The resulting iterator handles overflow by stopping.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// #![feature(step_by, inclusive_range_syntax)]
|
||||||
|
///
|
||||||
|
/// for i in (0...10).step_by(2) {
|
||||||
|
/// println!("{}", i);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// This prints:
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// 0
|
||||||
|
/// 2
|
||||||
|
/// 4
|
||||||
|
/// 6
|
||||||
|
/// 8
|
||||||
|
/// 10
|
||||||
|
/// ```
|
||||||
|
#[unstable(feature = "step_by", reason = "recent addition",
|
||||||
|
issue = "27741")]
|
||||||
|
pub fn step_by(self, by: A) -> StepBy<A, Self> {
|
||||||
|
StepBy {
|
||||||
|
step_by: by,
|
||||||
|
range: self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A> Iterator for StepBy<A, ops::RangeFrom<A>> where
|
||||||
|
A: Clone,
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
let mut n = &self.range.start + &self.step_by;
|
||||||
|
mem::swap(&mut n, &mut self.range.start);
|
||||||
|
Some(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
(usize::MAX, None) // Too bad we can't specify an infinite lower bound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::Range<A>> {
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
let rev = self.step_by < A::zero();
|
||||||
|
if (rev && self.range.start > self.range.end) ||
|
||||||
|
(!rev && self.range.start < self.range.end)
|
||||||
|
{
|
||||||
|
match self.range.start.step(&self.step_by) {
|
||||||
|
Some(mut n) => {
|
||||||
|
mem::swap(&mut self.range.start, &mut n);
|
||||||
|
Some(n)
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
let mut n = self.range.end.clone();
|
||||||
|
mem::swap(&mut self.range.start, &mut n);
|
||||||
|
Some(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
match Step::steps_between(&self.range.start,
|
||||||
|
&self.range.end,
|
||||||
|
&self.step_by) {
|
||||||
|
Some(hint) => (hint, Some(hint)),
|
||||||
|
None => (0, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unstable(feature = "inclusive_range",
|
||||||
|
reason = "recently added, follows RFC",
|
||||||
|
issue = "28237")]
|
||||||
|
impl<A: Step + Zero + Clone> Iterator for StepBy<A, ops::RangeInclusive<A>> {
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
use ops::RangeInclusive::*;
|
||||||
|
|
||||||
|
// this function has a sort of odd structure due to borrowck issues
|
||||||
|
// we may need to replace self.range, so borrows of start and end need to end early
|
||||||
|
|
||||||
|
let (finishing, n) = match self.range {
|
||||||
|
Empty { .. } => return None, // empty iterators yield no values
|
||||||
|
|
||||||
|
NonEmpty { ref mut start, ref mut end } => {
|
||||||
|
let zero = A::zero();
|
||||||
|
let rev = self.step_by < zero;
|
||||||
|
|
||||||
|
// march start towards (maybe past!) end and yield the old value
|
||||||
|
if (rev && start >= end) ||
|
||||||
|
(!rev && start <= end)
|
||||||
|
{
|
||||||
|
match start.step(&self.step_by) {
|
||||||
|
Some(mut n) => {
|
||||||
|
mem::swap(start, &mut n);
|
||||||
|
(None, Some(n)) // yield old value, remain non-empty
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
let mut n = end.clone();
|
||||||
|
mem::swap(start, &mut n);
|
||||||
|
(None, Some(n)) // yield old value, remain non-empty
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// found range in inconsistent state (start at or past end), so become empty
|
||||||
|
(Some(mem::replace(end, zero)), None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// turn into an empty iterator if we've reached the end
|
||||||
|
if let Some(end) = finishing {
|
||||||
|
self.range = Empty { at: end };
|
||||||
|
}
|
||||||
|
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
use ops::RangeInclusive::*;
|
||||||
|
|
||||||
|
match self.range {
|
||||||
|
Empty { .. } => (0, Some(0)),
|
||||||
|
|
||||||
|
NonEmpty { ref start, ref end } =>
|
||||||
|
match Step::steps_between(start,
|
||||||
|
end,
|
||||||
|
&self.step_by) {
|
||||||
|
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
|
||||||
|
None => (0, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! range_exact_iter_impl {
|
||||||
|
($($t:ty)*) => ($(
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl ExactSizeIterator for ops::Range<$t> { }
|
||||||
|
|
||||||
|
#[unstable(feature = "inclusive_range",
|
||||||
|
reason = "recently added, follows RFC",
|
||||||
|
issue = "28237")]
|
||||||
|
impl ExactSizeIterator for ops::RangeInclusive<$t> { }
|
||||||
|
)*)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Step + One> Iterator for ops::Range<A> where
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
if self.start < self.end {
|
||||||
|
let mut n = &self.start + &A::one();
|
||||||
|
mem::swap(&mut n, &mut self.start);
|
||||||
|
Some(n)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
match Step::steps_between(&self.start, &self.end, &A::one()) {
|
||||||
|
Some(hint) => (hint, Some(hint)),
|
||||||
|
None => (0, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ranges of u64 and i64 are excluded because they cannot guarantee having
|
||||||
|
// a length <= usize::MAX, which is required by ExactSizeIterator.
|
||||||
|
range_exact_iter_impl!(usize u8 u16 u32 isize i8 i16 i32);
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Step + One + Clone> DoubleEndedIterator for ops::Range<A> where
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>,
|
||||||
|
for<'a> &'a A: Sub<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn next_back(&mut self) -> Option<A> {
|
||||||
|
if self.start < self.end {
|
||||||
|
self.end = &self.end - &A::one();
|
||||||
|
Some(self.end.clone())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Step + One> Iterator for ops::RangeFrom<A> where
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
let mut n = &self.start + &A::one();
|
||||||
|
mem::swap(&mut n, &mut self.start);
|
||||||
|
Some(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
|
||||||
|
impl<A: Step + One> Iterator for ops::RangeInclusive<A> where
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> {
|
||||||
|
use ops::RangeInclusive::*;
|
||||||
|
|
||||||
|
// this function has a sort of odd structure due to borrowck issues
|
||||||
|
// we may need to replace self, so borrows of self.start and self.end need to end early
|
||||||
|
|
||||||
|
let (finishing, n) = match *self {
|
||||||
|
Empty { .. } => (None, None), // empty iterators yield no values
|
||||||
|
|
||||||
|
NonEmpty { ref mut start, ref mut end } => {
|
||||||
|
if start == end {
|
||||||
|
(Some(mem::replace(end, A::one())), Some(mem::replace(start, A::one())))
|
||||||
|
} else if start < end {
|
||||||
|
let one = A::one();
|
||||||
|
let mut n = &*start + &one;
|
||||||
|
mem::swap(&mut n, start);
|
||||||
|
|
||||||
|
// if the iterator is done iterating, it will change from NonEmpty to Empty
|
||||||
|
// to avoid unnecessary drops or clones, we'll reuse either start or end
|
||||||
|
// (they are equal now, so it doesn't matter which)
|
||||||
|
// to pull out end, we need to swap something back in -- use the previously
|
||||||
|
// created A::one() as a dummy value
|
||||||
|
|
||||||
|
(if n == *end { Some(mem::replace(end, one)) } else { None },
|
||||||
|
// ^ are we done yet?
|
||||||
|
Some(n)) // < the value to output
|
||||||
|
} else {
|
||||||
|
(Some(mem::replace(start, A::one())), None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// turn into an empty iterator if this is the last value
|
||||||
|
if let Some(end) = finishing {
|
||||||
|
*self = Empty { at: end };
|
||||||
|
}
|
||||||
|
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
use ops::RangeInclusive::*;
|
||||||
|
|
||||||
|
match *self {
|
||||||
|
Empty { .. } => (0, Some(0)),
|
||||||
|
|
||||||
|
NonEmpty { ref start, ref end } =>
|
||||||
|
match Step::steps_between(start, end, &A::one()) {
|
||||||
|
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
|
||||||
|
None => (0, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
|
||||||
|
impl<A: Step + One> DoubleEndedIterator for ops::RangeInclusive<A> where
|
||||||
|
for<'a> &'a A: Add<&'a A, Output = A>,
|
||||||
|
for<'a> &'a A: Sub<&'a A, Output = A>
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn next_back(&mut self) -> Option<A> {
|
||||||
|
use ops::RangeInclusive::*;
|
||||||
|
|
||||||
|
// see Iterator::next for comments
|
||||||
|
|
||||||
|
let (finishing, n) = match *self {
|
||||||
|
Empty { .. } => return None,
|
||||||
|
|
||||||
|
NonEmpty { ref mut start, ref mut end } => {
|
||||||
|
if start == end {
|
||||||
|
(Some(mem::replace(start, A::one())), Some(mem::replace(end, A::one())))
|
||||||
|
} else if start < end {
|
||||||
|
let one = A::one();
|
||||||
|
let mut n = &*end - &one;
|
||||||
|
mem::swap(&mut n, end);
|
||||||
|
|
||||||
|
(if n == *start { Some(mem::replace(start, one)) } else { None },
|
||||||
|
Some(n))
|
||||||
|
} else {
|
||||||
|
(Some(mem::replace(end, A::one())), None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(start) = finishing {
|
||||||
|
*self = Empty { at: start };
|
||||||
|
}
|
||||||
|
|
||||||
|
n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
270
src/libcore/iter/sources.rs
Normal file
270
src/libcore/iter/sources.rs
Normal file
@ -0,0 +1,270 @@
|
|||||||
|
// Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
|
||||||
|
// file at the top-level directory of this distribution and at
|
||||||
|
// http://rust-lang.org/COPYRIGHT.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||||
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||||
|
// option. This file may not be copied, modified, or distributed
|
||||||
|
// except according to those terms.
|
||||||
|
|
||||||
|
use clone::Clone;
|
||||||
|
use default::Default;
|
||||||
|
use fmt;
|
||||||
|
use marker;
|
||||||
|
use option::Option::{self, Some, None};
|
||||||
|
use usize;
|
||||||
|
|
||||||
|
use super::{DoubleEndedIterator, IntoIterator, Iterator, ExactSizeIterator};
|
||||||
|
|
||||||
|
/// An iterator that repeats an element endlessly.
|
||||||
|
///
|
||||||
|
/// This `struct` is created by the [`repeat()`] function. See its documentation for more.
|
||||||
|
///
|
||||||
|
/// [`repeat()`]: fn.repeat.html
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
pub struct Repeat<A> {
|
||||||
|
element: A
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Clone> Iterator for Repeat<A> {
|
||||||
|
type Item = A;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn next(&mut self) -> Option<A> { Some(self.element.clone()) }
|
||||||
|
#[inline]
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) { (usize::MAX, None) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<A: Clone> DoubleEndedIterator for Repeat<A> {
|
||||||
|
#[inline]
|
||||||
|
fn next_back(&mut self) -> Option<A> { Some(self.element.clone()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new iterator that endlessly repeats a single element.
|
||||||
|
///
|
||||||
|
/// The `repeat()` function repeats a single value over and over and over and
|
||||||
|
/// over and over and 🔁.
|
||||||
|
///
|
||||||
|
/// Infinite iterators like `repeat()` are often used with adapters like
|
||||||
|
/// [`take()`], in order to make them finite.
|
||||||
|
///
|
||||||
|
/// [`take()`]: trait.Iterator.html#method.take
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::iter;
|
||||||
|
///
|
||||||
|
/// // the number four 4ever:
|
||||||
|
/// let mut fours = iter::repeat(4);
|
||||||
|
///
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
///
|
||||||
|
/// // yup, still four
|
||||||
|
/// assert_eq!(Some(4), fours.next());
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Going finite with [`take()`]:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::iter;
|
||||||
|
///
|
||||||
|
/// // that last example was too many fours. Let's only have four fours.
|
||||||
|
/// let mut four_fours = iter::repeat(4).take(4);
|
||||||
|
///
|
||||||
|
/// assert_eq!(Some(4), four_fours.next());
|
||||||
|
/// assert_eq!(Some(4), four_fours.next());
|
||||||
|
/// assert_eq!(Some(4), four_fours.next());
|
||||||
|
/// assert_eq!(Some(4), four_fours.next());
|
||||||
|
///
|
||||||
|
/// // ... and now we're done
|
||||||
|
/// assert_eq!(None, four_fours.next());
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
|
||||||
|
Repeat{element: elt}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An iterator that yields nothing.
|
||||||
|
///
|
||||||
|
/// This `struct` is created by the [`empty()`] function. See its documentation for more.
|
||||||
|
///
|
||||||
|
/// [`empty()`]: fn.empty.html
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
pub struct Empty<T>(marker::PhantomData<T>);
|
||||||
|
|
||||||
|
#[stable(feature = "core_impl_debug", since = "1.9.0")]
|
||||||
|
impl<T> fmt::Debug for Empty<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
f.pad("Empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
impl<T> Iterator for Empty<T> {
|
||||||
|
type Item = T;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<T> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>){
|
||||||
|
(0, Some(0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
impl<T> DoubleEndedIterator for Empty<T> {
|
||||||
|
fn next_back(&mut self) -> Option<T> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
impl<T> ExactSizeIterator for Empty<T> {
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// not #[derive] because that adds a Clone bound on T,
|
||||||
|
// which isn't necessary.
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
impl<T> Clone for Empty<T> {
|
||||||
|
fn clone(&self) -> Empty<T> {
|
||||||
|
Empty(marker::PhantomData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// not #[derive] because that adds a Default bound on T,
|
||||||
|
// which isn't necessary.
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
impl<T> Default for Empty<T> {
|
||||||
|
fn default() -> Empty<T> {
|
||||||
|
Empty(marker::PhantomData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an iterator that yields nothing.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::iter;
|
||||||
|
///
|
||||||
|
/// // this could have been an iterator over i32, but alas, it's just not.
|
||||||
|
/// let mut nope = iter::empty::<i32>();
|
||||||
|
///
|
||||||
|
/// assert_eq!(None, nope.next());
|
||||||
|
/// ```
|
||||||
|
#[stable(feature = "iter_empty", since = "1.2.0")]
|
||||||
|
pub fn empty<T>() -> Empty<T> {
|
||||||
|
Empty(marker::PhantomData)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An iterator that yields an element exactly once.
|
||||||
|
///
|
||||||
|
/// This `struct` is created by the [`once()`] function. See its documentation for more.
|
||||||
|
///
|
||||||
|
/// [`once()`]: fn.once.html
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
#[stable(feature = "iter_once", since = "1.2.0")]
|
||||||
|
pub struct Once<T> {
|
||||||
|
inner: ::option::IntoIter<T>
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_once", since = "1.2.0")]
|
||||||
|
impl<T> Iterator for Once<T> {
|
||||||
|
type Item = T;
|
||||||
|
|
||||||
|
fn next(&mut self) -> Option<T> {
|
||||||
|
self.inner.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
self.inner.size_hint()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_once", since = "1.2.0")]
|
||||||
|
impl<T> DoubleEndedIterator for Once<T> {
|
||||||
|
fn next_back(&mut self) -> Option<T> {
|
||||||
|
self.inner.next_back()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "iter_once", since = "1.2.0")]
|
||||||
|
impl<T> ExactSizeIterator for Once<T> {
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
self.inner.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an iterator that yields an element exactly once.
|
||||||
|
///
|
||||||
|
/// This is commonly used to adapt a single value into a [`chain()`] of other
|
||||||
|
/// kinds of iteration. Maybe you have an iterator that covers almost
|
||||||
|
/// everything, but you need an extra special case. Maybe you have a function
|
||||||
|
/// which works on iterators, but you only need to process one value.
|
||||||
|
///
|
||||||
|
/// [`chain()`]: trait.Iterator.html#method.chain
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use std::iter;
|
||||||
|
///
|
||||||
|
/// // one is the loneliest number
|
||||||
|
/// let mut one = iter::once(1);
|
||||||
|
///
|
||||||
|
/// assert_eq!(Some(1), one.next());
|
||||||
|
///
|
||||||
|
/// // just one, that's all we get
|
||||||
|
/// assert_eq!(None, one.next());
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Chaining together with another iterator. Let's say that we want to iterate
|
||||||
|
/// over each file of the `.foo` directory, but also a configuration file,
|
||||||
|
/// `.foorc`:
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use std::iter;
|
||||||
|
/// use std::fs;
|
||||||
|
/// use std::path::PathBuf;
|
||||||
|
///
|
||||||
|
/// let dirs = fs::read_dir(".foo").unwrap();
|
||||||
|
///
|
||||||
|
/// // we need to convert from an iterator of DirEntry-s to an iterator of
|
||||||
|
/// // PathBufs, so we use map
|
||||||
|
/// let dirs = dirs.map(|file| file.unwrap().path());
|
||||||
|
///
|
||||||
|
/// // now, our iterator just for our config file
|
||||||
|
/// let config = iter::once(PathBuf::from(".foorc"));
|
||||||
|
///
|
||||||
|
/// // chain the two iterators together into one big iterator
|
||||||
|
/// let files = dirs.chain(config);
|
||||||
|
///
|
||||||
|
/// // this will give us all of the files in .foo as well as .foorc
|
||||||
|
/// for f in files {
|
||||||
|
/// println!("{:?}", f);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[stable(feature = "iter_once", since = "1.2.0")]
|
||||||
|
pub fn once<T>(value: T) -> Once<T> {
|
||||||
|
Once { inner: Some(value).into_iter() }
|
||||||
|
}
|
526
src/libcore/iter/traits.rs
Normal file
526
src/libcore/iter/traits.rs
Normal file
@ -0,0 +1,526 @@
|
|||||||
|
// Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
|
||||||
|
// file at the top-level directory of this distribution and at
|
||||||
|
// http://rust-lang.org/COPYRIGHT.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||||
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||||
|
// option. This file may not be copied, modified, or distributed
|
||||||
|
// except according to those terms.
|
||||||
|
|
||||||
|
use option::Option::{self, Some};
|
||||||
|
use marker::Sized;
|
||||||
|
|
||||||
|
use super::Iterator;
|
||||||
|
|
||||||
|
/// 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="a collection of type `{Self}` cannot be \
|
||||||
|
built from an iterator over elements of type `{A}`"]
|
||||||
|
pub trait FromIterator<A>: Sized {
|
||||||
|
/// Creates a value from an iterator.
|
||||||
|
///
|
||||||
|
/// See the [module-level documentation] for more.
|
||||||
|
///
|
||||||
|
/// [module-level documentation]: trait.FromIterator.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();
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(1), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(2), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(3), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(None, n);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// 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);
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[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]: trait.IntoIterator.html
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let v = vec![1, 2, 3];
|
||||||
|
///
|
||||||
|
/// let mut iter = v.into_iter();
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(1), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(2), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(Some(3), n);
|
||||||
|
///
|
||||||
|
/// let n = iter.next();
|
||||||
|
/// assert_eq!(None, n);
|
||||||
|
/// ```
|
||||||
|
#[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.
|
||||||
|
///
|
||||||
|
/// # 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// interchangable for this purpose.
|
||||||
|
///
|
||||||
|
/// [`Iterator`]: trait.Iterator.html
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let numbers = vec![1, 2, 3];
|
||||||
|
///
|
||||||
|
/// let mut iter = numbers.iter();
|
||||||
|
///
|
||||||
|
/// assert_eq!(Some(&1), iter.next());
|
||||||
|
/// assert_eq!(Some(&3), iter.next_back());
|
||||||
|
/// assert_eq!(Some(&2), iter.next_back());
|
||||||
|
/// assert_eq!(None, iter.next());
|
||||||
|
/// assert_eq!(None, iter.next_back());
|
||||||
|
/// ```
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
pub trait DoubleEndedIterator: Iterator {
|
||||||
|
/// An iterator able to yield elements from both ends.
|
||||||
|
///
|
||||||
|
/// As this is the only method for this trait, the [trait-level] docs
|
||||||
|
/// contain more details.
|
||||||
|
///
|
||||||
|
/// [trait-level]: trait.DoubleEndedIterator.html
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// Basic usage:
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// let numbers = vec![1, 2, 3];
|
||||||
|
///
|
||||||
|
/// let mut iter = numbers.iter();
|
||||||
|
///
|
||||||
|
/// assert_eq!(Some(&1), iter.next());
|
||||||
|
/// assert_eq!(Some(&3), iter.next_back());
|
||||||
|
/// assert_eq!(Some(&2), iter.next_back());
|
||||||
|
/// 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>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 already have the number of iterations, so we can use it directly.
|
||||||
|
/// fn len(&self) -> usize {
|
||||||
|
/// self.count
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // And now we can use it!
|
||||||
|
///
|
||||||
|
/// let counter = Counter::new();
|
||||||
|
///
|
||||||
|
/// assert_eq!(0, counter.len());
|
||||||
|
/// ```
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
pub trait ExactSizeIterator: Iterator {
|
||||||
|
#[inline]
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
/// 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());
|
||||||
|
/// ```
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[stable(feature = "rust1", since = "1.0.0")]
|
||||||
|
impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user