aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorpravic <[email protected]>2016-04-29 21:16:15 +0300
committerpravic <[email protected]>2016-04-29 21:16:15 +0300
commit77e9a3167b4aaadf3583a0c1d1ee0d9e63c9a000 (patch)
tree710e445d56a1a582b8eff19b7b4b180276eae122
parenttweak: /driver option specifies /fixed:no implicitly as well (diff)
downloadkmd-env-rs-77e9a3167b4aaadf3583a0c1d1ee0d9e63c9a000.tar.xz
kmd-env-rs-77e9a3167b4aaadf3583a0c1d1ee0d9e63c9a000.zip
update libcore to 2016-04-29 nightly
-rw-r--r--libcollections/binary_heap.rs94
-rw-r--r--libcollections/btree/map.rs189
-rw-r--r--libcollections/btree/node.rs320
-rw-r--r--libcollections/btree/set.rs41
-rw-r--r--libcollections/fmt.rs15
-rw-r--r--libcollections/lib.rs10
-rw-r--r--libcollections/linked_list.rs24
-rw-r--r--libcollections/slice.rs41
-rw-r--r--libcollections/str.rs33
-rw-r--r--libcollections/string.rs33
-rw-r--r--libcollections/vec.rs13
-rw-r--r--libcollections/vec_deque.rs190
-rw-r--r--libcore/cell.rs7
-rw-r--r--libcore/char.rs52
-rw-r--r--libcore/clone.rs13
-rw-r--r--libcore/cmp.rs2
-rw-r--r--libcore/default.rs2
-rw-r--r--libcore/fmt/builders.rs2
-rw-r--r--libcore/fmt/mod.rs9
-rw-r--r--libcore/intrinsics.rs31
-rw-r--r--libcore/iter.rs5007
-rw-r--r--libcore/iter/iterator.rs2111
-rw-r--r--libcore/iter/mod.rs1657
-rw-r--r--libcore/iter/range.rs548
-rw-r--r--libcore/iter/sources.rs270
-rw-r--r--libcore/iter/traits.rs526
-rw-r--r--libcore/lib.rs2
-rw-r--r--libcore/macros.rs2
-rw-r--r--libcore/num/flt2dec/decoder.rs3
-rw-r--r--libcore/num/mod.rs121
-rw-r--r--libcore/ops.rs43
-rw-r--r--libcore/option.rs1
-rw-r--r--libcore/ptr.rs119
-rw-r--r--libcore/raw.rs10
-rw-r--r--libcore/result.rs47
-rw-r--r--libcore/slice.rs118
-rw-r--r--libcore/str/mod.rs44
-rw-r--r--libcore/sync/atomic.rs24
-rw-r--r--librustc_unicode/char.rs55
39 files changed, 6504 insertions, 5325 deletions
diff --git a/libcollections/binary_heap.rs b/libcollections/binary_heap.rs
index c9dd1ef..43c6e6e 100644
--- a/libcollections/binary_heap.rs
+++ b/libcollections/binary_heap.rs
@@ -153,12 +153,15 @@
use core::iter::FromIterator;
use core::mem::swap;
+use core::mem::size_of;
use core::ptr;
use core::fmt;
use slice;
use vec::{self, Vec};
+use super::SpecExtend;
+
/// A priority queue implemented with a binary heap.
///
/// This will be a max-heap.
@@ -738,6 +741,71 @@ impl<T: Ord> BinaryHeap<T> {
pub fn clear(&mut self) {
self.drain();
}
+
+ fn rebuild(&mut self) {
+ let mut n = self.len() / 2;
+ while n > 0 {
+ n -= 1;
+ self.sift_down(n);
+ }
+ }
+
+ /// Moves all the elements of `other` into `self`, leaving `other` empty.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// #![feature(binary_heap_append)]
+ ///
+ /// use std::collections::BinaryHeap;
+ ///
+ /// let v = vec![-10, 1, 2, 3, 3];
+ /// let mut a = BinaryHeap::from(v);
+ ///
+ /// let v = vec![-20, 5, 43];
+ /// let mut b = BinaryHeap::from(v);
+ ///
+ /// a.append(&mut b);
+ ///
+ /// assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
+ /// assert!(b.is_empty());
+ /// ```
+ #[unstable(feature = "binary_heap_append",
+ reason = "needs to be audited",
+ issue = "32526")]
+ pub fn append(&mut self, other: &mut Self) {
+ if self.len() < other.len() {
+ swap(self, other);
+ }
+
+ if other.is_empty() {
+ return;
+ }
+
+ #[inline(always)]
+ fn log2_fast(x: usize) -> usize {
+ 8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
+ }
+
+ // `rebuild` takes O(len1 + len2) operations
+ // and about 2 * (len1 + len2) comparisons in the worst case
+ // while `extend` takes O(len2 * log_2(len1)) operations
+ // and about 1 * len2 * log_2(len1) comparisons in the worst case,
+ // assuming len1 >= len2.
+ #[inline]
+ fn better_to_rebuild(len1: usize, len2: usize) -> bool {
+ 2 * (len1 + len2) < len2 * log2_fast(len1)
+ }
+
+ if better_to_rebuild(self.len(), other.len()) {
+ self.data.append(&mut other.data);
+ self.rebuild();
+ } else {
+ self.extend(other.drain());
+ }
+ }
}
/// Hole represents a hole in a slice i.e. an index without valid value
@@ -851,6 +919,7 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
/// An iterator that moves out of a `BinaryHeap`.
#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
pub struct IntoIter<T> {
iter: vec::IntoIter<T>,
}
@@ -917,11 +986,7 @@ impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
impl<T: Ord> From<Vec<T>> for BinaryHeap<T> {
fn from(vec: Vec<T>) -> BinaryHeap<T> {
let mut heap = BinaryHeap { data: vec };
- let mut n = heap.len() / 2;
- while n > 0 {
- n -= 1;
- heap.sift_down(n);
- }
+ heap.rebuild();
heap
}
}
@@ -980,7 +1045,26 @@ impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BinaryHeap<T> {
+ #[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
+ <Self as SpecExtend<I>>::spec_extend(self, iter);
+ }
+}
+
+impl<T: Ord, I: IntoIterator<Item = T>> SpecExtend<I> for BinaryHeap<T> {
+ default fn spec_extend(&mut self, iter: I) {
+ self.extend_desugared(iter.into_iter());
+ }
+}
+
+impl<T: Ord> SpecExtend<BinaryHeap<T>> for BinaryHeap<T> {
+ fn spec_extend(&mut self, ref mut other: BinaryHeap<T>) {
+ self.append(other);
+ }
+}
+
+impl<T: Ord> BinaryHeap<T> {
+ fn extend_desugared<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
diff --git a/libcollections/btree/map.rs b/libcollections/btree/map.rs
index de40568..20ef273 100644
--- a/libcollections/btree/map.rs
+++ b/libcollections/btree/map.rs
@@ -11,7 +11,7 @@
use core::cmp::Ordering;
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
-use core::iter::FromIterator;
+use core::iter::{FromIterator, Peekable};
use core::marker::PhantomData;
use core::ops::Index;
use core::{fmt, intrinsics, mem, ptr};
@@ -348,6 +348,12 @@ pub struct OccupiedEntry<'a, K: 'a, V: 'a> {
_marker: PhantomData<&'a mut (K, V)>,
}
+// An iterator for merging two sorted sequences into one
+struct MergeIter<K, V, I: Iterator<Item=(K, V)>> {
+ left: Peekable<I>,
+ right: Peekable<I>,
+}
+
impl<K: Ord, V> BTreeMap<K, V> {
/// Makes a new empty BTreeMap with a reasonable choice for B.
///
@@ -535,6 +541,62 @@ impl<K: Ord, V> BTreeMap<K, V> {
}
}
+ /// Moves all elements from `other` into `Self`, leaving `other` empty.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(btree_append)]
+ /// use std::collections::BTreeMap;
+ ///
+ /// let mut a = BTreeMap::new();
+ /// a.insert(1, "a");
+ /// a.insert(2, "b");
+ /// a.insert(3, "c");
+ ///
+ /// let mut b = BTreeMap::new();
+ /// b.insert(3, "d");
+ /// b.insert(4, "e");
+ /// b.insert(5, "f");
+ ///
+ /// a.append(&mut b);
+ ///
+ /// assert_eq!(a.len(), 5);
+ /// assert_eq!(b.len(), 0);
+ ///
+ /// assert_eq!(a[&1], "a");
+ /// assert_eq!(a[&2], "b");
+ /// assert_eq!(a[&3], "d");
+ /// assert_eq!(a[&4], "e");
+ /// assert_eq!(a[&5], "f");
+ /// ```
+ #[unstable(feature = "btree_append", reason = "recently added as part of collections reform 2",
+ issue = "19986")]
+ pub fn append(&mut self, other: &mut Self) {
+ // Do we have to append anything at all?
+ if other.len() == 0 {
+ return;
+ }
+
+ // We can just swap `self` and `other` if `self` is empty.
+ if self.len() == 0 {
+ mem::swap(self, other);
+ return;
+ }
+
+ // First, we merge `self` and `other` into a sorted sequence in linear time.
+ let self_iter = mem::replace(self, BTreeMap::new()).into_iter();
+ let other_iter = mem::replace(other, BTreeMap::new()).into_iter();
+ let iter = MergeIter {
+ left: self_iter.peekable(),
+ right: other_iter.peekable(),
+ };
+
+ // Second, we build a tree from the sorted sequence in linear time.
+ self.from_sorted_iter(iter);
+ self.fix_right_edge();
+ }
+
/// Constructs a double-ended iterator over a sub-range of elements in the map, starting
/// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
/// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
@@ -724,6 +786,76 @@ impl<K: Ord, V> BTreeMap<K, V> {
})
}
}
+
+ fn from_sorted_iter<I: Iterator<Item=(K, V)>>(&mut self, iter: I) {
+ let mut cur_node = last_leaf_edge(self.root.as_mut()).into_node();
+ // Iterate through all key-value pairs, pushing them into nodes at the right level.
+ for (key, value) in iter {
+ // Try to push key-value pair into the current leaf node.
+ if cur_node.len() < node::CAPACITY {
+ cur_node.push(key, value);
+ } else {
+ // No space left, go up and push there.
+ let mut open_node;
+ let mut test_node = cur_node.forget_type();
+ loop {
+ match test_node.ascend() {
+ Ok(parent) => {
+ let parent = parent.into_node();
+ if parent.len() < node::CAPACITY {
+ // Found a node with space left, push here.
+ open_node = parent;
+ break;
+ } else {
+ // Go up again.
+ test_node = parent.forget_type();
+ }
+ },
+ Err(node) => {
+ // We are at the top, create a new root node and push there.
+ open_node = node.into_root_mut().push_level();
+ break;
+ },
+ }
+ }
+
+ // Push key-value pair and new right subtree.
+ let tree_height = open_node.height() - 1;
+ let mut right_tree = node::Root::new_leaf();
+ for _ in 0..tree_height {
+ right_tree.push_level();
+ }
+ open_node.push(key, value, right_tree);
+
+ // Go down to the right-most leaf again.
+ cur_node = last_leaf_edge(open_node.forget_type()).into_node();
+ }
+
+ self.length += 1;
+ }
+ }
+
+ fn fix_right_edge(&mut self) {
+ // Handle underfull nodes, start from the top.
+ let mut cur_node = self.root.as_mut();
+ while let Internal(internal) = cur_node.force() {
+ // Check if right-most child is underfull.
+ let mut last_edge = internal.last_edge();
+ let right_child_len = last_edge.reborrow().descend().len();
+ if right_child_len < node::CAPACITY / 2 {
+ // We need to steal.
+ let mut last_kv = match last_edge.left_kv() {
+ Ok(left) => left,
+ Err(_) => unreachable!(),
+ };
+ last_kv.bulk_steal_left(node::CAPACITY/2 - right_child_len);
+ last_edge = last_kv.right_edge();
+ }
+
+ // Go further down.
+ cur_node = last_edge.descend();
+ }
+ }
}
impl<'a, K: 'a, V: 'a> IntoIterator for &'a BTreeMap<K, V> {
@@ -1690,32 +1822,41 @@ fn handle_underfull_node<'a, K, V>(node: NodeRef<marker::Mut<'a>,
};
if handle.can_merge() {
- return Merged(handle.merge().into_node());
+ Merged(handle.merge().into_node())
} else {
- unsafe {
- let (k, v, edge) = if is_left {
- handle.reborrow_mut().left_edge().descend().pop()
- } else {
- handle.reborrow_mut().right_edge().descend().pop_front()
- };
+ if is_left {
+ handle.steal_left();
+ } else {
+ handle.steal_right();
+ }
+ Stole(handle.into_node())
+ }
+}
- let k = mem::replace(handle.reborrow_mut().into_kv_mut().0, k);
- let v = mem::replace(handle.reborrow_mut().into_kv_mut().1, v);
+impl<K: Ord, V, I: Iterator<Item=(K, V)>> Iterator for MergeIter<K, V, I> {
+ type Item = (K, V);
- // FIXME: reuse cur_node?
- if is_left {
- match handle.reborrow_mut().right_edge().descend().force() {
- Leaf(mut leaf) => leaf.push_front(k, v),
- Internal(mut internal) => internal.push_front(k, v, edge.unwrap())
- }
- } else {
- match handle.reborrow_mut().left_edge().descend().force() {
- Leaf(mut leaf) => leaf.push(k, v),
- Internal(mut internal) => internal.push(k, v, edge.unwrap())
- }
- }
- }
+ fn next(&mut self) -> Option<(K, V)> {
+ let res = match (self.left.peek(), self.right.peek()) {
+ (Some(&(ref left_key, _)), Some(&(ref right_key, _))) => left_key.cmp(right_key),
+ (Some(_), None) => Ordering::Less,
+ (None, Some(_)) => Ordering::Greater,
+ (None, None) => return None,
+ };
- return Stole(handle.into_node());
+ // Check which elements comes first and only advance the corresponding iterator.
+ // If two keys are equal, take the value from `right`.
+ match res {
+ Ordering::Less => {
+ self.left.next()
+ },
+ Ordering::Greater => {
+ self.right.next()
+ },
+ Ordering::Equal => {
+ self.left.next();
+ self.right.next()
+ },
+ }
}
}
diff --git a/libcollections/btree/node.rs b/libcollections/btree/node.rs
index 8ae23a6..ca1cf6b 100644
--- a/libcollections/btree/node.rs
+++ b/libcollections/btree/node.rs
@@ -31,6 +31,16 @@
// Since Rust doesn't actually have dependent types and polymorphic recursion,
// we make do with lots of unsafety.
+// A major goal of this module is to avoid complexity by treating the tree as a generic (if
+// weirdly shaped) container and avoiding dealing with most of the B-Tree invariants. As such,
+// this module doesn't care whether the entries are sorted, which nodes can be underfull, or
+// even what underfull means. However, we do rely on a few invariants:
+//
+// - Trees must have uniform depth/height. This means that every path down to a leaf from a
+// given node has exactly the same length.
+// - A node of length `n` has `n` keys, `n` values, and (in an internal node) `n + 1` edges.
+// This implies that even an empty internal node has at least one edge.
+
use alloc::heap;
use core::marker::PhantomData;
use core::mem;
@@ -43,17 +53,43 @@ use boxed::Box;
const B: usize = 6;
pub const CAPACITY: usize = 2 * B - 1;
+/// The underlying representation of leaf nodes. Note that it is often unsafe to actually store
+/// these, since only the first `len` keys and values are assumed to be initialized. As such,
+/// these should always be put behind pointers, and specifically behind `BoxedNode` in the owned
+/// case.
+///
+/// See also rust-lang/rfcs#197, which would make this structure significantly more safe by
+/// avoiding accidentally dropping unused and uninitialized keys and values.
struct LeafNode<K, V> {
+ /// The arrays storing the actual data of the node. Only the first `len` elements of each
+ /// array are initialized and valid.
keys: [K; CAPACITY],
vals: [V; CAPACITY],
+
+ /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`.
+ /// This either points to an actual node or is null.
parent: *const InternalNode<K, V>,
+
+ /// This node's index into the parent node's `edges` array.
+ /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`.
+ /// This is only guaranteed to be initialized when `parent` is nonnull.
parent_idx: u16,
+
+ /// The number of keys and values this node stores.
+ ///
+ /// This is at the end of the node's representation and next to `parent_idx` to encourage
+ /// the compiler to join `len` and `parent_idx` into the same 32-bit word, reducing space
+ /// overhead.
len: u16,
}
impl<K, V> LeafNode<K, V> {
+ /// Creates a new `LeafNode`. Unsafe because all nodes should really be hidden behind
+ /// `BoxedNode`, preventing accidental dropping of uninitialized keys and values.
unsafe fn new() -> Self {
LeafNode {
+ // As a general policy, we leave fields uninitialized if they can be, as this should
+ // be both slightly faster and easier to track in Valgrind.
keys: mem::uninitialized(),
vals: mem::uninitialized(),
parent: ptr::null(),
@@ -63,15 +99,28 @@ impl<K, V> LeafNode<K, V> {
}
}
-// We use repr(C) so that a pointer to an internal node can be
-// directly used as a pointer to a leaf node
+/// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden
+/// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an
+/// `InternalNode` can be directly casted to a pointer to the underlying `LeafNode` portion of the
+/// node, allowing code to act on leaf and internal nodes generically without having to even check
+/// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`.
#[repr(C)]
struct InternalNode<K, V> {
data: LeafNode<K, V>,
+
+ /// The pointers to the children of this node. `len + 1` of these are considered
+ /// initialized and valid.
edges: [BoxedNode<K, V>; 2 * B],
}
impl<K, V> InternalNode<K, V> {
+ /// Creates a new `InternalNode`.
+ ///
+ /// This is unsafe for two reasons. First, it returns an `InternalNode` by value, risking
+ /// dropping of uninitialized fields. Second, an invariant of internal nodes is that `len + 1`
+ /// edges are initialized and valid, meaning that even when the node is empty (having a
+ /// `len` of 0), there must be one initialized and valid edge. This function does not set up
+ /// such an edge.
unsafe fn new() -> Self {
InternalNode {
data: LeafNode::new(),
@@ -80,8 +129,12 @@ impl<K, V> InternalNode<K, V> {
}
}
+/// An owned pointer to a node. This basically is either `Box<LeafNode<K, V>>` or
+/// `Box<InternalNode<K, V>>`. However, it contains no information as to which of the two types
+/// of nodes is acutally behind the box, and, partially due to this lack of information, has no
+/// destructor.
struct BoxedNode<K, V> {
- ptr: Unique<LeafNode<K, V>> // we don't know if this points to a leaf node or an internal node
+ ptr: Unique<LeafNode<K, V>>
}
impl<K, V> BoxedNode<K, V> {
@@ -156,7 +209,7 @@ impl<K, V> Root<K, V> {
}
}
- /// Add a new internal node with a single edge, pointing to the previous root, and make that
+ /// Adds a new internal node with a single edge, pointing to the previous root, and make that
/// new node the root. This increases the height by 1 and is the opposite of `pop_level`.
pub fn push_level(&mut self)
-> NodeRef<marker::Mut, K, V, marker::Internal> {
@@ -180,7 +233,7 @@ impl<K, V> Root<K, V> {
ret
}
- /// Remove the root node, using its first child as the new root. This cannot be called when
+ /// Removes the root node, using its first child as the new root. This cannot be called when
/// the tree consists only of a leaf node. As it is intended only to be called when the root
/// has only one edge, no cleanup is done on any of the other children are elements of the root.
/// This decreases the height by 1 and is the opposite of `push_level`.
@@ -229,6 +282,7 @@ impl<K, V> Root<K, V> {
pub struct NodeRef<BorrowType, K, V, Type> {
height: usize,
node: NonZero<*const LeafNode<K, V>>,
+ // This is null unless the borrow type is `Mut`
root: *const Root<K, V>,
_marker: PhantomData<(BorrowType, Type)>
}
@@ -268,10 +322,20 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
+ /// Finds the length of the node. This is the number of keys or values. In an
+ /// internal node, the number of edges is `len() + 1`.
pub fn len(&self) -> usize {
self.as_leaf().len as usize
}
+ /// Returns the height of this node in the whole tree. Zero height denotes the
+ /// leaf level.
+ pub fn height(&self) -> usize {
+ self.height
+ }
+
+ /// Removes any static information about whether this node is a `Leaf` or an
+ /// `Internal` node.
pub fn forget_type(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
NodeRef {
height: self.height,
@@ -281,6 +345,7 @@ impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
}
}
+ /// Temporarily takes out another, immutable reference to the same node.
fn reborrow<'a>(&'a self) -> NodeRef<marker::Immut<'a>, K, V, Type> {
NodeRef {
height: self.height,
@@ -304,6 +369,13 @@ impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
self.reborrow().into_slices().1
}
+ /// Finds the parent of the current node. Returns `Ok(handle)` if the current
+ /// node actually has a parent, where `handle` points to the edge of the parent
+ /// that points to the current node. Returns `Err(self)` if the current node has
+ /// no parent, giving back the original `NodeRef`.
+ ///
+ /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
+ /// both, upon success, do nothing.
pub fn ascend(self) -> Result<
Handle<
NodeRef<
@@ -344,6 +416,9 @@ impl<BorrowType, K, V, Type> NodeRef<BorrowType, K, V, Type> {
}
impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
+ /// Similar to `ascend`, gets a reference to a node's parent node, but also
+ /// deallocate the current node in the process. This is unsafe because the
+ /// current node will still be accessible despite being deallocated.
pub unsafe fn deallocate_and_ascend(self) -> Option<
Handle<
NodeRef<
@@ -362,6 +437,9 @@ impl<K, V> NodeRef<marker::Owned, K, V, marker::Leaf> {
}
impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
+ /// Similar to `ascend`, gets a reference to a node's parent node, but also
+ /// deallocate the current node in the process. This is unsafe because the
+ /// current node will still be accessible despite being deallocated.
pub unsafe fn deallocate_and_ascend(self) -> Option<
Handle<
NodeRef<
@@ -384,6 +462,8 @@ impl<K, V> NodeRef<marker::Owned, K, V, marker::Internal> {
}
impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
+ /// Unsafely asserts to the compiler some static information about whether this
+ /// node is a `Leaf`.
unsafe fn cast_unchecked<NewType>(&mut self)
-> NodeRef<marker::Mut, K, V, NewType> {
@@ -395,6 +475,16 @@ impl<'a, K, V, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
}
}
+ /// Temporarily takes out another, mutable reference to the same node. Beware, as
+ /// this method is very dangerous, doubly so since it may not immediately appear
+ /// dangerous.
+ ///
+ /// Because mutable pointers can roam anywhere around the tree and can even (through
+ /// `into_root_mut`) mess with the root of the tree, the result of `reborrow_mut`
+ /// can easily be used to make the original mutable pointer dangling, or, in the case
+ /// of a reborrowed handle, out of bounds.
+ // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` that restricts
+ // the use of `ascend` and `into_root_mut` on reborrowed pointers, preventing this unsafety.
unsafe fn reborrow_mut(&mut self) -> NodeRef<marker::Mut, K, V, Type> {
NodeRef {
height: self.height,
@@ -437,6 +527,8 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Immut<'a>, K, V, Type> {
}
impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
+ /// Gets a mutable reference to the root itself. This is useful primarily when the
+ /// height of the tree needs to be adjusted. Never call this on a reborrowed pointer.
pub fn into_root_mut(self) -> &'a mut Root<K, V> {
unsafe {
&mut *(self.root as *mut Root<K, V>)
@@ -460,6 +552,7 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef<marker::Mut<'a>, K, V, Type> {
}
impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
+ /// Adds a key/value pair the end of the node.
pub fn push(&mut self, key: K, val: V) {
// Necessary for correctness, but this is an internal module
debug_assert!(self.len() < CAPACITY);
@@ -474,6 +567,7 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
self.as_leaf_mut().len += 1;
}
+ /// Adds a key/value pair to the beginning of the node.
pub fn push_front(&mut self, key: K, val: V) {
// Necessary for correctness, but this is an internal module
debug_assert!(self.len() < CAPACITY);
@@ -488,6 +582,8 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Leaf> {
}
impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
+ /// Adds a key/value pair and an edge to go to the right of that pair to
+ /// the end of the node.
pub fn push(&mut self, key: K, val: V, edge: Root<K, V>) {
// Necessary for correctness, but this is an internal module
debug_assert!(edge.height == self.height - 1);
@@ -506,6 +602,8 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
}
}
+ /// Adds a key/value pair and an edge to go to the left of that pair to
+ /// the beginning of the node.
pub fn push_front(&mut self, key: K, val: V, edge: Root<K, V>) {
// Necessary for correctness, but this is an internal module
debug_assert!(edge.height == self.height - 1);
@@ -534,6 +632,8 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::Internal> {
}
impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
+ /// Removes a key/value pair from the end of this node. If this is an internal node,
+ /// also removes the edge that was to the right of that pair.
pub fn pop(&mut self) -> (K, V, Option<Root<K, V>>) {
// Necessary for correctness, but this is an internal module
debug_assert!(self.len() > 0);
@@ -558,6 +658,8 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
}
}
+ /// Removes a key/value pair from the beginning of this node. If this is an internal node,
+ /// also removes the edge that was to the left of that pair.
pub fn pop_front(&mut self) -> (K, V, Option<Root<K, V>>) {
// Necessary for correctness, but this is an internal module
debug_assert!(self.len() > 0);
@@ -597,6 +699,7 @@ impl<'a, K, V> NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal> {
}
impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
+ /// Checks whether a node is an `Internal` node or a `Leaf` node.
pub fn force(self) -> ForceResult<
NodeRef<BorrowType, K, V, marker::Leaf>,
NodeRef<BorrowType, K, V, marker::Internal>
@@ -619,6 +722,14 @@ impl<BorrowType, K, V> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
}
}
+/// A reference to a specific key/value pair or edge within a node. The `Node` parameter
+/// must be a `NodeRef`, while the `Type` can either be `KV` (signifying a handle on a key/value
+/// pair) or `Edge` (signifying a handle on an edge).
+///
+/// Note that even `Leaf` nodes can have `Edge` handles. Instead of representing a pointer to
+/// a child node, these represent the spaces where child pointers would go between the key/value
+/// pairs. For example, in a node with length 2, there would be 3 possible edge locations - one
+/// to the left of the node, one between the two pairs, and one at the right of the node.
pub struct Handle<Node, Type> {
node: Node,
idx: usize,
@@ -626,6 +737,8 @@ pub struct Handle<Node, Type> {
}
impl<Node: Copy, Type> Copy for Handle<Node, Type> { }
+// We don't need the full generality of `#[derive(Clone)]`, as the only time `Node` will be
+// `Clone`able is when it is an immutable reference and therefore `Copy`.
impl<Node: Copy, Type> Clone for Handle<Node, Type> {
fn clone(&self) -> Self {
*self
@@ -633,12 +746,14 @@ impl<Node: Copy, Type> Clone for Handle<Node, Type> {
}
impl<Node, Type> Handle<Node, Type> {
+ /// Retrieves the node that contains the edge of key/value pair this handle pointes to.
pub fn into_node(self) -> Node {
self.node
}
}
impl<BorrowType, K, V, NodeType> Handle<NodeRef<BorrowType, K, V, NodeType>, marker::KV> {
+ /// Creates a new handle to a key/value pair in `node`. `idx` must be less than `node.len()`.
pub fn new_kv(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
// Necessary for correctness, but in a private module
debug_assert!(idx < node.len());
@@ -670,6 +785,7 @@ impl<BorrowType, K, V, NodeType, HandleType> PartialEq
impl<BorrowType, K, V, NodeType, HandleType>
Handle<NodeRef<BorrowType, K, V, NodeType>, HandleType> {
+ /// Temporarily takes out another, immutable handle on the same location.
pub fn reborrow(&self)
-> Handle<NodeRef<marker::Immut, K, V, NodeType>, HandleType> {
@@ -685,6 +801,16 @@ impl<BorrowType, K, V, NodeType, HandleType>
impl<'a, K, V, NodeType, HandleType>
Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, HandleType> {
+ /// Temporarily takes out another, mutable handle on the same location. Beware, as
+ /// this method is very dangerous, doubly so since it may not immediately appear
+ /// dangerous.
+ ///
+ /// Because mutable pointers can roam anywhere around the tree and can even (through
+ /// `into_root_mut`) mess with the root of the tree, the result of `reborrow_mut`
+ /// can easily be used to make the original mutable pointer dangling, or, in the case
+ /// of a reborrowed handle, out of bounds.
+ // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` that restricts
+ // the use of `ascend` and `into_root_mut` on reborrowed pointers, preventing this unsafety.
pub unsafe fn reborrow_mut(&mut self)
-> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
@@ -700,6 +826,8 @@ impl<'a, K, V, NodeType, HandleType>
impl<BorrowType, K, V, NodeType>
Handle<NodeRef<BorrowType, K, V, NodeType>, marker::Edge> {
+ /// Creates a new handle to an edge in `node`. `idx` must be less than or equal to
+ /// `node.len()`.
pub fn new_edge(node: NodeRef<BorrowType, K, V, NodeType>, idx: usize) -> Self {
// Necessary for correctness, but in a private module
debug_assert!(idx <= node.len());
@@ -733,6 +861,11 @@ impl<BorrowType, K, V, NodeType>
}
impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge> {
+ /// Inserts a new key/value pair between the key/value pairs to the right and left of
+ /// this edge. This method assumes that there is enough space in the node for the new
+ /// pair to fit.
+ ///
+ /// The returned pointer points to the inserted value.
fn insert_fit(&mut self, key: K, val: V) -> *mut V {
// Necessary for correctness, but in a private module
debug_assert!(self.node.len() < CAPACITY);
@@ -747,6 +880,10 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge
}
}
+ /// Inserts a new key/value pair between the key/value pairs to the right and left of
+ /// this edge. This method splits the node if there isn't enough room.
+ ///
+ /// The returned pointer points to the inserted value.
pub fn insert(mut self, key: K, val: V)
-> (InsertResult<'a, K, V, marker::Leaf>, *mut V) {
@@ -774,6 +911,8 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge
}
impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
+ /// Fixes the parent pointer and index in the child node below this edge. This is useful
+ /// when the ordering of edges has been changed, such as in the various `insert` methods.
fn correct_parent_link(mut self) {
let idx = self.idx as u16;
let ptr = self.node.as_internal_mut() as *mut _;
@@ -782,18 +921,24 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
child.as_leaf_mut().parent_idx = idx;
}
+ /// Unsafely asserts to the compiler some static information about whether the underlying
+ /// node of this handle is a `Leaf`.
unsafe fn cast_unchecked<NewType>(&mut self)
-> Handle<NodeRef<marker::Mut, K, V, NewType>, marker::Edge> {
Handle::new_edge(self.node.cast_unchecked(), self.idx)
}
+ /// Inserts a new key/value pair and an edge that will go to the right of that new pair
+ /// between this edge and the key/value pair to the right of this edge. This method assumes
+ /// that there is enough space in the node for the new pair to fit.
fn insert_fit(&mut self, key: K, val: V, edge: Root<K, V>) {
// Necessary for correctness, but in an internal module
debug_assert!(self.node.len() < CAPACITY);
debug_assert!(edge.height == self.node.height - 1);
unsafe {
+ // This cast is a lie, but it allows us to reuse the key/value insertion logic.
self.cast_unchecked::<marker::Leaf>().insert_fit(key, val);
slice_insert(
@@ -811,6 +956,9 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
}
}
+ /// Inserts a new key/value pair and an edge that will go to the right of that new pair
+ /// between this edge and the key/value pair to the right of this edge. This method splits
+ /// the node if there isn't enough room.
pub fn insert(mut self, key: K, val: V, edge: Root<K, V>)
-> InsertResult<'a, K, V, marker::Internal> {
@@ -843,6 +991,10 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
impl<BorrowType, K, V>
Handle<NodeRef<BorrowType, K, V, marker::Internal>, marker::Edge> {
+ /// Finds the node pointed to by this edge.
+ ///
+ /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should
+ /// both, upon success, do nothing.
pub fn descend(self) -> NodeRef<BorrowType, K, V, marker::LeafOrInternal> {
NodeRef {
height: self.node.height - 1,
@@ -885,6 +1037,13 @@ impl<'a, K, V, NodeType> Handle<NodeRef<marker::Mut<'a>, K, V, NodeType>, marker
}
impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV> {
+ /// Splits the underlying node into three parts:
+ ///
+ /// - The node is truncated to only contain the key/value pairs to the right of
+ /// this handle.
+ /// - The key and value pointed to by this handle and extracted.
+ /// - All the key/value pairs to the right of this handle are put into a newly
+ /// allocated node.
pub fn split(mut self)
-> (NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, K, V, Root<K, V>) {
unsafe {
@@ -920,6 +1079,8 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV>
}
}
+ /// Removes the key/value pair pointed to by this handle, returning the edge between the
+ /// now adjacent key/value pairs to the left and right of this handle.
pub fn remove(mut self)
-> (Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>, K, V) {
unsafe {
@@ -932,6 +1093,13 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::KV>
}
impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::KV> {
+ /// Splits the underlying node into three parts:
+ ///
+ /// - The node is truncated to only contain the edges and key/value pairs to the
+ /// right of this handle.
+ /// - The key and value pointed to by this handle and extracted.
+ /// - All the edges and key/value pairs to the right of this handle are put into
+ /// a newly allocated node.
pub fn split(mut self)
-> (NodeRef<marker::Mut<'a>, K, V, marker::Internal>, K, V, Root<K, V>) {
unsafe {
@@ -979,6 +1147,9 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
}
}
+ /// Returns whether it is valid to call `.merge()`, i.e., whether there is enough room in
+ /// a node to hold the combination of the nodes to the left and right of this handle along
+ /// with the key/value pair at this handle.
pub fn can_merge(&self) -> bool {
(
self.reborrow()
@@ -993,6 +1164,11 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
) <= CAPACITY
}
+ /// Combines the node immediately to the left of this handle, the key/value pair pointed
+ /// to by this handle, and the node immediately to the right of this handle into one new
+ /// child of the underlying node, returning an edge referencing that new child.
+ ///
+ /// Assumes that this edge `.can_merge()`.
pub fn merge(mut self)
-> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
let self1 = unsafe { ptr::read(&self) };
@@ -1063,11 +1239,145 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
Handle::new_edge(self.node, self.idx)
}
}
+
+ /// This removes a key/value pair from the left child and replaces it with the key/value pair
+ /// pointed to by this handle while pushing the old key/value pair of this handle into the right
+ /// child.
+ pub fn steal_left(&mut self) {
+ unsafe {
+ let (k, v, edge) = self.reborrow_mut().left_edge().descend().pop();
+
+ let k = mem::replace(self.reborrow_mut().into_kv_mut().0, k);
+ let v = mem::replace(self.reborrow_mut().into_kv_mut().1, v);
+
+ match self.reborrow_mut().right_edge().descend().force() {
+ ForceResult::Leaf(mut leaf) => leaf.push_front(k, v),
+ ForceResult::Internal(mut internal) => internal.push_front(k, v, edge.unwrap())
+ }
+ }
+ }
+
+ /// This removes a key/value pair from the right child and replaces it with the key/value pair
+ /// pointed to by this handle while pushing the old key/value pair of this handle into the left
+ /// child.
+ pub fn steal_right(&mut self) {
+ unsafe {
+ let (k, v, edge) = self.reborrow_mut().right_edge().descend().pop_front();
+
+ let k = mem::replace(self.reborrow_mut().into_kv_mut().0, k);
+ let v = mem::replace(self.reborrow_mut().into_kv_mut().1, v);
+
+ match self.reborrow_mut().left_edge().descend().force() {
+ ForceResult::Leaf(mut leaf) => leaf.push(k, v),
+ ForceResult::Internal(mut internal) => internal.push(k, v, edge.unwrap())
+ }
+ }
+ }
+
+ /// This does stealing similar to `steal_left` but steals multiple elements at once.
+ pub fn bulk_steal_left(&mut self, n: usize) {
+ unsafe {
+ // Get raw pointers to left child's keys, values and edges.
+ let (left_len, left_k, left_v, left_e) = {
+ let mut left = self.reborrow_mut().left_edge().descend();
+
+ (left.len(),
+ left.keys_mut().as_mut_ptr(),
+ left.vals_mut().as_mut_ptr(),
+ match left.force() {
+ ForceResult::Leaf(_) => None,
+ ForceResult::Internal(mut i) => Some(i.as_internal_mut().edges.as_mut_ptr()),
+ })
+ };
+
+ // Get raw pointers to right child's keys, values and edges.
+ let (right_len, right_k, right_v, right_e) = {
+ let mut right = self.reborrow_mut().right_edge().descend();
+
+ (right.len(),
+ right.keys_mut().as_mut_ptr(),
+ right.vals_mut().as_mut_ptr(),
+ match right.force() {
+ ForceResult::Leaf(_) => None,
+ ForceResult::Internal(mut i) => Some(i.as_internal_mut().edges.as_mut_ptr()),
+ })
+ };
+
+ // Get raw pointers to parent's key and value.
+ let (parent_k, parent_v) = {
+ let kv = self.reborrow_mut().into_kv_mut();
+ (kv.0 as *mut K, kv.1 as *mut V)
+ };
+
+ // Make sure that we may steal safely.
+ debug_assert!(right_len + n <= CAPACITY);
+ debug_assert!(left_len >= n);
+
+ // Make room for stolen elements in right child.
+ ptr::copy(right_k,
+ right_k.offset(n as isize),
+ right_len);
+ ptr::copy(right_v,
+ right_v.offset(n as isize),
+ right_len);
+ if let Some(edges) = right_e {
+ ptr::copy(edges,
+ edges.offset(n as isize),
+ right_len+1);
+ }
+
+ // Move elements from the left child to the right one.
+ let left_ind = (left_len - n) as isize;
+ ptr::copy_nonoverlapping(left_k.offset(left_ind + 1),
+ right_k,
+ n - 1);
+ ptr::copy_nonoverlapping(left_v.offset(left_ind + 1),
+ right_v,
+ n - 1);
+ match (left_e, right_e) {
+ (Some(left), Some(right)) => {
+ ptr::copy_nonoverlapping(left.offset(left_ind + 1),
+ right,
+ n);
+ },
+ (Some(_), None) => unreachable!(),
+ (None, Some(_)) => unreachable!(),
+ (None, None) => {},
+ }
+
+ // Copy parent key/value pair to right child.
+ ptr::copy_nonoverlapping(parent_k,
+ right_k.offset(n as isize - 1),
+ 1);
+ ptr::copy_nonoverlapping(parent_v,
+ right_v.offset(n as isize - 1),
+ 1);
+ // Copy left-most stolen pair to parent.
+ ptr::copy_nonoverlapping(left_k.offset(left_ind),
+ parent_k,
+ 1);
+ ptr::copy_nonoverlapping(left_v.offset(left_ind),
+ parent_v,
+ 1);
+
+ // Fix lengths of left and right child and parent pointers in children of the right
+ // child.
+ self.reborrow_mut().left_edge().descend().as_leaf_mut().len -= n as u16;
+ let mut right = self.reborrow_mut().right_edge().descend();
+ right.as_leaf_mut().len += n as u16;
+ if let ForceResult::Internal(mut node) = right.force() {
+ for i in 0..(right_len+n+1) {
+ Handle::new_edge(node.reborrow_mut(), i as usize).correct_parent_link();
+ }
+ }
+ }
+ }
}
impl<BorrowType, K, V, HandleType>
Handle<NodeRef<BorrowType, K, V, marker::LeafOrInternal>, HandleType> {
+ /// Check whether the underlying node is an `Internal` node or a `Leaf` node.
pub fn force(self) -> ForceResult<
Handle<NodeRef<BorrowType, K, V, marker::Leaf>, HandleType>,
Handle<NodeRef<BorrowType, K, V, marker::Internal>, HandleType>
diff --git a/libcollections/btree/set.rs b/libcollections/btree/set.rs
index 23e0af8..5419d7a 100644
--- a/libcollections/btree/set.rs
+++ b/libcollections/btree/set.rs
@@ -379,7 +379,7 @@ impl<T: Ord> BTreeSet<T> {
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
- #[unstable(feature = "set_recovery", issue = "28050")]
+ #[stable(feature = "set_recovery", since = "1.9.0")]
pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
where T: Borrow<Q>,
Q: Ord
@@ -502,7 +502,7 @@ impl<T: Ord> BTreeSet<T> {
/// Adds a value to the set, replacing the existing value, if any, that is equal to the given
/// one. Returns the replaced value.
- #[unstable(feature = "set_recovery", issue = "28050")]
+ #[stable(feature = "set_recovery", since = "1.9.0")]
pub fn replace(&mut self, value: T) -> Option<T> {
Recover::replace(&mut self.map, value)
}
@@ -538,13 +538,48 @@ impl<T: Ord> BTreeSet<T> {
/// The value may be any borrowed form of the set's value type,
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
- #[unstable(feature = "set_recovery", issue = "28050")]
+ #[stable(feature = "set_recovery", since = "1.9.0")]
pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
where T: Borrow<Q>,
Q: Ord
{
Recover::take(&mut self.map, value)
}
+
+ /// Moves all elements from `other` into `Self`, leaving `other` empty.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(btree_append)]
+ /// use std::collections::BTreeSet;
+ ///
+ /// let mut a = BTreeSet::new();
+ /// a.insert(1);
+ /// a.insert(2);
+ /// a.insert(3);
+ ///
+ /// let mut b = BTreeSet::new();
+ /// b.insert(3);
+ /// b.insert(4);
+ /// b.insert(5);
+ ///
+ /// a.append(&mut b);
+ ///
+ /// assert_eq!(a.len(), 5);
+ /// assert_eq!(b.len(), 0);
+ ///
+ /// assert!(a.contains(&1));
+ /// assert!(a.contains(&2));
+ /// assert!(a.contains(&3));
+ /// assert!(a.contains(&4));
+ /// assert!(a.contains(&5));
+ /// ```
+ #[unstable(feature = "btree_append", reason = "recently added as part of collections reform 2",
+ issue = "19986")]
+ pub fn append(&mut self, other: &mut Self) {
+ self.map.append(&mut other.map);
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
diff --git a/libcollections/fmt.rs b/libcollections/fmt.rs
index e30e0b2..710a30f 100644
--- a/libcollections/fmt.rs
+++ b/libcollections/fmt.rs
@@ -395,8 +395,19 @@
//! `0`.
//!
//! The value for the width can also be provided as a `usize` in the list of
-//! parameters by using the `2$` syntax indicating that the second argument is a
-//! `usize` specifying the width.
+//! parameters by using the dollar syntax indicating that the second argument is
+//! a `usize` specifying the width, for example:
+//!
+//! ```
+//! // All of these print "Hello x !"
+//! println!("Hello {:5}!", "x");
+//! println!("Hello {:1$}!", "x", 5);
+//! println!("Hello {1:0$}!", 5, "x");
+//! ```
+//!
+//! Referring to an argument with the dollar syntax does not affect the "next
+//! argument" counter, so it's usually a good idea to refer to all arguments by
+//! their position explicitly.
//!
//! ## Precision
//!
diff --git a/libcollections/lib.rs b/libcollections/lib.rs
index 8e62b38..34e4a42 100644
--- a/libcollections/lib.rs
+++ b/libcollections/lib.rs
@@ -27,7 +27,7 @@
test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![cfg_attr(test, allow(deprecated))] // rand
-#![cfg_attr(not(test), feature(copy_from_slice))] // impl [T]
+#![cfg_attr(not(test), feature(slice_binary_search_by_key))] // impl [T]
#![cfg_attr(not(stage0), deny(warnings))]
#![feature(alloc)]
@@ -35,7 +35,6 @@
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
-#![feature(decode_utf16)]
#![feature(dropck_parametricity)]
#![feature(fmt_internals)]
#![feature(heap_api)]
@@ -133,3 +132,10 @@ pub enum Bound<T> {
/// An infinite endpoint. Indicates that there is no bound in this direction.
Unbounded,
}
+
+/// An intermediate trait for specialization of `Extend`.
+#[doc(hidden)]
+trait SpecExtend<I: IntoIterator> {
+ /// Extends `self` with the contents of the given iterator.
+ fn spec_extend(&mut self, iter: I);
+}
diff --git a/libcollections/linked_list.rs b/libcollections/linked_list.rs
index 85a4fa8..406b979 100644
--- a/libcollections/linked_list.rs
+++ b/libcollections/linked_list.rs
@@ -30,6 +30,8 @@ use core::mem;
use core::ops::{BoxPlace, InPlace, Place, Placer};
use core::ptr::{self, Shared};
+use super::SpecExtend;
+
/// A doubly-linked list.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct LinkedList<T> {
@@ -401,6 +403,16 @@ impl<T> LinkedList<T> {
*self = LinkedList::new()
}
+ /// Returns `true` if the `LinkedList` contains an element equal to the
+ /// given value.
+ #[unstable(feature = "linked_list_contains", reason = "recently added",
+ issue = "32630")]
+ pub fn contains(&self, x: &T) -> bool
+ where T: PartialEq<T>
+ {
+ self.iter().any(|e| e == x)
+ }
+
/// Provides a reference to the front element, or `None` if the list is
/// empty.
///
@@ -969,12 +981,24 @@ impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> Extend<A> for LinkedList<A> {
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
+ <Self as SpecExtend<T>>::spec_extend(self, iter);
+ }
+}
+
+impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
+ default fn spec_extend(&mut self, iter: I) {
for elt in iter {
self.push_back(elt);
}
}
}
+impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
+ fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
+ self.append(other);
+ }
+}
+
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
diff --git a/libcollections/slice.rs b/libcollections/slice.rs
index 8fa594c..588ad7a 100644
--- a/libcollections/slice.rs
+++ b/libcollections/slice.rs
@@ -741,6 +741,44 @@ impl<T> [T] {
core_slice::SliceExt::binary_search_by(self, f)
}
+ /// Binary search a sorted slice with a key extraction function.
+ ///
+ /// Assumes that the slice is sorted by the key, for instance with
+ /// `sort_by_key` using the same key extraction function.
+ ///
+ /// If a matching value is found then returns `Ok`, containing the
+ /// index for the matched element; if no match is found then `Err`
+ /// is returned, containing the index where a matching element could
+ /// be inserted while maintaining sorted order.
+ ///
+ /// # Examples
+ ///
+ /// Looks up a series of four elements in a slice of pairs sorted by
+ /// their second elements. The first is found, with a uniquely
+ /// determined position; the second and third are not found; the
+ /// fourth could match any position in `[1,4]`.
+ ///
+ /// ```rust
+ /// #![feature(slice_binary_search_by_key)]
+ /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
+ /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
+ /// (1, 21), (2, 34), (4, 55)];
+ ///
+ /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
+ /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
+ /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
+ /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
+ /// assert!(match r { Ok(1...4) => true, _ => false, });
+ /// ```
+ #[unstable(feature = "slice_binary_search_by_key", reason = "recently added", issue = "33018")]
+ #[inline]
+ pub fn binary_search_by_key<B, F>(&self, b: &B, f: F) -> Result<usize, usize>
+ where F: FnMut(&T) -> B,
+ B: Ord
+ {
+ core_slice::SliceExt::binary_search_by_key(self, b, f)
+ }
+
/// Sorts the slice, in place.
///
/// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
@@ -845,14 +883,13 @@ impl<T> [T] {
/// # Example
///
/// ```rust
- /// #![feature(copy_from_slice)]
/// let mut dst = [0, 0, 0];
/// let src = [1, 2, 3];
///
/// dst.copy_from_slice(&src);
/// assert_eq!(src, dst);
/// ```
- #[unstable(feature = "copy_from_slice", issue = "31755")]
+ #[stable(feature = "copy_from_slice", since = "1.9.0")]
pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
core_slice::SliceExt::copy_from_slice(self, src)
}
diff --git a/libcollections/str.rs b/libcollections/str.rs
index 9798e32..2059943 100644
--- a/libcollections/str.rs
+++ b/libcollections/str.rs
@@ -228,8 +228,6 @@ impl str {
/// # Examples
///
/// ```
- /// #![feature(str_char)]
- ///
/// let s = "Löwe 老虎 Léopard";
/// assert!(s.is_char_boundary(0));
/// // start of `老`
@@ -242,12 +240,7 @@ impl str {
/// // third byte of `老`
/// assert!(!s.is_char_boundary(8));
/// ```
- #[unstable(feature = "str_char",
- reason = "it is unclear whether this method pulls its weight \
- with the existence of the char_indices iterator or \
- this method may want to be replaced with checked \
- slicing",
- issue = "27754")]
+ #[stable(feature = "is_char_boundary", since = "1.9.0")]
#[inline]
pub fn is_char_boundary(&self, index: usize) -> bool {
core_str::StrExt::is_char_boundary(self, index)
@@ -374,6 +367,7 @@ impl str {
///
/// ```
/// #![feature(str_char)]
+ /// #![allow(deprecated)]
///
/// use std::str::CharRange;
///
@@ -408,6 +402,9 @@ impl str {
removed altogether",
issue = "27754")]
#[inline]
+ #[rustc_deprecated(reason = "use slicing plus chars() plus len_utf8",
+ since = "1.9.0")]
+ #[allow(deprecated)]
pub fn char_range_at(&self, start: usize) -> CharRange {
core_str::StrExt::char_range_at(self, start)
}
@@ -432,6 +429,7 @@ impl str {
///
/// ```
/// #![feature(str_char)]
+ /// #![allow(deprecated)]
///
/// use std::str::CharRange;
///
@@ -466,6 +464,9 @@ impl str {
eventually removed altogether",
issue = "27754")]
#[inline]
+ #[rustc_deprecated(reason = "use slicing plus chars().rev() plus len_utf8",
+ since = "1.9.0")]
+ #[allow(deprecated)]
pub fn char_range_at_reverse(&self, start: usize) -> CharRange {
core_str::StrExt::char_range_at_reverse(self, start)
}
@@ -481,6 +482,7 @@ impl str {
///
/// ```
/// #![feature(str_char)]
+ /// #![allow(deprecated)]
///
/// let s = "abπc";
/// assert_eq!(s.char_at(1), 'b');
@@ -495,6 +497,9 @@ impl str {
subslice",
issue = "27754")]
#[inline]
+ #[allow(deprecated)]
+ #[rustc_deprecated(reason = "use slicing plus chars()",
+ since = "1.9.0")]
pub fn char_at(&self, i: usize) -> char {
core_str::StrExt::char_at(self, i)
}
@@ -511,6 +516,7 @@ impl str {
///
/// ```
/// #![feature(str_char)]
+ /// #![allow(deprecated)]
///
/// let s = "abπc";
/// assert_eq!(s.char_at_reverse(1), 'a');
@@ -523,6 +529,9 @@ impl str {
cases generate panics",
issue = "27754")]
#[inline]
+ #[rustc_deprecated(reason = "use slicing plus chars().rev()",
+ since = "1.9.0")]
+ #[allow(deprecated)]
pub fn char_at_reverse(&self, i: usize) -> char {
core_str::StrExt::char_at_reverse(self, i)
}
@@ -541,6 +550,7 @@ impl str {
///
/// ```
/// #![feature(str_char)]
+ /// #![allow(deprecated)]
///
/// let s = "Łódź"; // \u{141}o\u{301}dz\u{301}
/// let (c, s1) = s.slice_shift_char().unwrap();
@@ -559,6 +569,9 @@ impl str {
and/or char_indices iterators",
issue = "27754")]
#[inline]
+ #[rustc_deprecated(reason = "use chars() plus Chars::as_str",
+ since = "1.9.0")]
+ #[allow(deprecated)]
pub fn slice_shift_char(&self) -> Option<(char, &str)> {
core_str::StrExt::slice_shift_char(self)
}
@@ -621,9 +634,9 @@ impl str {
/// Basic usage:
///
/// ```
- /// let s = "Per Martin-Löf";
+ /// let mut s = "Per Martin-Löf".to_string();
///
- /// let (first, last) = s.split_at(3);
+ /// let (first, last) = s.split_at_mut(3);
///
/// assert_eq!("Per", first);
/// assert_eq!(" Martin-Löf", last);
diff --git a/libcollections/string.rs b/libcollections/string.rs
index c84d849..306fad2 100644
--- a/libcollections/string.rs
+++ b/libcollections/string.rs
@@ -992,10 +992,12 @@ impl String {
/// Shortens this `String` to the specified length.
///
+ /// If `new_len` is greater than the string's current length, this has no
+ /// effect.
+ ///
/// # Panics
///
- /// Panics if `new_len` > current length, or if `new_len` does not lie on a
- /// [`char`] boundary.
+ /// Panics if `new_len` does not lie on a [`char`] boundary.
///
/// [`char`]: ../../std/primitive.char.html
///
@@ -1013,8 +1015,10 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn truncate(&mut self, new_len: usize) {
- assert!(self.is_char_boundary(new_len));
- self.vec.truncate(new_len)
+ if new_len <= self.len() {
+ assert!(self.is_char_boundary(new_len));
+ self.vec.truncate(new_len)
+ }
}
/// Removes the last character from the string buffer and returns it.
@@ -1037,14 +1041,13 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<char> {
- let len = self.len();
- if len == 0 {
- return None;
- }
-
- let ch = self.char_at_reverse(len);
+ let ch = match self.chars().rev().next() {
+ Some(ch) => ch,
+ None => return None,
+ };
+ let newlen = self.len() - ch.len_utf8();
unsafe {
- self.vec.set_len(len - ch.len_utf8());
+ self.vec.set_len(newlen);
}
Some(ch)
}
@@ -1075,11 +1078,13 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove(&mut self, idx: usize) -> char {
- let len = self.len();
- assert!(idx < len);
+ let ch = match self[idx..].chars().next() {
+ Some(ch) => ch,
+ None => panic!("cannot remove a char from the end of a string"),
+ };
- let ch = self.char_at(idx);
let next = idx + ch.len_utf8();
+ let len = self.len();
unsafe {
ptr::copy(self.vec.as_ptr().offset(next as isize),
self.vec.as_mut_ptr().offset(idx as isize),
diff --git a/libcollections/vec.rs b/libcollections/vec.rs
index dde5cbb..58d4a4e 100644
--- a/libcollections/vec.rs
+++ b/libcollections/vec.rs
@@ -75,6 +75,7 @@ use core::ops;
use core::ptr;
use core::slice;
+use super::SpecExtend;
use super::range::RangeArgument;
/// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
@@ -1390,10 +1391,22 @@ impl<'a, T> IntoIterator for &'a mut Vec<T> {
impl<T> Extend<T> for Vec<T> {
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
+ <Self as SpecExtend<I>>::spec_extend(self, iter);
+ }
+}
+
+impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
+ default fn spec_extend(&mut self, iter: I) {
self.extend_desugared(iter.into_iter())
}
}
+impl<T> SpecExtend<Vec<T>> for Vec<T> {
+ fn spec_extend(&mut self, ref mut other: Vec<T>) {
+ self.append(other);
+ }
+}
+
impl<T> Vec<T> {
fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
// This function should be the moral equivalent of:
diff --git a/libcollections/vec_deque.rs b/libcollections/vec_deque.rs
index 9e2b25d..84a0bbb 100644
--- a/libcollections/vec_deque.rs
+++ b/libcollections/vec_deque.rs
@@ -32,6 +32,7 @@ use core::cmp;
use alloc::raw_vec::RawVec;
use super::range::RangeArgument;
+use super::vec::Vec;
const INITIAL_CAPACITY: usize = 7; // 2^3 - 1
const MINIMUM_CAPACITY: usize = 1; // 2 - 1
@@ -872,6 +873,17 @@ impl<T> VecDeque<T> {
self.drain(..);
}
+ /// Returns `true` if the `VecDeque` contains an element equal to the
+ /// given value.
+ #[unstable(feature = "vec_deque_contains", reason = "recently added",
+ issue = "32630")]
+ pub fn contains(&self, x: &T) -> bool
+ where T: PartialEq<T>
+ {
+ let (a, b) = self.as_slices();
+ a.contains(x) || b.contains(x)
+ }
+
/// Provides a reference to the front element, or `None` if the sequence is
/// empty.
///
@@ -2121,6 +2133,106 @@ impl<T: fmt::Debug> fmt::Debug for VecDeque<T> {
}
}
+#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
+impl<T> From<Vec<T>> for VecDeque<T> {
+ fn from(mut other: Vec<T>) -> Self {
+ unsafe {
+ let other_buf = other.as_mut_ptr();
+ let mut buf = RawVec::from_raw_parts(other_buf, other.capacity());
+ let len = other.len();
+ mem::forget(other);
+
+ // We need to extend the buf if it's not a power of two, too small
+ // or doesn't have at least one free space
+ if !buf.cap().is_power_of_two()
+ || (buf.cap() < (MINIMUM_CAPACITY + 1))
+ || (buf.cap() == len)
+ {
+ let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
+ buf.reserve_exact(len, cap - len);
+ }
+
+ VecDeque {
+ tail: 0,
+ head: len,
+ buf: buf
+ }
+ }
+ }
+}
+
+#[stable(feature = "vecdeque_vec_conversions", since = "1.10.0")]
+impl<T> From<VecDeque<T>> for Vec<T> {
+ fn from(other: VecDeque<T>) -> Self {
+ unsafe {
+ let buf = other.buf.ptr();
+ let len = other.len();
+ let tail = other.tail;
+ let head = other.head;
+ let cap = other.cap();
+
+ // Need to move the ring to the front of the buffer, as vec will expect this.
+ if other.is_contiguous() {
+ ptr::copy(buf.offset(tail as isize), buf, len);
+ } else {
+ if (tail - head) >= cmp::min((cap - tail), head) {
+ // There is enough free space in the centre for the shortest block so we can
+ // do this in at most three copy moves.
+ if (cap - tail) > head {
+ // right hand block is the long one; move that enough for the left
+ ptr::copy(
+ buf.offset(tail as isize),
+ buf.offset((tail - head) as isize),
+ cap - tail);
+ // copy left in the end
+ ptr::copy(buf, buf.offset((cap - head) as isize), head);
+ // shift the new thing to the start
+ ptr::copy(buf.offset((tail-head) as isize), buf, len);
+ } else {
+ // left hand block is the long one, we can do it in two!
+ ptr::copy(buf, buf.offset((cap-tail) as isize), head);
+ ptr::copy(buf.offset(tail as isize), buf, cap-tail);
+ }
+ } else {
+ // Need to use N swaps to move the ring
+ // We can use the space at the end of the ring as a temp store
+
+ let mut left_edge: usize = 0;
+ let mut right_edge: usize = tail;
+
+ // The general problem looks like this
+ // GHIJKLM...ABCDEF - before any swaps
+ // ABCDEFM...GHIJKL - after 1 pass of swaps
+ // ABCDEFGHIJM...KL - swap until the left edge reaches the temp store
+ // - then restart the algorithm with a new (smaller) store
+ // Sometimes the temp store is reached when the right edge is at the end
+ // of the buffer - this means we've hit the right order with fewer swaps!
+ // E.g
+ // EF..ABCD
+ // ABCDEF.. - after four only swaps we've finished
+
+ while left_edge < len && right_edge != cap {
+ let mut right_offset = 0;
+ for i in left_edge..right_edge {
+ right_offset = (i - left_edge) % (cap - right_edge);
+ let src: isize = (right_edge + right_offset) as isize;
+ ptr::swap(buf.offset(i as isize), buf.offset(src));
+ }
+ let n_ops = right_edge - left_edge;
+ left_edge += n_ops;
+ right_edge += right_offset + 1;
+
+ }
+ }
+
+ }
+ let out = Vec::from_raw_parts(buf, len, cap);
+ mem::forget(other);
+ out
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use core::iter::Iterator;
@@ -2401,4 +2513,82 @@ mod tests {
}
}
}
+
+ #[test]
+ fn test_from_vec() {
+ use super::super::vec::Vec;
+ for cap in 0..35 {
+ for len in 0..cap + 1 {
+ let mut vec = Vec::with_capacity(cap);
+ vec.extend(0..len);
+
+ let vd = VecDeque::from(vec.clone());
+ assert!(vd.cap().is_power_of_two());
+ assert_eq!(vd.len(), vec.len());
+ assert!(vd.into_iter().eq(vec));
+ }
+ }
+ }
+
+ #[test]
+ fn test_vec_from_vecdeque() {
+ use super::super::vec::Vec;
+
+ fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) {
+ let mut vd = VecDeque::with_capacity(cap);
+ for _ in 0..offset {
+ vd.push_back(0);
+ vd.pop_front();
+ }
+ vd.extend(0..len);
+
+ let vec: Vec<_> = Vec::from(vd.clone());
+ assert_eq!(vec.len(), vd.len());
+ assert!(vec.into_iter().eq(vd));
+ }
+
+ for cap_pwr in 0..7 {
+ // Make capacity as a (2^x)-1, so that the ring size is 2^x
+ let cap = (2i32.pow(cap_pwr) - 1) as usize;
+
+ // In these cases there is enough free space to solve it with copies
+ for len in 0..((cap+1)/2) {
+ // Test contiguous cases
+ for offset in 0..(cap-len) {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+
+ // Test cases where block at end of buffer is bigger than block at start
+ for offset in (cap-len)..(cap-(len/2)) {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+
+ // Test cases where block at start of buffer is bigger than block at end
+ for offset in (cap-(len/2))..cap {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+ }
+
+ // Now there's not (necessarily) space to straighten the ring with simple copies,
+ // the ring will use swapping when:
+ // (cap + 1 - offset) > (cap + 1 - len) && (len - (cap + 1 - offset)) > (cap + 1 - len))
+ // right block size > free space && left block size > free space
+ for len in ((cap+1)/2)..cap {
+ // Test contiguous cases
+ for offset in 0..(cap-len) {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+
+ // Test cases where block at end of buffer is bigger than block at start
+ for offset in (cap-len)..(cap-(len/2)) {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+
+ // Test cases where block at start of buffer is bigger than block at end
+ for offset in (cap-(len/2))..cap {
+ create_vec_and_test_convert(cap, offset, len)
+ }
+ }
+ }
+ }
}
diff --git a/libcore/cell.rs b/libcore/cell.rs
index a1c7a29..257027d 100644
--- a/libcore/cell.rs
+++ b/libcore/cell.rs
@@ -859,3 +859,10 @@ impl<T: ?Sized> UnsafeCell<T> {
&self.value as *const T as *mut T
}
}
+
+#[stable(feature = "unsafe_cell_default", since = "1.9.0")]
+impl<T: Default> Default for UnsafeCell<T> {
+ fn default() -> UnsafeCell<T> {
+ UnsafeCell::new(Default::default())
+ }
+}
diff --git a/libcore/char.rs b/libcore/char.rs
index b2b1dc5..1404038 100644
--- a/libcore/char.rs
+++ b/libcore/char.rs
@@ -299,7 +299,20 @@ impl CharExt for char {
#[inline]
fn escape_unicode(self) -> EscapeUnicode {
- EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
+ let c = self as u32;
+
+ // or-ing 1 ensures that for c==0 the code computes that one
+ // digit should be printed and (which is the same) avoids the
+ // (31 - 32) underflow
+ let msb = 31 - (c | 1).leading_zeros();
+
+ // the index of the most significant hex digit
+ let ms_hex_digit = msb / 4;
+ EscapeUnicode {
+ c: self,
+ state: EscapeUnicodeState::Backslash,
+ hex_digit_idx: ms_hex_digit as usize,
+ }
}
#[inline]
@@ -392,7 +405,12 @@ impl CharExt for char {
#[stable(feature = "rust1", since = "1.0.0")]
pub struct EscapeUnicode {
c: char,
- state: EscapeUnicodeState
+ state: EscapeUnicodeState,
+
+ // The index of the next hex digit to be printed (0 if none),
+ // i.e. the number of remaining hex digits to be printed;
+ // increasing from the least significant digit: 0x543210
+ hex_digit_idx: usize,
}
#[derive(Clone, Debug)]
@@ -400,7 +418,7 @@ enum EscapeUnicodeState {
Backslash,
Type,
LeftBrace,
- Value(usize),
+ Value,
RightBrace,
Done,
}
@@ -420,19 +438,16 @@ impl Iterator for EscapeUnicode {
Some('u')
}
EscapeUnicodeState::LeftBrace => {
- let mut n = 0;
- while (self.c as u32) >> (4 * (n + 1)) != 0 {
- n += 1;
- }
- self.state = EscapeUnicodeState::Value(n);
+ self.state = EscapeUnicodeState::Value;
Some('{')
}
- EscapeUnicodeState::Value(offset) => {
- let c = from_digit(((self.c as u32) >> (offset * 4)) & 0xf, 16).unwrap();
- if offset == 0 {
+ EscapeUnicodeState::Value => {
+ let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf;
+ let c = from_digit(hex_digit, 16).unwrap();
+ if self.hex_digit_idx == 0 {
self.state = EscapeUnicodeState::RightBrace;
} else {
- self.state = EscapeUnicodeState::Value(offset - 1);
+ self.hex_digit_idx -= 1;
}
Some(c)
}
@@ -445,18 +460,15 @@ impl Iterator for EscapeUnicode {
}
fn size_hint(&self) -> (usize, Option<usize>) {
- let mut n = 0;
- while (self.c as usize) >> (4 * (n + 1)) != 0 {
- n += 1;
- }
let n = match self.state {
- EscapeUnicodeState::Backslash => n + 5,
- EscapeUnicodeState::Type => n + 4,
- EscapeUnicodeState::LeftBrace => n + 3,
- EscapeUnicodeState::Value(offset) => offset + 2,
+ EscapeUnicodeState::Backslash => 5,
+ EscapeUnicodeState::Type => 4,
+ EscapeUnicodeState::LeftBrace => 3,
+ EscapeUnicodeState::Value => 2,
EscapeUnicodeState::RightBrace => 1,
EscapeUnicodeState::Done => 0,
};
+ let n = n + self.hex_digit_idx;
(n, Some(n))
}
}
diff --git a/libcore/clone.rs b/libcore/clone.rs
index 6fb733f..ad2a205 100644
--- a/libcore/clone.rs
+++ b/libcore/clone.rs
@@ -75,6 +75,17 @@ pub trait Clone : Sized {
}
}
+// FIXME(aburka): this method is used solely by #[derive] to
+// assert that every component of a type implements Clone.
+//
+// This should never be called by user code.
+#[doc(hidden)]
+#[inline(always)]
+#[unstable(feature = "derive_clone_copy",
+ reason = "deriving hack, should not be public",
+ issue = "0")]
+pub fn assert_receiver_is_clone<T: Clone + ?Sized>(_: &T) {}
+
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Clone for &'a T {
/// Returns a shallow copy of the reference.
@@ -105,9 +116,7 @@ clone_impl! { u16 }
clone_impl! { u32 }
clone_impl! { u64 }
-#[cfg(not(disable_float))]
clone_impl! { f32 }
-#[cfg(not(disable_float))]
clone_impl! { f64 }
clone_impl! { () }
diff --git a/libcore/cmp.rs b/libcore/cmp.rs
index 49aa023..d3481ba 100644
--- a/libcore/cmp.rs
+++ b/libcore/cmp.rs
@@ -128,7 +128,7 @@ pub trait Eq: PartialEq<Self> {
/// let result = 2.cmp(&1);
/// assert_eq!(Ordering::Greater, result);
/// ```
-#[derive(Clone, Copy, PartialEq, Debug)]
+#[derive(Clone, Copy, PartialEq, Debug, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Ordering {
/// An ordering where a compared value is less [than another].
diff --git a/libcore/default.rs b/libcore/default.rs
index 4ec4fb6..12c4a5c 100644
--- a/libcore/default.rs
+++ b/libcore/default.rs
@@ -160,7 +160,5 @@ default_impl! { i16, 0 }
default_impl! { i32, 0 }
default_impl! { i64, 0 }
-#[cfg(not(disable_float))]
default_impl! { f32, 0.0f32 }
-#[cfg(not(disable_float))]
default_impl! { f64, 0.0f64 }
diff --git a/libcore/fmt/builders.rs b/libcore/fmt/builders.rs
index d337463..6cac80a 100644
--- a/libcore/fmt/builders.rs
+++ b/libcore/fmt/builders.rs
@@ -9,7 +9,7 @@
// except according to those terms.
use prelude::v1::*;
-use fmt::{self, Write, FlagV1};
+use fmt::{self, FlagV1};
struct PadAdapter<'a, 'b: 'a> {
fmt: &'a mut fmt::Formatter<'b>,
diff --git a/libcore/fmt/mod.rs b/libcore/fmt/mod.rs
index 3637238..0c824b5 100644
--- a/libcore/fmt/mod.rs
+++ b/libcore/fmt/mod.rs
@@ -17,7 +17,6 @@ use prelude::v1::*;
use cell::{UnsafeCell, Cell, RefCell, Ref, RefMut, BorrowState};
use marker::PhantomData;
use mem;
-#[cfg(not(disable_float))]
use num::flt2dec;
use ops::Deref;
use result;
@@ -61,7 +60,7 @@ pub type Result = result::Result<(), Error>;
/// occurred. Any extra information must be arranged to be transmitted through
/// some other means.
#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Copy, Clone, Debug)]
+#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Error;
/// A collection of methods that are required to format a message into a stream.
@@ -1024,7 +1023,6 @@ impl<'a> Formatter<'a> {
/// Takes the formatted parts and applies the padding.
/// Assumes that the caller already has rendered the parts with required precision,
/// so that `self.precision` can be ignored.
- #[cfg(not(disable_float))]
fn pad_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
if let Some(mut width) = self.width {
// for the sign-aware zero padding, we render the sign first and
@@ -1061,7 +1059,6 @@ impl<'a> Formatter<'a> {
}
}
- #[cfg(not(disable_float))]
fn write_formatted_parts(&mut self, formatted: &flt2dec::Formatted) -> Result {
fn write_bytes(buf: &mut Write, s: &[u8]) -> Result {
buf.write_str(unsafe { str::from_utf8_unchecked(s) })
@@ -1450,7 +1447,6 @@ impl<'a, T: ?Sized> Pointer for &'a mut T {
}
}
-#[cfg(not(disable_float))]
// Common code of floating point Debug and Display.
fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result
where T: flt2dec::DecodableFloat
@@ -1475,7 +1471,6 @@ fn float_to_decimal_common<T>(fmt: &mut Formatter, num: &T, negative_zero: bool)
fmt.pad_formatted_parts(&formatted)
}
-#[cfg(not(disable_float))]
// Common code of floating point LowerExp and UpperExp.
fn float_to_exponential_common<T>(fmt: &mut Formatter, num: &T, upper: bool) -> Result
where T: flt2dec::DecodableFloat
@@ -1529,9 +1524,7 @@ macro_rules! floating { ($ty:ident) => {
}
}
} }
-#[cfg(not(disable_float))]
floating! { f32 }
-#[cfg(not(disable_float))]
floating! { f64 }
// Implementation of Display/Debug for various core types
diff --git a/libcore/intrinsics.rs b/libcore/intrinsics.rs
index 4ab434d..45890cd 100644
--- a/libcore/intrinsics.rs
+++ b/libcore/intrinsics.rs
@@ -53,34 +53,14 @@ extern "rust-intrinsic" {
// NB: These intrinsics take raw pointers because they mutate aliased
// memory, which is not valid for either `&` or `&mut`.
- #[cfg(all(stage0, not(cargobuild)))]
- pub fn atomic_cxchg<T>(dst: *mut T, old: T, src: T) -> T;
- #[cfg(all(stage0, not(cargobuild)))]
- pub fn atomic_cxchg_acq<T>(dst: *mut T, old: T, src: T) -> T;
- #[cfg(all(stage0, not(cargobuild)))]
- pub fn atomic_cxchg_rel<T>(dst: *mut T, old: T, src: T) -> T;
- #[cfg(all(stage0, not(cargobuild)))]
- pub fn atomic_cxchg_acqrel<T>(dst: *mut T, old: T, src: T) -> T;
- #[cfg(all(stage0, not(cargobuild)))]
- pub fn atomic_cxchg_relaxed<T>(dst: *mut T, old: T, src: T) -> T;
-
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_acq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_rel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_acqrel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_relaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_failacq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_acq_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
- #[cfg(any(not(stage0), cargobuild))]
pub fn atomic_cxchg_acqrel_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
pub fn atomic_cxchgweak<T>(dst: *mut T, old: T, src: T) -> (T, bool);
@@ -448,10 +428,7 @@ extern "rust-intrinsic" {
pub fn volatile_load<T>(src: *const T) -> T;
/// Perform a volatile store to the `dst` pointer.
pub fn volatile_store<T>(dst: *mut T, val: T);
-}
-#[cfg(not(disable_float))]
-extern "rust-intrinsic" {
/// Returns the square root of an `f32`
pub fn sqrtf32(x: f32) -> f32;
/// Returns the square root of an `f64`
@@ -551,31 +528,25 @@ extern "rust-intrinsic" {
/// Float addition that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
- #[cfg(not(stage0))]
pub fn fadd_fast<T>(a: T, b: T) -> T;
/// Float subtraction that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
- #[cfg(not(stage0))]
pub fn fsub_fast<T>(a: T, b: T) -> T;
/// Float multiplication that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
- #[cfg(not(stage0))]
pub fn fmul_fast<T>(a: T, b: T) -> T;
/// Float division that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
- #[cfg(not(stage0))]
pub fn fdiv_fast<T>(a: T, b: T) -> T;
/// Float remainder that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
- #[cfg(not(stage0))]
pub fn frem_fast<T>(a: T, b: T) -> T;
-}
-extern "rust-intrinsic" {
+
/// Returns the number of bits set in an integer type `T`
pub fn ctpop<T>(x: T) -> T;
diff --git a/libcore/iter.rs b/libcore/iter.rs
deleted file mode 100644
index b4378a5..0000000
--- a/libcore/iter.rs
+++ /dev/null
@@ -1,5007 +0,0 @@
-// Copyright 2013-2014 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.
-
-//! Composable external iteration.
-//!
-//! If you've found yourself with a collection of some kind, and needed to
-//! perform an operation on the elements of said collection, you'll quickly run
-//! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
-//! it's worth becoming familiar with them.
-//!
-//! Before explaining more, let's talk about how this module is structured:
-//!
-//! # Organization
-//!
-//! This module is largely organized by type:
-//!
-//! * [Traits] are the core portion: these traits define what kind of iterators
-//! exist and what you can do with them. The methods of these traits are worth
-//! putting some extra study time into.
-//! * [Functions] provide some helpful ways to create some basic iterators.
-//! * [Structs] are often the return types of the various methods on this
-//! module's traits. You'll usually want to look at the method that creates
-//! the `struct`, rather than the `struct` itself. For more detail about why,
-//! see '[Implementing Iterator](#implementing-iterator)'.
-//!
-//! [Traits]: #traits
-//! [Functions]: #functions
-//! [Structs]: #structs
-//!
-//! That's it! Let's dig into iterators.
-//!
-//! # Iterator
-//!
-//! The heart and soul of this module is the [`Iterator`] trait. The core of
-//! [`Iterator`] looks like this:
-//!
-//! ```
-//! trait Iterator {
-//! type Item;
-//! fn next(&mut self) -> Option<Self::Item>;
-//! }
-//! ```
-//!
-//! An iterator has a method, [`next()`], which when called, returns an
-//! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
-//! are elements, and once they've all been exhausted, will return `None` to
-//! indicate that iteration is finished. Individual iterators may choose to
-//! resume iteration, and so calling [`next()`] again may or may not eventually
-//! start returning `Some(Item)` again at some point.
-//!
-//! [`Iterator`]'s full definition includes a number of other methods as well,
-//! but they are default methods, built on top of [`next()`], and so you get
-//! them for free.
-//!
-//! Iterators are also composable, and it's common to chain them together to do
-//! more complex forms of processing. See the [Adapters](#adapters) section
-//! below for more details.
-//!
-//! [`Iterator`]: trait.Iterator.html
-//! [`next()`]: trait.Iterator.html#tymethod.next
-//! [`Option`]: ../../std/option/enum.Option.html
-//!
-//! # The three forms of iteration
-//!
-//! There are three common methods which can create iterators from a collection:
-//!
-//! * `iter()`, which iterates over `&T`.
-//! * `iter_mut()`, which iterates over `&mut T`.
-//! * `into_iter()`, which iterates over `T`.
-//!
-//! Various things in the standard library may implement one or more of the
-//! three, where appropriate.
-//!
-//! # Implementing Iterator
-//!
-//! Creating an iterator of your own involves two steps: creating a `struct` to
-//! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
-//! `struct`. This is why there are so many `struct`s in this module: there is
-//! one for each iterator and iterator adapter.
-//!
-//! Let's make an iterator named `Counter` which counts from `1` to `5`:
-//!
-//! ```
-//! // First, the struct:
-//!
-//! /// An iterator which counts from one to five
-//! struct Counter {
-//! count: usize,
-//! }
-//!
-//! // we want our count to start at one, so let's add a new() method to help.
-//! // This isn't strictly necessary, but is convenient. Note that we start
-//! // `count` at zero, we'll see why in `next()`'s implementation below.
-//! impl Counter {
-//! fn new() -> Counter {
-//! Counter { count: 0 }
-//! }
-//! }
-//!
-//! // Then, we implement `Iterator` for our `Counter`:
-//!
-//! impl Iterator for Counter {
-//! // we will be counting with usize
-//! type Item = usize;
-//!
-//! // next() is the only required method
-//! fn next(&mut self) -> Option<usize> {
-//! // increment our count. This is why we started at zero.
-//! self.count += 1;
-//!
-//! // check to see if we've finished counting or not.
-//! if self.count < 6 {
-//! Some(self.count)
-//! } else {
-//! None
-//! }
-//! }
-//! }
-//!
-//! // And now we can use it!
-//!
-//! let mut counter = Counter::new();
-//!
-//! let x = counter.next().unwrap();
-//! println!("{}", x);
-//!
-//! let x = counter.next().unwrap();
-//! println!("{}", x);
-//!
-//! let x = counter.next().unwrap();
-//! println!("{}", x);
-//!
-//! let x = counter.next().unwrap();
-//! println!("{}", x);
-//!
-//! let x = counter.next().unwrap();
-//! println!("{}", x);
-//! ```
-//!
-//! This will print `1` through `5`, each on their own line.
-//!
-//! Calling `next()` this way gets repetitive. Rust has a construct which can
-//! call `next()` on your iterator, until it reaches `None`. Let's go over that
-//! next.
-//!
-//! # for Loops and IntoIterator
-//!
-//! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
-//! example of `for`:
-//!
-//! ```
-//! let values = vec![1, 2, 3, 4, 5];
-//!
-//! for x in values {
-//! println!("{}", x);
-//! }
-//! ```
-//!
-//! This will print the numbers one through five, each on their own line. But
-//! you'll notice something here: we never called anything on our vector to
-//! produce an iterator. What gives?
-//!
-//! There's a trait in the standard library for converting something into an
-//! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
-//! which converts the thing implementing [`IntoIterator`] into an iterator.
-//! Let's take a look at that `for` loop again, and what the compiler converts
-//! it into:
-//!
-//! [`IntoIterator`]: trait.IntoIterator.html
-//! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
-//!
-//! ```
-//! let values = vec![1, 2, 3, 4, 5];
-//!
-//! for x in values {
-//! println!("{}", x);
-//! }
-//! ```
-//!
-//! Rust de-sugars this into:
-//!
-//! ```
-//! let values = vec![1, 2, 3, 4, 5];
-//! {
-//! let result = match IntoIterator::into_iter(values) {
-//! mut iter => loop {
-//! match iter.next() {
-//! Some(x) => { println!("{}", x); },
-//! None => break,
-//! }
-//! },
-//! };
-//! result
-//! }
-//! ```
-//!
-//! First, we call `into_iter()` on the value. Then, we match on the iterator
-//! that returns, calling [`next()`] over and over until we see a `None`. At
-//! that point, we `break` out of the loop, and we're done iterating.
-//!
-//! There's one more subtle bit here: the standard library contains an
-//! interesting implementation of [`IntoIterator`]:
-//!
-//! ```ignore
-//! impl<I: Iterator> IntoIterator for I
-//! ```
-//!
-//! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
-//! returning themselves. This means two things:
-//!
-//! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
-//! 2. If you're creating a collection, implementing [`IntoIterator`] for it
-//! will allow your collection to be used with the `for` loop.
-//!
-//! # Adapters
-//!
-//! Functions which take an [`Iterator`] and return another [`Iterator`] are
-//! often called 'iterator adapters', as they're a form of the 'adapter
-//! pattern'.
-//!
-//! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
-//! For more, see their documentation.
-//!
-//! [`map()`]: trait.Iterator.html#method.map
-//! [`take()`]: trait.Iterator.html#method.take
-//! [`collect()`]: trait.Iterator.html#method.collect
-//!
-//! # Laziness
-//!
-//! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
-//! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
-//! until you call [`next()`]. This is sometimes a source of confusion when
-//! creating an iterator solely for its side effects. For example, the [`map()`]
-//! method calls a closure on each element it iterates over:
-//!
-//! ```
-//! # #![allow(unused_must_use)]
-//! let v = vec![1, 2, 3, 4, 5];
-//! v.iter().map(|x| println!("{}", x));
-//! ```
-//!
-//! This will not print any values, as we only created an iterator, rather than
-//! using it. The compiler will warn us about this kind of behavior:
-//!
-//! ```text
-//! warning: unused result which must be used: iterator adaptors are lazy and
-//! do nothing unless consumed
-//! ```
-//!
-//! The idiomatic way to write a [`map()`] for its side effects is to use a
-//! `for` loop instead:
-//!
-//! ```
-//! let v = vec![1, 2, 3, 4, 5];
-//!
-//! for x in &v {
-//! println!("{}", x);
-//! }
-//! ```
-//!
-//! [`map()`]: trait.Iterator.html#method.map
-//!
-//! The two most common ways to evaluate an iterator are to use a `for` loop
-//! like this, or using the [`collect()`] adapter to produce a new collection.
-//!
-//! [`collect()`]: trait.Iterator.html#method.collect
-//!
-//! # Infinity
-//!
-//! Iterators do not have to be finite. As an example, an open-ended range is
-//! an infinite iterator:
-//!
-//! ```
-//! let numbers = 0..;
-//! ```
-//!
-//! It is common to use the [`take()`] iterator adapter to turn an infinite
-//! iterator into a finite one:
-//!
-//! ```
-//! let numbers = 0..;
-//! let five_numbers = numbers.take(5);
-//!
-//! for number in five_numbers {
-//! println!("{}", number);
-//! }
-//! ```
-//!
-//! This will print the numbers `0` through `4`, each on their own line.
-//!
-//! [`take()`]: trait.Iterator.html#method.take
-
-#![stable(feature = "rust1", since = "1.0.0")]
-
-use clone::Clone;
-use cmp;
-use cmp::{Ord, PartialOrd, PartialEq, Ordering};
-use default::Default;
-use fmt;
-use marker;
-use mem;
-use num::{Zero, One};
-use ops::{self, Add, Sub, FnMut, Mul};
-use option::Option::{self, Some, None};
-use marker::Sized;
-use usize;
-
-fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
-
-/// An interface for dealing with iterators.
-///
-/// This is the main iterator trait. For more about the concept of iterators
-/// generally, please see the [module-level documentation]. In particular, you
-/// may want to know how to [implement `Iterator`][impl].
-///
-/// [module-level documentation]: index.html
-/// [impl]: index.html#implementing-iterator
-#[stable(feature = "rust1", since = "1.0.0")]
-#[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
- `.iter()` or a similar method"]
-pub trait Iterator {
- /// The type of the elements being iterated over.
- #[stable(feature = "rust1", since = "1.0.0")]
- type Item;
-
- /// Advances the iterator and returns the next value.
- ///
- /// Returns `None` when iteration is finished. Individual iterator
- /// implementations may choose to resume iteration, and so calling `next()`
- /// again may or may not eventually start returning `Some(Item)` again at some
- /// point.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// // A call to next() returns the next value...
- /// assert_eq!(Some(&1), iter.next());
- /// assert_eq!(Some(&2), iter.next());
- /// assert_eq!(Some(&3), iter.next());
- ///
- /// // ... and then None once it's over.
- /// assert_eq!(None, iter.next());
- ///
- /// // More calls may or may not return None. Here, they always will.
- /// assert_eq!(None, iter.next());
- /// assert_eq!(None, iter.next());
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn next(&mut self) -> Option<Self::Item>;
-
- /// Returns the bounds on the remaining length of the iterator.
- ///
- /// Specifically, `size_hint()` returns a tuple where the first element
- /// is the lower bound, and the second element is the upper bound.
- ///
- /// The second half of the tuple that is returned is an `Option<usize>`. A
- /// `None` here means that either there is no known upper bound, or the
- /// upper bound is larger than `usize`.
- ///
- /// # Implementation notes
- ///
- /// It is not enforced that an iterator implementation yields the declared
- /// number of elements. A buggy iterator may yield less than the lower bound
- /// or more than the upper bound of elements.
- ///
- /// `size_hint()` is primarily intended to be used for optimizations such as
- /// reserving space for the elements of the iterator, but must not be
- /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
- /// implementation of `size_hint()` should not lead to memory safety
- /// violations.
- ///
- /// That said, the implementation should provide a correct estimation,
- /// because otherwise it would be a violation of the trait's protocol.
- ///
- /// The default implementation returns `(0, None)` which is correct for any
- /// iterator.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// let iter = a.iter();
- ///
- /// assert_eq!((3, Some(3)), iter.size_hint());
- /// ```
- ///
- /// A more complex example:
- ///
- /// ```
- /// // The even numbers from zero to ten.
- /// let iter = (0..10).filter(|x| x % 2 == 0);
- ///
- /// // We might iterate from zero to ten times. Knowing that it's five
- /// // exactly wouldn't be possible without executing filter().
- /// assert_eq!((0, Some(10)), iter.size_hint());
- ///
- /// // Let's add one five more numbers with chain()
- /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
- ///
- /// // now both bounds are increased by five
- /// assert_eq!((5, Some(15)), iter.size_hint());
- /// ```
- ///
- /// Returning `None` for an upper bound:
- ///
- /// ```
- /// // an infinite iterator has no upper bound
- /// let iter = 0..;
- ///
- /// assert_eq!((0, None), iter.size_hint());
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
-
- /// Consumes the iterator, counting the number of iterations and returning it.
- ///
- /// This method will evaluate the iterator until its [`next()`] returns
- /// `None`. Once `None` is encountered, `count()` returns the number of
- /// times it called [`next()`].
- ///
- /// [`next()`]: #tymethod.next
- ///
- /// # Overflow Behavior
- ///
- /// The method does no guarding against overflows, so counting elements of
- /// an iterator with more than `usize::MAX` elements either produces the
- /// wrong result or panics. If debug assertions are enabled, a panic is
- /// guaranteed.
- ///
- /// # Panics
- ///
- /// This function might panic if the iterator has more than `usize::MAX`
- /// elements.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert_eq!(a.iter().count(), 3);
- ///
- /// let a = [1, 2, 3, 4, 5];
- /// assert_eq!(a.iter().count(), 5);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn count(self) -> usize where Self: Sized {
- // Might overflow.
- self.fold(0, |cnt, _| cnt + 1)
- }
-
- /// Consumes the iterator, returning the last element.
- ///
- /// This method will evaluate the iterator until it returns `None`. While
- /// doing so, it keeps track of the current element. After `None` is
- /// returned, `last()` will then return the last element it saw.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert_eq!(a.iter().last(), Some(&3));
- ///
- /// let a = [1, 2, 3, 4, 5];
- /// assert_eq!(a.iter().last(), Some(&5));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn last(self) -> Option<Self::Item> where Self: Sized {
- let mut last = None;
- for x in self { last = Some(x); }
- last
- }
-
- /// Consumes the `n` first elements of the iterator, then returns the
- /// `next()` one.
- ///
- /// This method will evaluate the iterator `n` times, discarding those elements.
- /// After it does so, it will call [`next()`] and return its value.
- ///
- /// [`next()`]: #tymethod.next
- ///
- /// Like most indexing operations, the count starts from zero, so `nth(0)`
- /// returns the first value, `nth(1)` the second, and so on.
- ///
- /// `nth()` will return `None` if `n` is larger than the length of the
- /// iterator.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert_eq!(a.iter().nth(1), Some(&2));
- /// ```
- ///
- /// Calling `nth()` multiple times doesn't rewind the iterator:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert_eq!(iter.nth(1), Some(&2));
- /// assert_eq!(iter.nth(1), None);
- /// ```
- ///
- /// Returning `None` if there are less than `n` elements:
- ///
- /// ```
- /// let a = [1, 2, 3];
- /// assert_eq!(a.iter().nth(10), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
- for x in self {
- if n == 0 { return Some(x) }
- n -= 1;
- }
- None
- }
-
- /// Takes two iterators and creates a new iterator over both in sequence.
- ///
- /// `chain()` will return a new iterator which will first iterate over
- /// values from the first iterator and then over values from the second
- /// iterator.
- ///
- /// In other words, it links two iterators together, in a chain. 🔗
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a1 = [1, 2, 3];
- /// let a2 = [4, 5, 6];
- ///
- /// let mut iter = a1.iter().chain(a2.iter());
- ///
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), Some(&3));
- /// assert_eq!(iter.next(), Some(&4));
- /// assert_eq!(iter.next(), Some(&5));
- /// assert_eq!(iter.next(), Some(&6));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
- /// anything that can be converted into an [`Iterator`], not just an
- /// [`Iterator`] itself. For example, slices (`&[T]`) implement
- /// [`IntoIterator`], and so can be passed to `chain()` directly:
- ///
- /// [`IntoIterator`]: trait.IntoIterator.html
- /// [`Iterator`]: trait.Iterator.html
- ///
- /// ```
- /// let s1 = &[1, 2, 3];
- /// let s2 = &[4, 5, 6];
- ///
- /// let mut iter = s1.iter().chain(s2);
- ///
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), Some(&3));
- /// assert_eq!(iter.next(), Some(&4));
- /// assert_eq!(iter.next(), Some(&5));
- /// assert_eq!(iter.next(), Some(&6));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- 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}
- }
-
- /// 'Zips up' two iterators into a single iterator of pairs.
- ///
- /// `zip()` returns a new iterator that will iterate over two other
- /// iterators, returning a tuple where the first element comes from the
- /// first iterator, and the second element comes from the second iterator.
- ///
- /// In other words, it zips two iterators together, into a single one.
- ///
- /// When either iterator returns `None`, all further calls to `next()`
- /// will return `None`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a1 = [1, 2, 3];
- /// let a2 = [4, 5, 6];
- ///
- /// let mut iter = a1.iter().zip(a2.iter());
- ///
- /// assert_eq!(iter.next(), Some((&1, &4)));
- /// assert_eq!(iter.next(), Some((&2, &5)));
- /// assert_eq!(iter.next(), Some((&3, &6)));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
- /// anything that can be converted into an [`Iterator`], not just an
- /// [`Iterator`] itself. For example, slices (`&[T]`) implement
- /// [`IntoIterator`], and so can be passed to `zip()` directly:
- ///
- /// [`IntoIterator`]: trait.IntoIterator.html
- /// [`Iterator`]: trait.Iterator.html
- ///
- /// ```
- /// let s1 = &[1, 2, 3];
- /// let s2 = &[4, 5, 6];
- ///
- /// let mut iter = s1.iter().zip(s2);
- ///
- /// assert_eq!(iter.next(), Some((&1, &4)));
- /// assert_eq!(iter.next(), Some((&2, &5)));
- /// assert_eq!(iter.next(), Some((&3, &6)));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// `zip()` is often used to zip an infinite iterator to a finite one.
- /// This works because the finite iterator will eventually return `None`,
- /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
- ///
- /// ```
- /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
- ///
- /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
- ///
- /// assert_eq!((0, 'f'), enumerate[0]);
- /// assert_eq!((0, 'f'), zipper[0]);
- ///
- /// assert_eq!((1, 'o'), enumerate[1]);
- /// assert_eq!((1, 'o'), zipper[1]);
- ///
- /// assert_eq!((2, 'o'), enumerate[2]);
- /// assert_eq!((2, 'o'), zipper[2]);
- /// ```
- ///
- /// [`enumerate()`]: trait.Iterator.html#method.enumerate
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
- Self: Sized, U: IntoIterator
- {
- Zip{a: self, b: other.into_iter()}
- }
-
- /// Takes a closure and creates an iterator which calls that closure on each
- /// element.
- ///
- /// `map()` transforms one iterator into another, by means of its argument:
- /// something that implements `FnMut`. It produces a new iterator which
- /// calls this closure on each element of the original iterator.
- ///
- /// If you are good at thinking in types, you can think of `map()` like this:
- /// If you have an iterator that gives you elements of some type `A`, and
- /// you want an iterator of some other type `B`, you can use `map()`,
- /// passing a closure that takes an `A` and returns a `B`.
- ///
- /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
- /// lazy, it is best used when you're already working with other iterators.
- /// If you're doing some sort of looping for a side effect, it's considered
- /// more idiomatic to use [`for`] than `map()`.
- ///
- /// [`for`]: ../../book/loops.html#for
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.into_iter().map(|x| 2 * x);
- ///
- /// assert_eq!(iter.next(), Some(2));
- /// assert_eq!(iter.next(), Some(4));
- /// assert_eq!(iter.next(), Some(6));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
- ///
- /// ```
- /// # #![allow(unused_must_use)]
- /// // don't do this:
- /// (0..5).map(|x| println!("{}", x));
- ///
- /// // it won't even execute, as it is lazy. Rust will warn you about this.
- ///
- /// // Instead, use for:
- /// for x in 0..5 {
- /// println!("{}", x);
- /// }
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn map<B, F>(self, f: F) -> Map<Self, F> where
- Self: Sized, F: FnMut(Self::Item) -> B,
- {
- Map{iter: self, f: f}
- }
-
- /// Creates an iterator which uses a closure to determine if an element
- /// should be yielded.
- ///
- /// The closure must return `true` or `false`. `filter()` creates an
- /// iterator which calls this closure on each element. If the closure
- /// returns `true`, then the element is returned. If the closure returns
- /// `false`, it will try again, and call the closure on the next element,
- /// seeing if it passes the test.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [0i32, 1, 2];
- ///
- /// let mut iter = a.into_iter().filter(|x| x.is_positive());
- ///
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Because the closure passed to `filter()` takes a reference, and many
- /// iterators iterate over references, this leads to a possibly confusing
- /// situation, where the type of the closure is a double reference:
- ///
- /// ```
- /// let a = [0, 1, 2];
- ///
- /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
- ///
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// It's common to instead use destructuring on the argument to strip away
- /// one:
- ///
- /// ```
- /// let a = [0, 1, 2];
- ///
- /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
- ///
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// or both:
- ///
- /// ```
- /// let a = [0, 1, 2];
- ///
- /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
- ///
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// of these layers.
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn filter<P>(self, predicate: P) -> Filter<Self, P> where
- Self: Sized, P: FnMut(&Self::Item) -> bool,
- {
- Filter{iter: self, predicate: predicate}
- }
-
- /// Creates an iterator that both filters and maps.
- ///
- /// The closure must return an [`Option<T>`]. `filter_map()` creates an
- /// iterator which calls this closure on each element. If the closure
- /// returns `Some(element)`, then that element is returned. If the
- /// closure returns `None`, it will try again, and call the closure on the
- /// next element, seeing if it will return `Some`.
- ///
- /// [`Option<T>`]: ../../std/option/enum.Option.html
- ///
- /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
- /// part:
- ///
- /// [`filter()`]: #method.filter
- /// [`map()`]: #method.map
- ///
- /// > If the closure returns `Some(element)`, then that element is returned.
- ///
- /// In other words, it removes the [`Option<T>`] layer automatically. If your
- /// mapping is already returning an [`Option<T>`] and you want to skip over
- /// `None`s, then `filter_map()` is much, much nicer to use.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = ["1", "2", "lol"];
- ///
- /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
- ///
- /// assert_eq!(iter.next(), Some(1));
- /// assert_eq!(iter.next(), Some(2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Here's the same example, but with [`filter()`] and [`map()`]:
- ///
- /// ```
- /// let a = ["1", "2", "lol"];
- ///
- /// let mut iter = a.iter()
- /// .map(|s| s.parse().ok())
- /// .filter(|s| s.is_some());
- ///
- /// assert_eq!(iter.next(), Some(Some(1)));
- /// assert_eq!(iter.next(), Some(Some(2)));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// There's an extra layer of `Some` in there.
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
- Self: Sized, F: FnMut(Self::Item) -> Option<B>,
- {
- FilterMap { iter: self, f: f }
- }
-
- /// Creates an iterator which gives the current iteration count as well as
- /// the next value.
- ///
- /// The iterator returned yields pairs `(i, val)`, where `i` is the
- /// current index of iteration and `val` is the value returned by the
- /// iterator.
- ///
- /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
- /// different sized integer, the [`zip()`] function provides similar
- /// functionality.
- ///
- /// [`usize`]: ../../std/primitive.usize.html
- /// [`zip()`]: #method.zip
- ///
- /// # Overflow Behavior
- ///
- /// The method does no guarding against overflows, so enumerating more than
- /// [`usize::MAX`] elements either produces the wrong result or panics. If
- /// debug assertions are enabled, a panic is guaranteed.
- ///
- /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
- ///
- /// # Panics
- ///
- /// The returned iterator might panic if the to-be-returned index would
- /// overflow a `usize`.
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter().enumerate();
- ///
- /// assert_eq!(iter.next(), Some((0, &1)));
- /// assert_eq!(iter.next(), Some((1, &2)));
- /// assert_eq!(iter.next(), Some((2, &3)));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn enumerate(self) -> Enumerate<Self> where Self: Sized {
- Enumerate { iter: self, count: 0 }
- }
-
- /// Creates an iterator which can look at the `next()` element without
- /// consuming it.
- ///
- /// Adds a [`peek()`] method to an iterator. See its documentation for
- /// more information.
- ///
- /// [`peek()`]: struct.Peekable.html#method.peek
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let xs = [1, 2, 3];
- ///
- /// let mut iter = xs.iter().peekable();
- ///
- /// // peek() lets us see into the future
- /// assert_eq!(iter.peek(), Some(&&1));
- /// assert_eq!(iter.next(), Some(&1));
- ///
- /// assert_eq!(iter.next(), Some(&2));
- ///
- /// // we can peek() multiple times, the iterator won't advance
- /// assert_eq!(iter.peek(), Some(&&3));
- /// assert_eq!(iter.peek(), Some(&&3));
- ///
- /// assert_eq!(iter.next(), Some(&3));
- ///
- /// // after the iterator is finished, so is peek()
- /// assert_eq!(iter.peek(), None);
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn peekable(self) -> Peekable<Self> where Self: Sized {
- Peekable{iter: self, peeked: None}
- }
-
- /// Creates an iterator that [`skip()`]s elements based on a predicate.
- ///
- /// [`skip()`]: #method.skip
- ///
- /// `skip_while()` takes a closure as an argument. It will call this
- /// closure on each element of the iterator, and ignore elements
- /// until it returns `false`.
- ///
- /// After `false` is returned, `skip_while()`'s job is over, and the
- /// rest of the elements are yielded.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [-1i32, 0, 1];
- ///
- /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
- ///
- /// assert_eq!(iter.next(), Some(&0));
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Because the closure passed to `skip_while()` takes a reference, and many
- /// iterators iterate over references, this leads to a possibly confusing
- /// situation, where the type of the closure is a double reference:
- ///
- /// ```
- /// let a = [-1, 0, 1];
- ///
- /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
- ///
- /// assert_eq!(iter.next(), Some(&0));
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Stopping after an initial `false`:
- ///
- /// ```
- /// let a = [-1, 0, 1, -2];
- ///
- /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
- ///
- /// assert_eq!(iter.next(), Some(&0));
- /// assert_eq!(iter.next(), Some(&1));
- ///
- /// // while this would have been false, since we already got a false,
- /// // skip_while() isn't used any more
- /// assert_eq!(iter.next(), Some(&-2));
- ///
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
- Self: Sized, P: FnMut(&Self::Item) -> bool,
- {
- SkipWhile{iter: self, flag: false, predicate: predicate}
- }
-
- /// Creates an iterator that yields elements based on a predicate.
- ///
- /// `take_while()` takes a closure as an argument. It will call this
- /// closure on each element of the iterator, and yield elements
- /// while it returns `true`.
- ///
- /// After `false` is returned, `take_while()`'s job is over, and the
- /// rest of the elements are ignored.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [-1i32, 0, 1];
- ///
- /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
- ///
- /// assert_eq!(iter.next(), Some(&-1));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Because the closure passed to `take_while()` takes a reference, and many
- /// iterators iterate over references, this leads to a possibly confusing
- /// situation, where the type of the closure is a double reference:
- ///
- /// ```
- /// let a = [-1, 0, 1];
- ///
- /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
- ///
- /// assert_eq!(iter.next(), Some(&-1));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Stopping after an initial `false`:
- ///
- /// ```
- /// let a = [-1, 0, 1, -2];
- ///
- /// let mut iter = a.into_iter().take_while(|x| **x < 0);
- ///
- /// assert_eq!(iter.next(), Some(&-1));
- ///
- /// // We have more elements that are less than zero, but since we already
- /// // got a false, take_while() isn't used any more
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// Because `take_while()` needs to look at the value in order to see if it
- /// should be included or not, consuming iterators will see that it is
- /// removed:
- ///
- /// ```
- /// let a = [1, 2, 3, 4];
- /// let mut iter = a.into_iter();
- ///
- /// let result: Vec<i32> = iter.by_ref()
- /// .take_while(|n| **n != 3)
- /// .cloned()
- /// .collect();
- ///
- /// assert_eq!(result, &[1, 2]);
- ///
- /// let result: Vec<i32> = iter.cloned().collect();
- ///
- /// assert_eq!(result, &[4]);
- /// ```
- ///
- /// The `3` is no longer there, because it was consumed in order to see if
- /// the iteration should stop, but wasn't placed back into the iterator or
- /// some similar thing.
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
- Self: Sized, P: FnMut(&Self::Item) -> bool,
- {
- TakeWhile{iter: self, flag: false, predicate: predicate}
- }
-
- /// Creates an iterator that skips the first `n` elements.
- ///
- /// After they have been consumed, the rest of the elements are yielded.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter().skip(2);
- ///
- /// assert_eq!(iter.next(), Some(&3));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
- Skip{iter: self, n: n}
- }
-
- /// Creates an iterator that yields its first `n` elements.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter().take(2);
- ///
- /// assert_eq!(iter.next(), Some(&1));
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), None);
- /// ```
- ///
- /// `take()` is often used with an infinite iterator, to make it finite:
- ///
- /// ```
- /// let mut iter = (0..).take(3);
- ///
- /// assert_eq!(iter.next(), Some(0));
- /// assert_eq!(iter.next(), Some(1));
- /// assert_eq!(iter.next(), Some(2));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn take(self, n: usize) -> Take<Self> where Self: Sized, {
- Take{iter: self, n: n}
- }
-
- /// An iterator adaptor similar to [`fold()`] that holds internal state and
- /// produces a new iterator.
- ///
- /// [`fold()`]: #method.fold
- ///
- /// `scan()` takes two arguments: an initial value which seeds the internal
- /// state, and a closure with two arguments, the first being a mutable
- /// reference to the internal state and the second an iterator element.
- /// The closure can assign to the internal state to share state between
- /// iterations.
- ///
- /// On iteration, the closure will be applied to each element of the
- /// iterator and the return value from the closure, an [`Option`], is
- /// yielded by the iterator.
- ///
- /// [`Option`]: ../../std/option/enum.Option.html
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter().scan(1, |state, &x| {
- /// // each iteration, we'll multiply the state by the element
- /// *state = *state * x;
- ///
- /// // the value passed on to the next iteration
- /// Some(*state)
- /// });
- ///
- /// assert_eq!(iter.next(), Some(1));
- /// assert_eq!(iter.next(), Some(2));
- /// assert_eq!(iter.next(), Some(6));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- 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: f, state: initial_state}
- }
-
- /// Creates an iterator that works like map, but flattens nested structure.
- ///
- /// The [`map()`] adapter is very useful, but only when the closure
- /// argument produces values. If it produces an iterator instead, there's
- /// an extra layer of indirection. `flat_map()` will remove this extra layer
- /// on its own.
- ///
- /// [`map()`]: #method.map
- ///
- /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
- /// one item for each element, and `flat_map()`'s closure returns an
- /// iterator for each element.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let words = ["alpha", "beta", "gamma"];
- ///
- /// // chars() returns an iterator
- /// let merged: String = words.iter()
- /// .flat_map(|s| s.chars())
- /// .collect();
- /// assert_eq!(merged, "alphabetagamma");
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
- where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
- {
- FlatMap{iter: self, f: f, frontiter: None, backiter: None }
- }
-
- /// Creates an iterator which ends after the first `None`.
- ///
- /// After an iterator returns `None`, future calls may or may not yield
- /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
- /// `None` is given, it will always return `None` forever.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// // an iterator which alternates between Some and None
- /// struct Alternate {
- /// state: i32,
- /// }
- ///
- /// impl Iterator for Alternate {
- /// type Item = i32;
- ///
- /// fn next(&mut self) -> Option<i32> {
- /// let val = self.state;
- /// self.state = self.state + 1;
- ///
- /// // if it's even, Some(i32), else None
- /// if val % 2 == 0 {
- /// Some(val)
- /// } else {
- /// None
- /// }
- /// }
- /// }
- ///
- /// let mut iter = Alternate { state: 0 };
- ///
- /// // we can see our iterator going back and forth
- /// assert_eq!(iter.next(), Some(0));
- /// assert_eq!(iter.next(), None);
- /// assert_eq!(iter.next(), Some(2));
- /// assert_eq!(iter.next(), None);
- ///
- /// // however, once we fuse it...
- /// let mut iter = iter.fuse();
- ///
- /// assert_eq!(iter.next(), Some(4));
- /// assert_eq!(iter.next(), None);
- ///
- /// // it will always return None after the first time.
- /// assert_eq!(iter.next(), None);
- /// assert_eq!(iter.next(), None);
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn fuse(self) -> Fuse<Self> where Self: Sized {
- Fuse{iter: self, done: false}
- }
-
- /// Do something with each element of an iterator, passing the value on.
- ///
- /// When using iterators, you'll often chain several of them together.
- /// While working on such code, you might want to check out what's
- /// happening at various parts in the pipeline. To do that, insert
- /// a call to `inspect()`.
- ///
- /// It's much more common for `inspect()` to be used as a debugging tool
- /// than to exist in your final code, but never say never.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 4, 2, 3];
- ///
- /// // this iterator sequence is complex.
- /// let sum = a.iter()
- /// .cloned()
- /// .filter(|&x| x % 2 == 0)
- /// .fold(0, |sum, i| sum + i);
- ///
- /// println!("{}", sum);
- ///
- /// // let's add some inspect() calls to investigate what's happening
- /// let sum = a.iter()
- /// .cloned()
- /// .inspect(|x| println!("about to filter: {}", x))
- /// .filter(|&x| x % 2 == 0)
- /// .inspect(|x| println!("made it through filter: {}", x))
- /// .fold(0, |sum, i| sum + i);
- ///
- /// println!("{}", sum);
- /// ```
- ///
- /// This will print:
- ///
- /// ```text
- /// about to filter: 1
- /// about to filter: 4
- /// made it through filter: 4
- /// about to filter: 2
- /// made it through filter: 2
- /// about to filter: 3
- /// 6
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn inspect<F>(self, f: F) -> Inspect<Self, F> where
- Self: Sized, F: FnMut(&Self::Item),
- {
- Inspect{iter: self, f: f}
- }
-
- /// Borrows an iterator, rather than consuming it.
- ///
- /// This is useful to allow applying iterator adaptors while still
- /// retaining ownership of the original iterator.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let iter = a.into_iter();
- ///
- /// let sum: i32 = iter.take(5)
- /// .fold(0, |acc, &i| acc + i );
- ///
- /// assert_eq!(sum, 6);
- ///
- /// // if we try to use iter again, it won't work. The following line
- /// // gives "error: use of moved value: `iter`
- /// // assert_eq!(iter.next(), None);
- ///
- /// // let's try that again
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.into_iter();
- ///
- /// // instead, we add in a .by_ref()
- /// let sum: i32 = iter.by_ref()
- /// .take(2)
- /// .fold(0, |acc, &i| acc + i );
- ///
- /// assert_eq!(sum, 3);
- ///
- /// // now this is just fine:
- /// assert_eq!(iter.next(), Some(&3));
- /// assert_eq!(iter.next(), None);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
-
- /// Transforms an iterator into a collection.
- ///
- /// `collect()` can take anything iterable, and turn it into a relevant
- /// collection. This is one of the more powerful methods in the standard
- /// library, used in a variety of contexts.
- ///
- /// The most basic pattern in which `collect()` is used is to turn one
- /// collection into another. You take a collection, call `iter()` on it,
- /// do a bunch of transformations, and then `collect()` at the end.
- ///
- /// One of the keys to `collect()`'s power is that many things you might
- /// not think of as 'collections' actually are. For example, a [`String`]
- /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
- /// be thought of as single `Result<Collection<T>, E>`. See the examples
- /// below for more.
- ///
- /// [`String`]: ../../std/string/struct.String.html
- /// [`Result<T, E>`]: ../../std/result/enum.Result.html
- /// [`char`]: ../../std/primitive.char.html
- ///
- /// Because `collect()` is so general, it can cause problems with type
- /// inference. As such, `collect()` is one of the few times you'll see
- /// the syntax affectionately known as the 'turbofish': `::<>`. This
- /// helps the inference algorithm understand specifically which collection
- /// you're trying to collect into.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let doubled: Vec<i32> = a.iter()
- /// .map(|&x| x * 2)
- /// .collect();
- ///
- /// assert_eq!(vec![2, 4, 6], doubled);
- /// ```
- ///
- /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
- /// we could collect into, for example, a [`VecDeque<T>`] instead:
- ///
- /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
- ///
- /// ```
- /// use std::collections::VecDeque;
- ///
- /// let a = [1, 2, 3];
- ///
- /// let doubled: VecDeque<i32> = a.iter()
- /// .map(|&x| x * 2)
- /// .collect();
- ///
- /// assert_eq!(2, doubled[0]);
- /// assert_eq!(4, doubled[1]);
- /// assert_eq!(6, doubled[2]);
- /// ```
- ///
- /// Using the 'turbofish' instead of annotating `doubled`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let doubled = a.iter()
- /// .map(|&x| x * 2)
- /// .collect::<Vec<i32>>();
- ///
- /// assert_eq!(vec![2, 4, 6], doubled);
- /// ```
- ///
- /// Because `collect()` cares about what you're collecting into, you can
- /// still use a partial type hint, `_`, with the turbofish:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let doubled = a.iter()
- /// .map(|&x| x * 2)
- /// .collect::<Vec<_>>();
- ///
- /// assert_eq!(vec![2, 4, 6], doubled);
- /// ```
- ///
- /// Using `collect()` to make a [`String`]:
- ///
- /// ```
- /// let chars = ['g', 'd', 'k', 'k', 'n'];
- ///
- /// let hello: String = chars.iter()
- /// .map(|&x| x as u8)
- /// .map(|x| (x + 1) as char)
- /// .collect();
- ///
- /// assert_eq!("hello", hello);
- /// ```
- ///
- /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
- /// see if any of them failed:
- ///
- /// ```
- /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
- ///
- /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
- ///
- /// // gives us the first error
- /// assert_eq!(Err("nope"), result);
- ///
- /// let results = [Ok(1), Ok(3)];
- ///
- /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
- ///
- /// // gives us the list of answers
- /// assert_eq!(Ok(vec![1, 3]), result);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
- FromIterator::from_iter(self)
- }
-
- /// Consumes an iterator, creating two collections from it.
- ///
- /// The predicate passed to `partition()` can return `true`, or `false`.
- /// `partition()` returns a pair, all of the elements for which it returned
- /// `true`, and all of the elements for which it returned `false`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
- /// .partition(|&n| n % 2 == 0);
- ///
- /// assert_eq!(even, vec![2]);
- /// assert_eq!(odd, vec![1, 3]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn partition<B, F>(self, mut f: F) -> (B, B) where
- Self: Sized,
- B: Default + Extend<Self::Item>,
- F: FnMut(&Self::Item) -> bool
- {
- let mut left: B = Default::default();
- let mut right: B = Default::default();
-
- for x in self {
- if f(&x) {
- left.extend(Some(x))
- } else {
- right.extend(Some(x))
- }
- }
-
- (left, right)
- }
-
- /// An iterator adaptor that applies a function, producing a single, final value.
- ///
- /// `fold()` 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, `fold()`
- /// 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.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// // the sum of all of the elements of a
- /// let sum = a.iter()
- /// .fold(0, |acc, &x| acc + x);
- ///
- /// assert_eq!(sum, 6);
- /// ```
- ///
- /// Let's walk through each step of the iteration here:
- ///
- /// | element | acc | x | result |
- /// |---------|-----|---|--------|
- /// | | 0 | | |
- /// | 1 | 0 | 1 | 1 |
- /// | 2 | 1 | 2 | 3 |
- /// | 3 | 3 | 3 | 6 |
- ///
- /// And so, our final result, `6`.
- ///
- /// It's common for people who haven't used iterators a lot to
- /// use a `for` loop with a list of things to build up a result. Those
- /// can be turned into `fold()`s:
- ///
- /// ```
- /// let numbers = [1, 2, 3, 4, 5];
- ///
- /// let mut result = 0;
- ///
- /// // for loop:
- /// for i in &numbers {
- /// result = result + i;
- /// }
- ///
- /// // fold:
- /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
- ///
- /// // they're the same
- /// assert_eq!(result, result2);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn fold<B, F>(self, init: B, mut f: F) -> B where
- Self: Sized, F: FnMut(B, Self::Item) -> B,
- {
- let mut accum = init;
- for x in self {
- accum = f(accum, x);
- }
- accum
- }
-
- /// Tests if every element of the iterator matches a predicate.
- ///
- /// `all()` takes a closure that returns `true` or `false`. It applies
- /// this closure to each element of the iterator, and if they all return
- /// `true`, then so does `all()`. If any of them return `false`, it
- /// returns `false`.
- ///
- /// `all()` is short-circuiting; in other words, it will stop processing
- /// as soon as it finds a `false`, given that no matter what else happens,
- /// the result will also be `false`.
- ///
- /// An empty iterator returns `true`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert!(a.iter().all(|&x| x > 0));
- ///
- /// assert!(!a.iter().all(|&x| x > 2));
- /// ```
- ///
- /// Stopping at the first `false`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert!(!iter.all(|&x| x != 2));
- ///
- /// // we can still use `iter`, as there are more elements.
- /// assert_eq!(iter.next(), Some(&3));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn all<F>(&mut self, mut f: F) -> bool where
- Self: Sized, F: FnMut(Self::Item) -> bool
- {
- for x in self {
- if !f(x) {
- return false;
- }
- }
- true
- }
-
- /// Tests if any element of the iterator matches a predicate.
- ///
- /// `any()` takes a closure that returns `true` or `false`. It applies
- /// this closure to each element of the iterator, and if any of them return
- /// `true`, then so does `any()`. If they all return `false`, it
- /// returns `false`.
- ///
- /// `any()` is short-circuiting; in other words, it will stop processing
- /// as soon as it finds a `true`, given that no matter what else happens,
- /// the result will also be `true`.
- ///
- /// An empty iterator returns `false`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert!(a.iter().any(|&x| x > 0));
- ///
- /// assert!(!a.iter().any(|&x| x > 5));
- /// ```
- ///
- /// Stopping at the first `true`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert!(iter.any(|&x| x != 2));
- ///
- /// // we can still use `iter`, as there are more elements.
- /// assert_eq!(iter.next(), Some(&2));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn any<F>(&mut self, mut f: F) -> bool where
- Self: Sized,
- F: FnMut(Self::Item) -> bool
- {
- for x in self {
- if f(x) {
- return true;
- }
- }
- false
- }
-
- /// Searches for an element of an iterator that satisfies a predicate.
- ///
- /// `find()` takes a closure that returns `true` or `false`. It applies
- /// this closure to each element of the iterator, and if any of them return
- /// `true`, then `find()` returns `Some(element)`. If they all return
- /// `false`, it returns `None`.
- ///
- /// `find()` is short-circuiting; in other words, it will stop processing
- /// as soon as the closure returns `true`.
- ///
- /// Because `find()` 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`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
- ///
- /// assert_eq!(a.iter().find(|&&x| x == 5), None);
- /// ```
- ///
- /// Stopping at the first `true`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
- ///
- /// // we can still use `iter`, as there are more elements.
- /// assert_eq!(iter.next(), Some(&3));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
- Self: Sized,
- P: FnMut(&Self::Item) -> bool,
- {
- for x in self {
- if predicate(&x) { return Some(x) }
- }
- None
- }
-
- /// Searches for an element in an iterator, returning its index.
- ///
- /// `position()` takes a closure that returns `true` or `false`. It applies
- /// this closure to each element of the iterator, and if one of them
- /// returns `true`, then `position()` returns `Some(index)`. If all of
- /// them return `false`, it returns `None`.
- ///
- /// `position()` is short-circuiting; in other words, it will stop
- /// processing as soon as it finds a `true`.
- ///
- /// # Overflow Behavior
- ///
- /// The method does no guarding against overflows, so if there are more
- /// than `usize::MAX` non-matching elements, it either produces the wrong
- /// result or panics. If debug assertions are enabled, a panic is
- /// guaranteed.
- ///
- /// # Panics
- ///
- /// This function might panic if the iterator has more than `usize::MAX`
- /// non-matching elements.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
- ///
- /// assert_eq!(a.iter().position(|&x| x == 5), None);
- /// ```
- ///
- /// Stopping at the first `true`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert_eq!(iter.position(|&x| x == 2), Some(1));
- ///
- /// // we can still use `iter`, as there are more elements.
- /// assert_eq!(iter.next(), Some(&3));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
- Self: Sized,
- P: FnMut(Self::Item) -> bool,
- {
- // `enumerate` might overflow.
- for (i, x) in self.enumerate() {
- if predicate(x) {
- return Some(i);
- }
- }
- None
- }
-
- /// Searches for an element in an iterator from the right, returning its
- /// index.
- ///
- /// `rposition()` takes a closure that returns `true` or `false`. It applies
- /// this closure to each element of the iterator, starting from the end,
- /// and if one of them returns `true`, then `rposition()` returns
- /// `Some(index)`. If all of them return `false`, it returns `None`.
- ///
- /// `rposition()` is short-circuiting; in other words, it will stop
- /// processing as soon as it finds a `true`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
- ///
- /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
- /// ```
- ///
- /// Stopping at the first `true`:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter();
- ///
- /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
- ///
- /// // we can still use `iter`, as there are more elements.
- /// assert_eq!(iter.next(), Some(&1));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
- P: FnMut(Self::Item) -> bool,
- Self: Sized + ExactSizeIterator + DoubleEndedIterator
- {
- let mut i = self.len();
-
- while let Some(v) = self.next_back() {
- if predicate(v) {
- return Some(i - 1);
- }
- // No need for an overflow check here, because `ExactSizeIterator`
- // implies that the number of elements fits into a `usize`.
- i -= 1;
- }
- None
- }
-
- /// Returns the maximum element of an iterator.
- ///
- /// If the two elements are equally maximum, the latest element is
- /// returned.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert_eq!(a.iter().max(), Some(&3));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
- {
- select_fold1(self,
- |_| (),
- // switch to y even if it is only equal, to preserve
- // stability.
- |_, x, _, y| *x <= *y)
- .map(|(_, x)| x)
- }
-
- /// Returns the minimum element of an iterator.
- ///
- /// If the two elements are equally minimum, the first element is
- /// returned.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// assert_eq!(a.iter().min(), Some(&1));
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
- {
- select_fold1(self,
- |_| (),
- // only switch to y if it is strictly smaller, to
- // preserve stability.
- |_, x, _, y| *x > *y)
- .map(|(_, x)| x)
- }
-
- /// Returns the element that gives the maximum value from the
- /// specified function.
- ///
- /// Returns the rightmost element if the comparison determines two elements
- /// to be equally maximum.
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [-3_i32, 0, 1, 5, -10];
- /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
- /// ```
- #[inline]
- #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
- fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
- where Self: Sized, F: FnMut(&Self::Item) -> B,
- {
- select_fold1(self,
- f,
- // switch to y even if it is only equal, to preserve
- // stability.
- |x_p, _, y_p, _| x_p <= y_p)
- .map(|(_, x)| x)
- }
-
- /// Returns the element that gives the minimum value from the
- /// specified function.
- ///
- /// Returns the latest element if the comparison determines two elements
- /// to be equally minimum.
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [-3_i32, 0, 1, 5, -10];
- /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
- /// ```
- #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
- fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
- where Self: Sized, F: FnMut(&Self::Item) -> B,
- {
- select_fold1(self,
- f,
- // only switch to y if it is strictly smaller, to
- // preserve stability.
- |x_p, _, y_p, _| x_p > y_p)
- .map(|(_, x)| x)
- }
-
- /// Reverses an iterator's direction.
- ///
- /// Usually, iterators iterate from left to right. After using `rev()`,
- /// an iterator will instead iterate from right to left.
- ///
- /// This is only possible if the iterator has an end, so `rev()` only
- /// works on [`DoubleEndedIterator`]s.
- ///
- /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
- ///
- /// # Examples
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut iter = a.iter().rev();
- ///
- /// assert_eq!(iter.next(), Some(&3));
- /// assert_eq!(iter.next(), Some(&2));
- /// assert_eq!(iter.next(), Some(&1));
- ///
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
- Rev{iter: self}
- }
-
- /// Converts an iterator of pairs into a pair of containers.
- ///
- /// `unzip()` consumes an entire iterator of pairs, producing two
- /// collections: one from the left elements of the pairs, and one
- /// from the right elements.
- ///
- /// This function is, in some sense, the opposite of [`zip()`].
- ///
- /// [`zip()`]: #method.zip
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [(1, 2), (3, 4)];
- ///
- /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
- ///
- /// assert_eq!(left, [1, 3]);
- /// assert_eq!(right, [2, 4]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
- FromA: Default + Extend<A>,
- FromB: Default + Extend<B>,
- Self: Sized + Iterator<Item=(A, B)>,
- {
- struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
- impl<A> Iterator for SizeHint<A> {
- type Item = A;
-
- fn next(&mut self) -> Option<A> { None }
- fn size_hint(&self) -> (usize, Option<usize>) {
- (self.0, self.1)
- }
- }
-
- let (lo, hi) = self.size_hint();
- let mut ts: FromA = Default::default();
- let mut us: FromB = Default::default();
-
- ts.extend(SizeHint(lo, hi, marker::PhantomData));
- us.extend(SizeHint(lo, hi, marker::PhantomData));
-
- for (t, u) in self {
- ts.extend(Some(t));
- us.extend(Some(u));
- }
-
- (ts, us)
- }
-
- /// Creates an iterator which `clone()`s all of its elements.
- ///
- /// This is useful when you have an iterator over `&T`, but you need an
- /// iterator over `T`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let v_cloned: Vec<_> = a.iter().cloned().collect();
- ///
- /// // cloned is the same as .map(|&x| x), for integers
- /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
- ///
- /// assert_eq!(v_cloned, vec![1, 2, 3]);
- /// assert_eq!(v_map, vec![1, 2, 3]);
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- fn cloned<'a, T: 'a>(self) -> Cloned<Self>
- where Self: Sized + Iterator<Item=&'a T>, T: Clone
- {
- Cloned { it: self }
- }
-
- /// Repeats an iterator endlessly.
- ///
- /// Instead of stopping at `None`, the iterator will instead start again,
- /// from the beginning. After iterating again, it will start at the
- /// beginning again. And again. And again. Forever.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let a = [1, 2, 3];
- ///
- /// let mut it = a.iter().cycle();
- ///
- /// assert_eq!(it.next(), Some(&1));
- /// assert_eq!(it.next(), Some(&2));
- /// assert_eq!(it.next(), Some(&3));
- /// assert_eq!(it.next(), Some(&1));
- /// assert_eq!(it.next(), Some(&2));
- /// assert_eq!(it.next(), Some(&3));
- /// assert_eq!(it.next(), Some(&1));
- /// ```
- #[stable(feature = "rust1", since = "1.0.0")]
- #[inline]
- fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
- Cycle{orig: self.clone(), iter: self}
- }
-
- /// Sums the elements of an iterator.
- ///
- /// Takes each element, adds them together, and returns the result.
- ///
- /// An empty iterator returns the zero value of the type.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// #![feature(iter_arith)]
- ///
- /// let a = [1, 2, 3];
- /// let sum: i32 = a.iter().sum();
- ///
- /// assert_eq!(sum, 6);
- /// ```
- #[unstable(feature = "iter_arith", reason = "bounds recently changed",
- issue = "27739")]
- fn sum<S>(self) -> S where
- S: Add<Self::Item, Output=S> + Zero,
- Self: Sized,
- {
- self.fold(Zero::zero(), |s, e| s + e)
- }
-
- /// Iterates over the entire iterator, multiplying all the elements
- ///
- /// An empty iterator returns the one value of the type.
- ///
- /// # Examples
- ///
- /// ```
- /// #![feature(iter_arith)]
- ///
- /// fn factorial(n: u32) -> u32 {
- /// (1..).take_while(|&i| i <= n).product()
- /// }
- /// assert_eq!(factorial(0), 1);
- /// assert_eq!(factorial(1), 1);
- /// assert_eq!(factorial(5), 120);
- /// ```
- #[unstable(feature="iter_arith", reason = "bounds recently changed",
- issue = "27739")]
- fn product<P>(self) -> P where
- P: Mul<Self::Item, Output=P> + One,
- Self: Sized,
- {
- self.fold(One::one(), |p, e| p * e)
- }
-
- /// Lexicographically compares the elements of this `Iterator` with those
- /// of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn cmp<I>(mut self, other: I) -> Ordering where
- I: IntoIterator<Item = Self::Item>,
- Self::Item: Ord,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return Ordering::Equal,
- (None, _ ) => return Ordering::Less,
- (_ , None) => return Ordering::Greater,
- (Some(x), Some(y)) => match x.cmp(&y) {
- Ordering::Equal => (),
- non_eq => return non_eq,
- },
- }
- }
- }
-
- /// Lexicographically compares the elements of this `Iterator` with those
- /// of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
- I: IntoIterator,
- Self::Item: PartialOrd<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return Some(Ordering::Equal),
- (None, _ ) => return Some(Ordering::Less),
- (_ , None) => return Some(Ordering::Greater),
- (Some(x), Some(y)) => match x.partial_cmp(&y) {
- Some(Ordering::Equal) => (),
- non_eq => return non_eq,
- },
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are equal to those of
- /// another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn eq<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialEq<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return true,
- (None, _) | (_, None) => return false,
- (Some(x), Some(y)) => if x != y { return false },
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are unequal to those of
- /// another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn ne<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialEq<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return false,
- (None, _) | (_, None) => return true,
- (Some(x), Some(y)) => if x.ne(&y) { return true },
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are lexicographically
- /// less than those of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn lt<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialOrd<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return false,
- (None, _ ) => return true,
- (_ , None) => return false,
- (Some(x), Some(y)) => {
- match x.partial_cmp(&y) {
- Some(Ordering::Less) => return true,
- Some(Ordering::Equal) => {}
- Some(Ordering::Greater) => return false,
- None => return false,
- }
- },
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are lexicographically
- /// less or equal to those of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn le<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialOrd<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return true,
- (None, _ ) => return true,
- (_ , None) => return false,
- (Some(x), Some(y)) => {
- match x.partial_cmp(&y) {
- Some(Ordering::Less) => return true,
- Some(Ordering::Equal) => {}
- Some(Ordering::Greater) => return false,
- None => return false,
- }
- },
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are lexicographically
- /// greater than those of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn gt<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialOrd<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return false,
- (None, _ ) => return false,
- (_ , None) => return true,
- (Some(x), Some(y)) => {
- match x.partial_cmp(&y) {
- Some(Ordering::Less) => return false,
- Some(Ordering::Equal) => {}
- Some(Ordering::Greater) => return true,
- None => return false,
- }
- }
- }
- }
- }
-
- /// Determines if the elements of this `Iterator` are lexicographically
- /// greater than or equal to those of another.
- #[stable(feature = "iter_order", since = "1.5.0")]
- fn ge<I>(mut self, other: I) -> bool where
- I: IntoIterator,
- Self::Item: PartialOrd<I::Item>,
- Self: Sized,
- {
- let mut other = other.into_iter();
-
- loop {
- match (self.next(), other.next()) {
- (None, None) => return true,
- (None, _ ) => return false,
- (_ , None) => return true,
- (Some(x), Some(y)) => {
- match x.partial_cmp(&y) {
- Some(Ordering::Less) => return false,
- Some(Ordering::Equal) => {}
- Some(Ordering::Greater) => return true,
- None => return false,
- }
- },
- }
- }
- }
-}
-
-/// Select an element from an iterator based on the given projection
-/// and "comparison" function.
-///
-/// This is an idiosyncratic helper to try to factor out the
-/// commonalities of {max,min}{,_by}. In particular, this avoids
-/// having to implement optimizations several times.
-#[inline]
-fn select_fold1<I,B, FProj, FCmp>(mut it: I,
- mut f_proj: FProj,
- mut f_cmp: FCmp) -> Option<(B, I::Item)>
- where I: Iterator,
- FProj: FnMut(&I::Item) -> B,
- FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
-{
- // start with the first element as our selection. This avoids
- // having to use `Option`s inside the loop, translating to a
- // sizeable performance gain (6x in one case).
- it.next().map(|mut sel| {
- let mut sel_p = f_proj(&sel);
-
- for x in it {
- let x_p = f_proj(&x);
- if f_cmp(&sel_p, &sel, &x_p, &x) {
- sel = x;
- sel_p = x_p;
- }
- }
- (sel_p, sel)
- })
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
- type Item = I::Item;
- fn next(&mut self) -> Option<I::Item> { (**self).next() }
- fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
-}
-
-/// 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 {}
-
-// All adaptors that preserve the size of the wrapped iterator are fine
-// Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F> where
- F: FnMut(&I::Item),
-{}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> ExactSizeIterator for Rev<I>
- where I: ExactSizeIterator + DoubleEndedIterator {}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F> where
- F: FnMut(I::Item) -> B,
-{}
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<A, B> ExactSizeIterator for Zip<A, B>
- where A: ExactSizeIterator, B: ExactSizeIterator {}
-
-/// An double-ended iterator with the direction inverted.
-///
-/// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`rev()`]: trait.Iterator.html#method.rev
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Rev<T> {
- iter: T
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
- type Item = <I as Iterator>::Item;
-
- #[inline]
- fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
- #[inline]
- fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
-}
-
-/// An iterator that clones the elements of an underlying iterator.
-///
-/// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`cloned()`]: trait.Iterator.html#method.cloned
-/// [`Iterator`]: trait.Iterator.html
-#[stable(feature = "iter_cloned", since = "1.1.0")]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[derive(Clone, Debug)]
-pub struct Cloned<I> {
- it: I,
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, I, T: 'a> Iterator for Cloned<I>
- where I: Iterator<Item=&'a T>, T: Clone
-{
- type Item = T;
-
- fn next(&mut self) -> Option<T> {
- self.it.next().cloned()
- }
-
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.it.size_hint()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
- where I: DoubleEndedIterator<Item=&'a T>, T: Clone
-{
- fn next_back(&mut self) -> Option<T> {
- self.it.next_back().cloned()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
- where I: ExactSizeIterator<Item=&'a T>, T: Clone
-{}
-
-/// An iterator that repeats endlessly.
-///
-/// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`cycle()`]: trait.Iterator.html#method.cycle
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Cycle<I> {
- orig: I,
- iter: I,
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
- type Item = <I as Iterator>::Item;
-
- #[inline]
- fn next(&mut self) -> Option<<I as Iterator>::Item> {
- match self.iter.next() {
- None => { self.iter = self.orig.clone(); self.iter.next() }
- y => y
- }
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- // the cycle iterator is either empty or infinite
- match self.orig.size_hint() {
- sz @ (0, Some(0)) => sz,
- (0, _) => (0, None),
- _ => (usize::MAX, None)
- }
- }
-}
-
-/// 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 = "iterator adaptors 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,
-}
-
-// 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]
- 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(),
- }
- }
-
- #[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 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(),
- }
- }
-}
-
-/// 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 = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Zip<A, B> {
- a: A,
- b: B
-}
-
-#[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<(A::Item, B::Item)> {
- self.a.next().and_then(|x| {
- self.b.next().and_then(|y| {
- Some((x, y))
- })
- })
- }
-
- #[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 = 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)
- }
-}
-
-#[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)> {
- 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!(),
- }
- }
-}
-
-/// An iterator that maps the values of `iter` with `f`.
-///
-/// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`map()`]: trait.Iterator.html#method.map
-/// [`Iterator`]: trait.Iterator.html
-///
-/// # Notes about side effects
-///
-/// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
-/// you can also [`map()`] backwards:
-///
-/// ```rust
-/// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
-///
-/// assert_eq!(v, [4, 3, 2]);
-/// ```
-///
-/// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
-///
-/// But if your closure has state, iterating backwards may act in a way you do
-/// not expect. Let's go through an example. First, in the forward direction:
-///
-/// ```rust
-/// let mut c = 0;
-///
-/// for pair in vec!['a', 'b', 'c'].into_iter()
-/// .map(|letter| { c += 1; (letter, c) }) {
-/// println!("{:?}", pair);
-/// }
-/// ```
-///
-/// This will print "('a', 1), ('b', 2), ('c', 3)".
-///
-/// Now consider this twist where we add a call to `rev`. This version will
-/// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
-/// but the values of the counter still go in order. This is because `map()` is
-/// still being called lazilly on each item, but we are popping items off the
-/// back of the vector now, instead of shifting them from the front.
-///
-/// ```rust
-/// let mut c = 0;
-///
-/// for pair in vec!['a', 'b', 'c'].into_iter()
-/// .map(|letter| { c += 1; (letter, c) })
-/// .rev() {
-/// println!("{:?}", pair);
-/// }
-/// ```
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct Map<I, F> {
- iter: I,
- f: F,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("Map")
- .field("iter", &self.iter)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
- type Item = B;
-
- #[inline]
- fn next(&mut self) -> Option<B> {
- self.iter.next().map(&mut self.f)
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
- F: FnMut(I::Item) -> B,
-{
- #[inline]
- fn next_back(&mut self) -> Option<B> {
- self.iter.next_back().map(&mut self.f)
- }
-}
-
-/// An iterator that filters the elements of `iter` with `predicate`.
-///
-/// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`filter()`]: trait.Iterator.html#method.filter
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct Filter<I, P> {
- iter: I,
- predicate: P,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("Filter")
- .field("iter", &self.iter)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
- type Item = I::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- for x in self.iter.by_ref() {
- if (self.predicate)(&x) {
- return Some(x);
- }
- }
- None
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (_, upper) = self.iter.size_hint();
- (0, upper) // can't know a lower bound, due to the predicate
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
- where P: FnMut(&I::Item) -> bool,
-{
- #[inline]
- fn next_back(&mut self) -> Option<I::Item> {
- for x in self.iter.by_ref().rev() {
- if (self.predicate)(&x) {
- return Some(x);
- }
- }
- None
- }
-}
-
-/// An iterator that uses `f` to both filter and map elements from `iter`.
-///
-/// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`filter_map()`]: trait.Iterator.html#method.filter_map
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct FilterMap<I, F> {
- iter: I,
- f: F,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("FilterMap")
- .field("iter", &self.iter)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
- where F: FnMut(I::Item) -> Option<B>,
-{
- type Item = B;
-
- #[inline]
- fn next(&mut self) -> Option<B> {
- for x in self.iter.by_ref() {
- if let Some(y) = (self.f)(x) {
- return Some(y);
- }
- }
- None
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (_, upper) = self.iter.size_hint();
- (0, upper) // can't know a lower bound, due to the predicate
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
- where F: FnMut(I::Item) -> Option<B>,
-{
- #[inline]
- fn next_back(&mut self) -> Option<B> {
- for x in self.iter.by_ref().rev() {
- if let Some(y) = (self.f)(x) {
- return Some(y);
- }
- }
- None
- }
-}
-
-/// An iterator that yields the current count and the element during iteration.
-///
-/// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`enumerate()`]: trait.Iterator.html#method.enumerate
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Enumerate<I> {
- iter: I,
- count: usize,
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Enumerate<I> where I: Iterator {
- type Item = (usize, <I as Iterator>::Item);
-
- /// # Overflow Behavior
- ///
- /// The method does no guarding against overflows, so enumerating more than
- /// `usize::MAX` elements either produces the wrong result or panics. If
- /// debug assertions are enabled, a panic is guaranteed.
- ///
- /// # Panics
- ///
- /// Might panic if the index of the element overflows a `usize`.
- #[inline]
- fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
- self.iter.next().map(|a| {
- let ret = (self.count, a);
- // Possible undefined overflow.
- self.count += 1;
- ret
- })
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-
- #[inline]
- fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
- self.iter.nth(n).map(|a| {
- let i = self.count + n;
- self.count = i + 1;
- (i, a)
- })
- }
-
- #[inline]
- fn count(self) -> usize {
- self.iter.count()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> DoubleEndedIterator for Enumerate<I> where
- I: ExactSizeIterator + DoubleEndedIterator
-{
- #[inline]
- fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
- self.iter.next_back().map(|a| {
- let len = self.iter.len();
- // Can safely add, `ExactSizeIterator` promises that the number of
- // elements fits into a `usize`.
- (self.count + len, a)
- })
- }
-}
-
-/// An iterator with a `peek()` that returns an optional reference to the next
-/// element.
-///
-/// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`peekable()`]: trait.Iterator.html#method.peekable
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Peekable<I: Iterator> {
- iter: I,
- peeked: Option<I::Item>,
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator> Iterator for Peekable<I> {
- type Item = I::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- match self.peeked {
- Some(_) => self.peeked.take(),
- None => self.iter.next(),
- }
- }
-
- #[inline]
- fn count(self) -> usize {
- (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
- }
-
- #[inline]
- fn nth(&mut self, n: usize) -> Option<I::Item> {
- match self.peeked {
- Some(_) if n == 0 => self.peeked.take(),
- Some(_) => {
- self.peeked = None;
- self.iter.nth(n-1)
- },
- None => self.iter.nth(n)
- }
- }
-
- #[inline]
- fn last(self) -> Option<I::Item> {
- self.iter.last().or(self.peeked)
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (lo, hi) = self.iter.size_hint();
- if self.peeked.is_some() {
- let lo = lo.saturating_add(1);
- let hi = hi.and_then(|x| x.checked_add(1));
- (lo, hi)
- } else {
- (lo, hi)
- }
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
-
-impl<I: Iterator> Peekable<I> {
- /// Returns a reference to the next() value without advancing the iterator.
- ///
- /// The `peek()` method will return the value that a call to [`next()`] would
- /// return, but does not advance the iterator. Like [`next()`], if there is
- /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
- /// will return `None`.
- ///
- /// [`next()`]: trait.Iterator.html#tymethod.next
- ///
- /// Because `peek()` returns reference, and many iterators iterate over
- /// references, this leads to a possibly confusing situation where the
- /// return value is a double reference. You can see this effect in the
- /// examples below, with `&&i32`.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// let xs = [1, 2, 3];
- ///
- /// let mut iter = xs.iter().peekable();
- ///
- /// // peek() lets us see into the future
- /// assert_eq!(iter.peek(), Some(&&1));
- /// assert_eq!(iter.next(), Some(&1));
- ///
- /// assert_eq!(iter.next(), Some(&2));
- ///
- /// // we can peek() multiple times, the iterator won't advance
- /// assert_eq!(iter.peek(), Some(&&3));
- /// assert_eq!(iter.peek(), Some(&&3));
- ///
- /// assert_eq!(iter.next(), Some(&3));
- ///
- /// // after the iterator is finished, so is peek()
- /// assert_eq!(iter.peek(), None);
- /// assert_eq!(iter.next(), None);
- /// ```
- #[inline]
- #[stable(feature = "rust1", since = "1.0.0")]
- pub fn peek(&mut self) -> Option<&I::Item> {
- if self.peeked.is_none() {
- self.peeked = self.iter.next();
- }
- match self.peeked {
- Some(ref value) => Some(value),
- None => None,
- }
- }
-
- /// Checks if the iterator has finished iterating.
- ///
- /// Returns `true` if there are no more elements in the iterator, and
- /// `false` if there are.
- ///
- /// # Examples
- ///
- /// Basic usage:
- ///
- /// ```
- /// #![feature(peekable_is_empty)]
- ///
- /// let xs = [1, 2, 3];
- ///
- /// let mut iter = xs.iter().peekable();
- ///
- /// // there are still elements to iterate over
- /// assert_eq!(iter.is_empty(), false);
- ///
- /// // let's consume the iterator
- /// iter.next();
- /// iter.next();
- /// iter.next();
- ///
- /// assert_eq!(iter.is_empty(), true);
- /// ```
- #[unstable(feature = "peekable_is_empty", issue = "32111")]
- #[inline]
- pub fn is_empty(&mut self) -> bool {
- self.peek().is_none()
- }
-}
-
-/// An iterator that rejects elements while `predicate` is true.
-///
-/// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`skip_while()`]: trait.Iterator.html#method.skip_while
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct SkipWhile<I, P> {
- iter: I,
- flag: bool,
- predicate: P,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("SkipWhile")
- .field("iter", &self.iter)
- .field("flag", &self.flag)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator, P> Iterator for SkipWhile<I, P>
- where P: FnMut(&I::Item) -> bool
-{
- type Item = I::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- for x in self.iter.by_ref() {
- if self.flag || !(self.predicate)(&x) {
- self.flag = true;
- return Some(x);
- }
- }
- None
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (_, upper) = self.iter.size_hint();
- (0, upper) // can't know a lower bound, due to the predicate
- }
-}
-
-/// An iterator that only accepts elements while `predicate` is true.
-///
-/// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`take_while()`]: trait.Iterator.html#method.take_while
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct TakeWhile<I, P> {
- iter: I,
- flag: bool,
- predicate: P,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("TakeWhile")
- .field("iter", &self.iter)
- .field("flag", &self.flag)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator, P> Iterator for TakeWhile<I, P>
- where P: FnMut(&I::Item) -> bool
-{
- type Item = I::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- if self.flag {
- None
- } else {
- self.iter.next().and_then(|x| {
- if (self.predicate)(&x) {
- Some(x)
- } else {
- self.flag = true;
- None
- }
- })
- }
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (_, upper) = self.iter.size_hint();
- (0, upper) // can't know a lower bound, due to the predicate
- }
-}
-
-/// An iterator that skips over `n` elements of `iter`.
-///
-/// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`skip()`]: trait.Iterator.html#method.skip
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Skip<I> {
- iter: I,
- n: usize
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Skip<I> where I: Iterator {
- type Item = <I as Iterator>::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- if self.n == 0 {
- self.iter.next()
- } else {
- let old_n = self.n;
- self.n = 0;
- self.iter.nth(old_n)
- }
- }
-
- #[inline]
- fn nth(&mut self, n: usize) -> Option<I::Item> {
- // Can't just add n + self.n due to overflow.
- if self.n == 0 {
- self.iter.nth(n)
- } else {
- let to_skip = self.n;
- self.n = 0;
- // nth(n) skips n+1
- if self.iter.nth(to_skip-1).is_none() {
- return None;
- }
- self.iter.nth(n)
- }
- }
-
- #[inline]
- fn count(self) -> usize {
- self.iter.count().saturating_sub(self.n)
- }
-
- #[inline]
- fn last(mut self) -> Option<I::Item> {
- if self.n == 0 {
- self.iter.last()
- } else {
- let next = self.next();
- if next.is_some() {
- // recurse. n should be 0.
- self.last().or(next)
- } else {
- None
- }
- }
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (lower, upper) = self.iter.size_hint();
-
- let lower = lower.saturating_sub(self.n);
- let upper = upper.map(|x| x.saturating_sub(self.n));
-
- (lower, upper)
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
-
-#[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
-impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
- fn next_back(&mut self) -> Option<Self::Item> {
- if self.len() > 0 {
- self.iter.next_back()
- } else {
- None
- }
- }
-}
-
-/// An iterator that only iterates over the first `n` iterations of `iter`.
-///
-/// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`take()`]: trait.Iterator.html#method.take
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Take<I> {
- iter: I,
- n: usize
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Take<I> where I: Iterator{
- type Item = <I as Iterator>::Item;
-
- #[inline]
- fn next(&mut self) -> Option<<I as Iterator>::Item> {
- if self.n != 0 {
- self.n -= 1;
- self.iter.next()
- } else {
- None
- }
- }
-
- #[inline]
- fn nth(&mut self, n: usize) -> Option<I::Item> {
- if self.n > n {
- self.n -= n + 1;
- self.iter.nth(n)
- } else {
- if self.n > 0 {
- self.iter.nth(self.n - 1);
- self.n = 0;
- }
- None
- }
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (lower, upper) = self.iter.size_hint();
-
- let lower = cmp::min(lower, self.n);
-
- let upper = match upper {
- Some(x) if x < self.n => Some(x),
- _ => Some(self.n)
- };
-
- (lower, upper)
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
-
-
-/// An iterator to maintain state while iterating another iterator.
-///
-/// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`scan()`]: trait.Iterator.html#method.scan
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct Scan<I, St, F> {
- iter: I,
- f: F,
- state: St,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("Scan")
- .field("iter", &self.iter)
- .field("state", &self.state)
- .finish()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<B, I, St, F> Iterator for Scan<I, St, F> where
- I: Iterator,
- F: FnMut(&mut St, I::Item) -> Option<B>,
-{
- type Item = B;
-
- #[inline]
- fn next(&mut self) -> Option<B> {
- self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- let (_, upper) = self.iter.size_hint();
- (0, upper) // can't know a lower bound, due to the scan function
- }
-}
-
-/// 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 = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct FlatMap<I, U: IntoIterator, F> {
- iter: I,
- f: F,
- frontiter: Option<U::IntoIter>,
- backiter: Option<U::IntoIter>,
-}
-
-#[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("iter", &self.iter)
- .field("frontiter", &self.frontiter)
- .field("backiter", &self.backiter)
- .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> {
- loop {
- if let Some(ref mut inner) = self.frontiter {
- if let Some(x) = inner.by_ref().next() {
- return Some(x)
- }
- }
- match self.iter.next().map(&mut self.f) {
- None => return self.backiter.as_mut().and_then(|it| it.next()),
- next => self.frontiter = next.map(IntoIterator::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)
- }
- }
-}
-
-#[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> {
- loop {
- if let Some(ref mut inner) = self.backiter {
- if let Some(y) = inner.next_back() {
- return Some(y)
- }
- }
- match self.iter.next_back().map(&mut self.f) {
- None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
- next => self.backiter = next.map(IntoIterator::into_iter),
- }
- }
- }
-}
-
-/// An iterator that yields `None` forever after the underlying iterator
-/// yields `None` once.
-///
-/// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`fuse()`]: trait.Iterator.html#method.fuse
-/// [`Iterator`]: trait.Iterator.html
-#[derive(Clone, Debug)]
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct Fuse<I> {
- iter: I,
- done: bool
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> Iterator for Fuse<I> where I: Iterator {
- type Item = <I as Iterator>::Item;
-
- #[inline]
- fn next(&mut self) -> Option<<I as Iterator>::Item> {
- if self.done {
- None
- } else {
- let next = self.iter.next();
- self.done = next.is_none();
- next
- }
- }
-
- #[inline]
- fn nth(&mut self, n: usize) -> Option<I::Item> {
- if self.done {
- None
- } else {
- let nth = self.iter.nth(n);
- self.done = nth.is_none();
- nth
- }
- }
-
- #[inline]
- fn last(self) -> Option<I::Item> {
- if self.done {
- None
- } else {
- self.iter.last()
- }
- }
-
- #[inline]
- fn count(self) -> usize {
- if self.done {
- 0
- } else {
- self.iter.count()
- }
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- if self.done {
- (0, Some(0))
- } else {
- self.iter.size_hint()
- }
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
- #[inline]
- fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
- if self.done {
- None
- } else {
- let next = self.iter.next_back();
- self.done = next.is_none();
- next
- }
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
-
-/// An iterator that calls a function with a reference to each element before
-/// yielding it.
-///
-/// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
-/// documentation for more.
-///
-/// [`inspect()`]: trait.Iterator.html#method.inspect
-/// [`Iterator`]: trait.Iterator.html
-#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
-#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(Clone)]
-pub struct Inspect<I, F> {
- iter: I,
- f: F,
-}
-
-#[stable(feature = "core_impl_debug", since = "1.9.0")]
-impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- f.debug_struct("Inspect")
- .field("iter", &self.iter)
- .finish()
- }
-}
-
-impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
- #[inline]
- fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
- if let Some(ref a) = elt {
- (self.f)(a);
- }
-
- elt
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
- type Item = I::Item;
-
- #[inline]
- fn next(&mut self) -> Option<I::Item> {
- let next = self.iter.next();
- self.do_inspect(next)
- }
-
- #[inline]
- fn size_hint(&self) -> (usize, Option<usize>) {
- self.iter.size_hint()
- }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
- where F: FnMut(&I::Item),
-{
- #[inline]
- fn next_back(&mut self) -> Option<I::Item> {
- let next = self.iter.next_back();
- self.do_inspect(next)
- }
-}
-
-/// 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
- }
-}
-
-/// 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() }
-}
diff --git a/libcore/iter/iterator.rs b/libcore/iter/iterator.rs
new file mode 100644
index 0000000..2033ae5
--- /dev/null
+++ b/libcore/iter/iterator.rs
@@ -0,0 +1,2111 @@
+// 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::{Ord, PartialOrd, PartialEq, Ordering};
+use default::Default;
+use marker;
+use num::{Zero, One};
+use ops::{Add, FnMut, Mul};
+use option::Option::{self, Some, None};
+use marker::Sized;
+
+use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, FlatMap, Fuse,
+ Inspect, Map, Peekable, Scan, Skip, SkipWhile, Take, TakeWhile, Rev,
+ Zip};
+use super::ChainState;
+use super::{DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator,
+ IntoIterator};
+
+fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
+
+/// An interface for dealing with iterators.
+///
+/// This is the main iterator trait. For more about the concept of iterators
+/// generally, please see the [module-level documentation]. In particular, you
+/// may want to know how to [implement `Iterator`][impl].
+///
+/// [module-level documentation]: index.html
+/// [impl]: index.html#implementing-iterator
+#[stable(feature = "rust1", since = "1.0.0")]
+#[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
+ `.iter()` or a similar method"]
+pub trait Iterator {
+ /// The type of the elements being iterated over.
+ #[stable(feature = "rust1", since = "1.0.0")]
+ type Item;
+
+ /// Advances the iterator and returns the next value.
+ ///
+ /// Returns `None` when iteration is finished. Individual iterator
+ /// implementations may choose to resume iteration, and so calling `next()`
+ /// again may or may not eventually start returning `Some(Item)` again at some
+ /// point.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// // A call to next() returns the next value...
+ /// assert_eq!(Some(&1), iter.next());
+ /// assert_eq!(Some(&2), iter.next());
+ /// assert_eq!(Some(&3), iter.next());
+ ///
+ /// // ... and then None once it's over.
+ /// assert_eq!(None, iter.next());
+ ///
+ /// // More calls may or may not return None. Here, they always will.
+ /// assert_eq!(None, iter.next());
+ /// assert_eq!(None, iter.next());
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn next(&mut self) -> Option<Self::Item>;
+
+ /// Returns the bounds on the remaining length of the iterator.
+ ///
+ /// Specifically, `size_hint()` returns a tuple where the first element
+ /// is the lower bound, and the second element is the upper bound.
+ ///
+ /// The second half of the tuple that is returned is an `Option<usize>`. A
+ /// `None` here means that either there is no known upper bound, or the
+ /// upper bound is larger than `usize`.
+ ///
+ /// # Implementation notes
+ ///
+ /// It is not enforced that an iterator implementation yields the declared
+ /// number of elements. A buggy iterator may yield less than the lower bound
+ /// or more than the upper bound of elements.
+ ///
+ /// `size_hint()` is primarily intended to be used for optimizations such as
+ /// reserving space for the elements of the iterator, but must not be
+ /// trusted to e.g. omit bounds checks in unsafe code. An incorrect
+ /// implementation of `size_hint()` should not lead to memory safety
+ /// violations.
+ ///
+ /// That said, the implementation should provide a correct estimation,
+ /// because otherwise it would be a violation of the trait's protocol.
+ ///
+ /// The default implementation returns `(0, None)` which is correct for any
+ /// iterator.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ /// let iter = a.iter();
+ ///
+ /// assert_eq!((3, Some(3)), iter.size_hint());
+ /// ```
+ ///
+ /// A more complex example:
+ ///
+ /// ```
+ /// // The even numbers from zero to ten.
+ /// let iter = (0..10).filter(|x| x % 2 == 0);
+ ///
+ /// // We might iterate from zero to ten times. Knowing that it's five
+ /// // exactly wouldn't be possible without executing filter().
+ /// assert_eq!((0, Some(10)), iter.size_hint());
+ ///
+ /// // Let's add one five more numbers with chain()
+ /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
+ ///
+ /// // now both bounds are increased by five
+ /// assert_eq!((5, Some(15)), iter.size_hint());
+ /// ```
+ ///
+ /// Returning `None` for an upper bound:
+ ///
+ /// ```
+ /// // an infinite iterator has no upper bound
+ /// let iter = 0..;
+ ///
+ /// assert_eq!((0, None), iter.size_hint());
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
+
+ /// Consumes the iterator, counting the number of iterations and returning it.
+ ///
+ /// This method will evaluate the iterator until its [`next()`] returns
+ /// `None`. Once `None` is encountered, `count()` returns the number of
+ /// times it called [`next()`].
+ ///
+ /// [`next()`]: #tymethod.next
+ ///
+ /// # Overflow Behavior
+ ///
+ /// The method does no guarding against overflows, so counting elements of
+ /// an iterator with more than `usize::MAX` elements either produces the
+ /// wrong result or panics. If debug assertions are enabled, a panic is
+ /// guaranteed.
+ ///
+ /// # Panics
+ ///
+ /// This function might panic if the iterator has more than `usize::MAX`
+ /// elements.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ /// assert_eq!(a.iter().count(), 3);
+ ///
+ /// let a = [1, 2, 3, 4, 5];
+ /// assert_eq!(a.iter().count(), 5);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn count(self) -> usize where Self: Sized {
+ // Might overflow.
+ self.fold(0, |cnt, _| cnt + 1)
+ }
+
+ /// Consumes the iterator, returning the last element.
+ ///
+ /// This method will evaluate the iterator until it returns `None`. While
+ /// doing so, it keeps track of the current element. After `None` is
+ /// returned, `last()` will then return the last element it saw.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ /// assert_eq!(a.iter().last(), Some(&3));
+ ///
+ /// let a = [1, 2, 3, 4, 5];
+ /// assert_eq!(a.iter().last(), Some(&5));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn last(self) -> Option<Self::Item> where Self: Sized {
+ let mut last = None;
+ for x in self { last = Some(x); }
+ last
+ }
+
+ /// Consumes the `n` first elements of the iterator, then returns the
+ /// `next()` one.
+ ///
+ /// This method will evaluate the iterator `n` times, discarding those elements.
+ /// After it does so, it will call [`next()`] and return its value.
+ ///
+ /// [`next()`]: #tymethod.next
+ ///
+ /// Like most indexing operations, the count starts from zero, so `nth(0)`
+ /// returns the first value, `nth(1)` the second, and so on.
+ ///
+ /// `nth()` will return `None` if `n` is larger than the length of the
+ /// iterator.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ /// assert_eq!(a.iter().nth(1), Some(&2));
+ /// ```
+ ///
+ /// Calling `nth()` multiple times doesn't rewind the iterator:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert_eq!(iter.nth(1), Some(&2));
+ /// assert_eq!(iter.nth(1), None);
+ /// ```
+ ///
+ /// Returning `None` if there are less than `n` elements:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ /// assert_eq!(a.iter().nth(10), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
+ for x in self {
+ if n == 0 { return Some(x) }
+ n -= 1;
+ }
+ None
+ }
+
+ /// Takes two iterators and creates a new iterator over both in sequence.
+ ///
+ /// `chain()` will return a new iterator which will first iterate over
+ /// values from the first iterator and then over values from the second
+ /// iterator.
+ ///
+ /// In other words, it links two iterators together, in a chain. 🔗
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a1 = [1, 2, 3];
+ /// let a2 = [4, 5, 6];
+ ///
+ /// let mut iter = a1.iter().chain(a2.iter());
+ ///
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), Some(&3));
+ /// assert_eq!(iter.next(), Some(&4));
+ /// assert_eq!(iter.next(), Some(&5));
+ /// assert_eq!(iter.next(), Some(&6));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
+ /// anything that can be converted into an [`Iterator`], not just an
+ /// [`Iterator`] itself. For example, slices (`&[T]`) implement
+ /// [`IntoIterator`], and so can be passed to `chain()` directly:
+ ///
+ /// [`IntoIterator`]: trait.IntoIterator.html
+ /// [`Iterator`]: trait.Iterator.html
+ ///
+ /// ```
+ /// let s1 = &[1, 2, 3];
+ /// let s2 = &[4, 5, 6];
+ ///
+ /// let mut iter = s1.iter().chain(s2);
+ ///
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), Some(&3));
+ /// assert_eq!(iter.next(), Some(&4));
+ /// assert_eq!(iter.next(), Some(&5));
+ /// assert_eq!(iter.next(), Some(&6));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ 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}
+ }
+
+ /// 'Zips up' two iterators into a single iterator of pairs.
+ ///
+ /// `zip()` returns a new iterator that will iterate over two other
+ /// iterators, returning a tuple where the first element comes from the
+ /// first iterator, and the second element comes from the second iterator.
+ ///
+ /// In other words, it zips two iterators together, into a single one.
+ ///
+ /// When either iterator returns `None`, all further calls to `next()`
+ /// will return `None`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a1 = [1, 2, 3];
+ /// let a2 = [4, 5, 6];
+ ///
+ /// let mut iter = a1.iter().zip(a2.iter());
+ ///
+ /// assert_eq!(iter.next(), Some((&1, &4)));
+ /// assert_eq!(iter.next(), Some((&2, &5)));
+ /// assert_eq!(iter.next(), Some((&3, &6)));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
+ /// anything that can be converted into an [`Iterator`], not just an
+ /// [`Iterator`] itself. For example, slices (`&[T]`) implement
+ /// [`IntoIterator`], and so can be passed to `zip()` directly:
+ ///
+ /// [`IntoIterator`]: trait.IntoIterator.html
+ /// [`Iterator`]: trait.Iterator.html
+ ///
+ /// ```
+ /// let s1 = &[1, 2, 3];
+ /// let s2 = &[4, 5, 6];
+ ///
+ /// let mut iter = s1.iter().zip(s2);
+ ///
+ /// assert_eq!(iter.next(), Some((&1, &4)));
+ /// assert_eq!(iter.next(), Some((&2, &5)));
+ /// assert_eq!(iter.next(), Some((&3, &6)));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// `zip()` is often used to zip an infinite iterator to a finite one.
+ /// This works because the finite iterator will eventually return `None`,
+ /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
+ ///
+ /// ```
+ /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
+ ///
+ /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
+ ///
+ /// assert_eq!((0, 'f'), enumerate[0]);
+ /// assert_eq!((0, 'f'), zipper[0]);
+ ///
+ /// assert_eq!((1, 'o'), enumerate[1]);
+ /// assert_eq!((1, 'o'), zipper[1]);
+ ///
+ /// assert_eq!((2, 'o'), enumerate[2]);
+ /// assert_eq!((2, 'o'), zipper[2]);
+ /// ```
+ ///
+ /// [`enumerate()`]: trait.Iterator.html#method.enumerate
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
+ Self: Sized, U: IntoIterator
+ {
+ Zip{a: self, b: other.into_iter()}
+ }
+
+ /// Takes a closure and creates an iterator which calls that closure on each
+ /// element.
+ ///
+ /// `map()` transforms one iterator into another, by means of its argument:
+ /// something that implements `FnMut`. It produces a new iterator which
+ /// calls this closure on each element of the original iterator.
+ ///
+ /// If you are good at thinking in types, you can think of `map()` like this:
+ /// If you have an iterator that gives you elements of some type `A`, and
+ /// you want an iterator of some other type `B`, you can use `map()`,
+ /// passing a closure that takes an `A` and returns a `B`.
+ ///
+ /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
+ /// lazy, it is best used when you're already working with other iterators.
+ /// If you're doing some sort of looping for a side effect, it's considered
+ /// more idiomatic to use [`for`] than `map()`.
+ ///
+ /// [`for`]: ../../book/loops.html#for
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.into_iter().map(|x| 2 * x);
+ ///
+ /// assert_eq!(iter.next(), Some(2));
+ /// assert_eq!(iter.next(), Some(4));
+ /// assert_eq!(iter.next(), Some(6));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
+ ///
+ /// ```
+ /// # #![allow(unused_must_use)]
+ /// // don't do this:
+ /// (0..5).map(|x| println!("{}", x));
+ ///
+ /// // it won't even execute, as it is lazy. Rust will warn you about this.
+ ///
+ /// // Instead, use for:
+ /// for x in 0..5 {
+ /// println!("{}", x);
+ /// }
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn map<B, F>(self, f: F) -> Map<Self, F> where
+ Self: Sized, F: FnMut(Self::Item) -> B,
+ {
+ Map{iter: self, f: f}
+ }
+
+ /// Creates an iterator which uses a closure to determine if an element
+ /// should be yielded.
+ ///
+ /// The closure must return `true` or `false`. `filter()` creates an
+ /// iterator which calls this closure on each element. If the closure
+ /// returns `true`, then the element is returned. If the closure returns
+ /// `false`, it will try again, and call the closure on the next element,
+ /// seeing if it passes the test.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [0i32, 1, 2];
+ ///
+ /// let mut iter = a.into_iter().filter(|x| x.is_positive());
+ ///
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Because the closure passed to `filter()` takes a reference, and many
+ /// iterators iterate over references, this leads to a possibly confusing
+ /// situation, where the type of the closure is a double reference:
+ ///
+ /// ```
+ /// let a = [0, 1, 2];
+ ///
+ /// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
+ ///
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// It's common to instead use destructuring on the argument to strip away
+ /// one:
+ ///
+ /// ```
+ /// let a = [0, 1, 2];
+ ///
+ /// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
+ ///
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// or both:
+ ///
+ /// ```
+ /// let a = [0, 1, 2];
+ ///
+ /// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
+ ///
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// of these layers.
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn filter<P>(self, predicate: P) -> Filter<Self, P> where
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
+ {
+ Filter{iter: self, predicate: predicate}
+ }
+
+ /// Creates an iterator that both filters and maps.
+ ///
+ /// The closure must return an [`Option<T>`]. `filter_map()` creates an
+ /// iterator which calls this closure on each element. If the closure
+ /// returns `Some(element)`, then that element is returned. If the
+ /// closure returns `None`, it will try again, and call the closure on the
+ /// next element, seeing if it will return `Some`.
+ ///
+ /// [`Option<T>`]: ../../std/option/enum.Option.html
+ ///
+ /// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
+ /// part:
+ ///
+ /// [`filter()`]: #method.filter
+ /// [`map()`]: #method.map
+ ///
+ /// > If the closure returns `Some(element)`, then that element is returned.
+ ///
+ /// In other words, it removes the [`Option<T>`] layer automatically. If your
+ /// mapping is already returning an [`Option<T>`] and you want to skip over
+ /// `None`s, then `filter_map()` is much, much nicer to use.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = ["1", "2", "lol"];
+ ///
+ /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
+ ///
+ /// assert_eq!(iter.next(), Some(1));
+ /// assert_eq!(iter.next(), Some(2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Here's the same example, but with [`filter()`] and [`map()`]:
+ ///
+ /// ```
+ /// let a = ["1", "2", "lol"];
+ ///
+ /// let mut iter = a.iter()
+ /// .map(|s| s.parse().ok())
+ /// .filter(|s| s.is_some());
+ ///
+ /// assert_eq!(iter.next(), Some(Some(1)));
+ /// assert_eq!(iter.next(), Some(Some(2)));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// There's an extra layer of `Some` in there.
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
+ Self: Sized, F: FnMut(Self::Item) -> Option<B>,
+ {
+ FilterMap { iter: self, f: f }
+ }
+
+ /// Creates an iterator which gives the current iteration count as well as
+ /// the next value.
+ ///
+ /// The iterator returned yields pairs `(i, val)`, where `i` is the
+ /// current index of iteration and `val` is the value returned by the
+ /// iterator.
+ ///
+ /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
+ /// different sized integer, the [`zip()`] function provides similar
+ /// functionality.
+ ///
+ /// [`usize`]: ../../std/primitive.usize.html
+ /// [`zip()`]: #method.zip
+ ///
+ /// # Overflow Behavior
+ ///
+ /// The method does no guarding against overflows, so enumerating more than
+ /// [`usize::MAX`] elements either produces the wrong result or panics. If
+ /// debug assertions are enabled, a panic is guaranteed.
+ ///
+ /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
+ ///
+ /// # Panics
+ ///
+ /// The returned iterator might panic if the to-be-returned index would
+ /// overflow a `usize`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let a = ['a', 'b', 'c'];
+ ///
+ /// let mut iter = a.iter().enumerate();
+ ///
+ /// assert_eq!(iter.next(), Some((0, &'a')));
+ /// assert_eq!(iter.next(), Some((1, &'b')));
+ /// assert_eq!(iter.next(), Some((2, &'c')));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn enumerate(self) -> Enumerate<Self> where Self: Sized {
+ Enumerate { iter: self, count: 0 }
+ }
+
+ /// Creates an iterator which can use `peek` to look at the next element of
+ /// the iterator without consuming it.
+ ///
+ /// Adds a [`peek()`] method to an iterator. See its documentation for
+ /// more information.
+ ///
+ /// Note that the underlying iterator is still advanced when `peek` is
+ /// called for the first time: In order to retrieve the next element,
+ /// `next` is called on the underlying iterator, hence any side effects of
+ /// the `next` method will occur.
+ ///
+ /// [`peek()`]: struct.Peekable.html#method.peek
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let xs = [1, 2, 3];
+ ///
+ /// let mut iter = xs.iter().peekable();
+ ///
+ /// // peek() lets us see into the future
+ /// assert_eq!(iter.peek(), Some(&&1));
+ /// assert_eq!(iter.next(), Some(&1));
+ ///
+ /// assert_eq!(iter.next(), Some(&2));
+ ///
+ /// // we can peek() multiple times, the iterator won't advance
+ /// assert_eq!(iter.peek(), Some(&&3));
+ /// assert_eq!(iter.peek(), Some(&&3));
+ ///
+ /// assert_eq!(iter.next(), Some(&3));
+ ///
+ /// // after the iterator is finished, so is peek()
+ /// assert_eq!(iter.peek(), None);
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn peekable(self) -> Peekable<Self> where Self: Sized {
+ Peekable{iter: self, peeked: None}
+ }
+
+ /// Creates an iterator that [`skip()`]s elements based on a predicate.
+ ///
+ /// [`skip()`]: #method.skip
+ ///
+ /// `skip_while()` takes a closure as an argument. It will call this
+ /// closure on each element of the iterator, and ignore elements
+ /// until it returns `false`.
+ ///
+ /// After `false` is returned, `skip_while()`'s job is over, and the
+ /// rest of the elements are yielded.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [-1i32, 0, 1];
+ ///
+ /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
+ ///
+ /// assert_eq!(iter.next(), Some(&0));
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Because the closure passed to `skip_while()` takes a reference, and many
+ /// iterators iterate over references, this leads to a possibly confusing
+ /// situation, where the type of the closure is a double reference:
+ ///
+ /// ```
+ /// let a = [-1, 0, 1];
+ ///
+ /// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
+ ///
+ /// assert_eq!(iter.next(), Some(&0));
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Stopping after an initial `false`:
+ ///
+ /// ```
+ /// let a = [-1, 0, 1, -2];
+ ///
+ /// let mut iter = a.into_iter().skip_while(|x| **x < 0);
+ ///
+ /// assert_eq!(iter.next(), Some(&0));
+ /// assert_eq!(iter.next(), Some(&1));
+ ///
+ /// // while this would have been false, since we already got a false,
+ /// // skip_while() isn't used any more
+ /// assert_eq!(iter.next(), Some(&-2));
+ ///
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
+ {
+ SkipWhile{iter: self, flag: false, predicate: predicate}
+ }
+
+ /// Creates an iterator that yields elements based on a predicate.
+ ///
+ /// `take_while()` takes a closure as an argument. It will call this
+ /// closure on each element of the iterator, and yield elements
+ /// while it returns `true`.
+ ///
+ /// After `false` is returned, `take_while()`'s job is over, and the
+ /// rest of the elements are ignored.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [-1i32, 0, 1];
+ ///
+ /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
+ ///
+ /// assert_eq!(iter.next(), Some(&-1));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Because the closure passed to `take_while()` takes a reference, and many
+ /// iterators iterate over references, this leads to a possibly confusing
+ /// situation, where the type of the closure is a double reference:
+ ///
+ /// ```
+ /// let a = [-1, 0, 1];
+ ///
+ /// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
+ ///
+ /// assert_eq!(iter.next(), Some(&-1));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Stopping after an initial `false`:
+ ///
+ /// ```
+ /// let a = [-1, 0, 1, -2];
+ ///
+ /// let mut iter = a.into_iter().take_while(|x| **x < 0);
+ ///
+ /// assert_eq!(iter.next(), Some(&-1));
+ ///
+ /// // We have more elements that are less than zero, but since we already
+ /// // got a false, take_while() isn't used any more
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// Because `take_while()` needs to look at the value in order to see if it
+ /// should be included or not, consuming iterators will see that it is
+ /// removed:
+ ///
+ /// ```
+ /// let a = [1, 2, 3, 4];
+ /// let mut iter = a.into_iter();
+ ///
+ /// let result: Vec<i32> = iter.by_ref()
+ /// .take_while(|n| **n != 3)
+ /// .cloned()
+ /// .collect();
+ ///
+ /// assert_eq!(result, &[1, 2]);
+ ///
+ /// let result: Vec<i32> = iter.cloned().collect();
+ ///
+ /// assert_eq!(result, &[4]);
+ /// ```
+ ///
+ /// The `3` is no longer there, because it was consumed in order to see if
+ /// the iteration should stop, but wasn't placed back into the iterator or
+ /// some similar thing.
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
+ Self: Sized, P: FnMut(&Self::Item) -> bool,
+ {
+ TakeWhile{iter: self, flag: false, predicate: predicate}
+ }
+
+ /// Creates an iterator that skips the first `n` elements.
+ ///
+ /// After they have been consumed, the rest of the elements are yielded.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter().skip(2);
+ ///
+ /// assert_eq!(iter.next(), Some(&3));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
+ Skip{iter: self, n: n}
+ }
+
+ /// Creates an iterator that yields its first `n` elements.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter().take(2);
+ ///
+ /// assert_eq!(iter.next(), Some(&1));
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ ///
+ /// `take()` is often used with an infinite iterator, to make it finite:
+ ///
+ /// ```
+ /// let mut iter = (0..).take(3);
+ ///
+ /// assert_eq!(iter.next(), Some(0));
+ /// assert_eq!(iter.next(), Some(1));
+ /// assert_eq!(iter.next(), Some(2));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn take(self, n: usize) -> Take<Self> where Self: Sized, {
+ Take{iter: self, n: n}
+ }
+
+ /// An iterator adaptor similar to [`fold()`] that holds internal state and
+ /// produces a new iterator.
+ ///
+ /// [`fold()`]: #method.fold
+ ///
+ /// `scan()` takes two arguments: an initial value which seeds the internal
+ /// state, and a closure with two arguments, the first being a mutable
+ /// reference to the internal state and the second an iterator element.
+ /// The closure can assign to the internal state to share state between
+ /// iterations.
+ ///
+ /// On iteration, the closure will be applied to each element of the
+ /// iterator and the return value from the closure, an [`Option`], is
+ /// yielded by the iterator.
+ ///
+ /// [`Option`]: ../../std/option/enum.Option.html
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter().scan(1, |state, &x| {
+ /// // each iteration, we'll multiply the state by the element
+ /// *state = *state * x;
+ ///
+ /// // the value passed on to the next iteration
+ /// Some(*state)
+ /// });
+ ///
+ /// assert_eq!(iter.next(), Some(1));
+ /// assert_eq!(iter.next(), Some(2));
+ /// assert_eq!(iter.next(), Some(6));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ 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: f, state: initial_state}
+ }
+
+ /// Creates an iterator that works like map, but flattens nested structure.
+ ///
+ /// The [`map()`] adapter is very useful, but only when the closure
+ /// argument produces values. If it produces an iterator instead, there's
+ /// an extra layer of indirection. `flat_map()` will remove this extra layer
+ /// on its own.
+ ///
+ /// [`map()`]: #method.map
+ ///
+ /// Another way of thinking about `flat_map()`: [`map()`]'s closure returns
+ /// one item for each element, and `flat_map()`'s closure returns an
+ /// iterator for each element.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let words = ["alpha", "beta", "gamma"];
+ ///
+ /// // chars() returns an iterator
+ /// let merged: String = words.iter()
+ /// .flat_map(|s| s.chars())
+ /// .collect();
+ /// assert_eq!(merged, "alphabetagamma");
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
+ where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
+ {
+ FlatMap{iter: self, f: f, frontiter: None, backiter: None }
+ }
+
+ /// Creates an iterator which ends after the first `None`.
+ ///
+ /// After an iterator returns `None`, future calls may or may not yield
+ /// `Some(T)` again. `fuse()` adapts an iterator, ensuring that after a
+ /// `None` is given, it will always return `None` forever.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// // an iterator which alternates between Some and None
+ /// struct Alternate {
+ /// state: i32,
+ /// }
+ ///
+ /// impl Iterator for Alternate {
+ /// type Item = i32;
+ ///
+ /// fn next(&mut self) -> Option<i32> {
+ /// let val = self.state;
+ /// self.state = self.state + 1;
+ ///
+ /// // if it's even, Some(i32), else None
+ /// if val % 2 == 0 {
+ /// Some(val)
+ /// } else {
+ /// None
+ /// }
+ /// }
+ /// }
+ ///
+ /// let mut iter = Alternate { state: 0 };
+ ///
+ /// // we can see our iterator going back and forth
+ /// assert_eq!(iter.next(), Some(0));
+ /// assert_eq!(iter.next(), None);
+ /// assert_eq!(iter.next(), Some(2));
+ /// assert_eq!(iter.next(), None);
+ ///
+ /// // however, once we fuse it...
+ /// let mut iter = iter.fuse();
+ ///
+ /// assert_eq!(iter.next(), Some(4));
+ /// assert_eq!(iter.next(), None);
+ ///
+ /// // it will always return None after the first time.
+ /// assert_eq!(iter.next(), None);
+ /// assert_eq!(iter.next(), None);
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn fuse(self) -> Fuse<Self> where Self: Sized {
+ Fuse{iter: self, done: false}
+ }
+
+ /// Do something with each element of an iterator, passing the value on.
+ ///
+ /// When using iterators, you'll often chain several of them together.
+ /// While working on such code, you might want to check out what's
+ /// happening at various parts in the pipeline. To do that, insert
+ /// a call to `inspect()`.
+ ///
+ /// It's much more common for `inspect()` to be used as a debugging tool
+ /// than to exist in your final code, but never say never.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 4, 2, 3];
+ ///
+ /// // this iterator sequence is complex.
+ /// let sum = a.iter()
+ /// .cloned()
+ /// .filter(|&x| x % 2 == 0)
+ /// .fold(0, |sum, i| sum + i);
+ ///
+ /// println!("{}", sum);
+ ///
+ /// // let's add some inspect() calls to investigate what's happening
+ /// let sum = a.iter()
+ /// .cloned()
+ /// .inspect(|x| println!("about to filter: {}", x))
+ /// .filter(|&x| x % 2 == 0)
+ /// .inspect(|x| println!("made it through filter: {}", x))
+ /// .fold(0, |sum, i| sum + i);
+ ///
+ /// println!("{}", sum);
+ /// ```
+ ///
+ /// This will print:
+ ///
+ /// ```text
+ /// about to filter: 1
+ /// about to filter: 4
+ /// made it through filter: 4
+ /// about to filter: 2
+ /// made it through filter: 2
+ /// about to filter: 3
+ /// 6
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn inspect<F>(self, f: F) -> Inspect<Self, F> where
+ Self: Sized, F: FnMut(&Self::Item),
+ {
+ Inspect{iter: self, f: f}
+ }
+
+ /// Borrows an iterator, rather than consuming it.
+ ///
+ /// This is useful to allow applying iterator adaptors while still
+ /// retaining ownership of the original iterator.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let iter = a.into_iter();
+ ///
+ /// let sum: i32 = iter.take(5)
+ /// .fold(0, |acc, &i| acc + i );
+ ///
+ /// assert_eq!(sum, 6);
+ ///
+ /// // if we try to use iter again, it won't work. The following line
+ /// // gives "error: use of moved value: `iter`
+ /// // assert_eq!(iter.next(), None);
+ ///
+ /// // let's try that again
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.into_iter();
+ ///
+ /// // instead, we add in a .by_ref()
+ /// let sum: i32 = iter.by_ref()
+ /// .take(2)
+ /// .fold(0, |acc, &i| acc + i );
+ ///
+ /// assert_eq!(sum, 3);
+ ///
+ /// // now this is just fine:
+ /// assert_eq!(iter.next(), Some(&3));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
+
+ /// Transforms an iterator into a collection.
+ ///
+ /// `collect()` can take anything iterable, and turn it into a relevant
+ /// collection. This is one of the more powerful methods in the standard
+ /// library, used in a variety of contexts.
+ ///
+ /// The most basic pattern in which `collect()` is used is to turn one
+ /// collection into another. You take a collection, call `iter()` on it,
+ /// do a bunch of transformations, and then `collect()` at the end.
+ ///
+ /// One of the keys to `collect()`'s power is that many things you might
+ /// not think of as 'collections' actually are. For example, a [`String`]
+ /// is a collection of [`char`]s. And a collection of [`Result<T, E>`] can
+ /// be thought of as single `Result<Collection<T>, E>`. See the examples
+ /// below for more.
+ ///
+ /// [`String`]: ../../std/string/struct.String.html
+ /// [`Result<T, E>`]: ../../std/result/enum.Result.html
+ /// [`char`]: ../../std/primitive.char.html
+ ///
+ /// Because `collect()` is so general, it can cause problems with type
+ /// inference. As such, `collect()` is one of the few times you'll see
+ /// the syntax affectionately known as the 'turbofish': `::<>`. This
+ /// helps the inference algorithm understand specifically which collection
+ /// you're trying to collect into.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let doubled: Vec<i32> = a.iter()
+ /// .map(|&x| x * 2)
+ /// .collect();
+ ///
+ /// assert_eq!(vec![2, 4, 6], doubled);
+ /// ```
+ ///
+ /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
+ /// we could collect into, for example, a [`VecDeque<T>`] instead:
+ ///
+ /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
+ ///
+ /// ```
+ /// use std::collections::VecDeque;
+ ///
+ /// let a = [1, 2, 3];
+ ///
+ /// let doubled: VecDeque<i32> = a.iter()
+ /// .map(|&x| x * 2)
+ /// .collect();
+ ///
+ /// assert_eq!(2, doubled[0]);
+ /// assert_eq!(4, doubled[1]);
+ /// assert_eq!(6, doubled[2]);
+ /// ```
+ ///
+ /// Using the 'turbofish' instead of annotating `doubled`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let doubled = a.iter()
+ /// .map(|&x| x * 2)
+ /// .collect::<Vec<i32>>();
+ ///
+ /// assert_eq!(vec![2, 4, 6], doubled);
+ /// ```
+ ///
+ /// Because `collect()` cares about what you're collecting into, you can
+ /// still use a partial type hint, `_`, with the turbofish:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let doubled = a.iter()
+ /// .map(|&x| x * 2)
+ /// .collect::<Vec<_>>();
+ ///
+ /// assert_eq!(vec![2, 4, 6], doubled);
+ /// ```
+ ///
+ /// Using `collect()` to make a [`String`]:
+ ///
+ /// ```
+ /// let chars = ['g', 'd', 'k', 'k', 'n'];
+ ///
+ /// let hello: String = chars.iter()
+ /// .map(|&x| x as u8)
+ /// .map(|x| (x + 1) as char)
+ /// .collect();
+ ///
+ /// assert_eq!("hello", hello);
+ /// ```
+ ///
+ /// If you have a list of [`Result<T, E>`]s, you can use `collect()` to
+ /// see if any of them failed:
+ ///
+ /// ```
+ /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
+ ///
+ /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
+ ///
+ /// // gives us the first error
+ /// assert_eq!(Err("nope"), result);
+ ///
+ /// let results = [Ok(1), Ok(3)];
+ ///
+ /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
+ ///
+ /// // gives us the list of answers
+ /// assert_eq!(Ok(vec![1, 3]), result);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
+ FromIterator::from_iter(self)
+ }
+
+ /// Consumes an iterator, creating two collections from it.
+ ///
+ /// The predicate passed to `partition()` can return `true`, or `false`.
+ /// `partition()` returns a pair, all of the elements for which it returned
+ /// `true`, and all of the elements for which it returned `false`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let (even, odd): (Vec<i32>, Vec<i32>) = a.into_iter()
+ /// .partition(|&n| n % 2 == 0);
+ ///
+ /// assert_eq!(even, vec![2]);
+ /// assert_eq!(odd, vec![1, 3]);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn partition<B, F>(self, mut f: F) -> (B, B) where
+ Self: Sized,
+ B: Default + Extend<Self::Item>,
+ F: FnMut(&Self::Item) -> bool
+ {
+ let mut left: B = Default::default();
+ let mut right: B = Default::default();
+
+ for x in self {
+ if f(&x) {
+ left.extend(Some(x))
+ } else {
+ right.extend(Some(x))
+ }
+ }
+
+ (left, right)
+ }
+
+ /// An iterator adaptor that applies a function, producing a single, final value.
+ ///
+ /// `fold()` 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, `fold()`
+ /// 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.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// // the sum of all of the elements of a
+ /// let sum = a.iter()
+ /// .fold(0, |acc, &x| acc + x);
+ ///
+ /// assert_eq!(sum, 6);
+ /// ```
+ ///
+ /// Let's walk through each step of the iteration here:
+ ///
+ /// | element | acc | x | result |
+ /// |---------|-----|---|--------|
+ /// | | 0 | | |
+ /// | 1 | 0 | 1 | 1 |
+ /// | 2 | 1 | 2 | 3 |
+ /// | 3 | 3 | 3 | 6 |
+ ///
+ /// And so, our final result, `6`.
+ ///
+ /// It's common for people who haven't used iterators a lot to
+ /// use a `for` loop with a list of things to build up a result. Those
+ /// can be turned into `fold()`s:
+ ///
+ /// ```
+ /// let numbers = [1, 2, 3, 4, 5];
+ ///
+ /// let mut result = 0;
+ ///
+ /// // for loop:
+ /// for i in &numbers {
+ /// result = result + i;
+ /// }
+ ///
+ /// // fold:
+ /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
+ ///
+ /// // they're the same
+ /// assert_eq!(result, result2);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn fold<B, F>(self, init: B, mut f: F) -> B where
+ Self: Sized, F: FnMut(B, Self::Item) -> B,
+ {
+ let mut accum = init;
+ for x in self {
+ accum = f(accum, x);
+ }
+ accum
+ }
+
+ /// Tests if every element of the iterator matches a predicate.
+ ///
+ /// `all()` takes a closure that returns `true` or `false`. It applies
+ /// this closure to each element of the iterator, and if they all return
+ /// `true`, then so does `all()`. If any of them return `false`, it
+ /// returns `false`.
+ ///
+ /// `all()` is short-circuiting; in other words, it will stop processing
+ /// as soon as it finds a `false`, given that no matter what else happens,
+ /// the result will also be `false`.
+ ///
+ /// An empty iterator returns `true`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert!(a.iter().all(|&x| x > 0));
+ ///
+ /// assert!(!a.iter().all(|&x| x > 2));
+ /// ```
+ ///
+ /// Stopping at the first `false`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert!(!iter.all(|&x| x != 2));
+ ///
+ /// // we can still use `iter`, as there are more elements.
+ /// assert_eq!(iter.next(), Some(&3));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn all<F>(&mut self, mut f: F) -> bool where
+ Self: Sized, F: FnMut(Self::Item) -> bool
+ {
+ for x in self {
+ if !f(x) {
+ return false;
+ }
+ }
+ true
+ }
+
+ /// Tests if any element of the iterator matches a predicate.
+ ///
+ /// `any()` takes a closure that returns `true` or `false`. It applies
+ /// this closure to each element of the iterator, and if any of them return
+ /// `true`, then so does `any()`. If they all return `false`, it
+ /// returns `false`.
+ ///
+ /// `any()` is short-circuiting; in other words, it will stop processing
+ /// as soon as it finds a `true`, given that no matter what else happens,
+ /// the result will also be `true`.
+ ///
+ /// An empty iterator returns `false`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert!(a.iter().any(|&x| x > 0));
+ ///
+ /// assert!(!a.iter().any(|&x| x > 5));
+ /// ```
+ ///
+ /// Stopping at the first `true`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert!(iter.any(|&x| x != 2));
+ ///
+ /// // we can still use `iter`, as there are more elements.
+ /// assert_eq!(iter.next(), Some(&2));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn any<F>(&mut self, mut f: F) -> bool where
+ Self: Sized,
+ F: FnMut(Self::Item) -> bool
+ {
+ for x in self {
+ if f(x) {
+ return true;
+ }
+ }
+ false
+ }
+
+ /// Searches for an element of an iterator that satisfies a predicate.
+ ///
+ /// `find()` takes a closure that returns `true` or `false`. It applies
+ /// this closure to each element of the iterator, and if any of them return
+ /// `true`, then `find()` returns `Some(element)`. If they all return
+ /// `false`, it returns `None`.
+ ///
+ /// `find()` is short-circuiting; in other words, it will stop processing
+ /// as soon as the closure returns `true`.
+ ///
+ /// Because `find()` 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`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
+ ///
+ /// assert_eq!(a.iter().find(|&&x| x == 5), None);
+ /// ```
+ ///
+ /// Stopping at the first `true`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
+ ///
+ /// // we can still use `iter`, as there are more elements.
+ /// assert_eq!(iter.next(), Some(&3));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
+ Self: Sized,
+ P: FnMut(&Self::Item) -> bool,
+ {
+ for x in self {
+ if predicate(&x) { return Some(x) }
+ }
+ None
+ }
+
+ /// Searches for an element in an iterator, returning its index.
+ ///
+ /// `position()` takes a closure that returns `true` or `false`. It applies
+ /// this closure to each element of the iterator, and if one of them
+ /// returns `true`, then `position()` returns `Some(index)`. If all of
+ /// them return `false`, it returns `None`.
+ ///
+ /// `position()` is short-circuiting; in other words, it will stop
+ /// processing as soon as it finds a `true`.
+ ///
+ /// # Overflow Behavior
+ ///
+ /// The method does no guarding against overflows, so if there are more
+ /// than `usize::MAX` non-matching elements, it either produces the wrong
+ /// result or panics. If debug assertions are enabled, a panic is
+ /// guaranteed.
+ ///
+ /// # Panics
+ ///
+ /// This function might panic if the iterator has more than `usize::MAX`
+ /// non-matching elements.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
+ ///
+ /// assert_eq!(a.iter().position(|&x| x == 5), None);
+ /// ```
+ ///
+ /// Stopping at the first `true`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert_eq!(iter.position(|&x| x == 2), Some(1));
+ ///
+ /// // we can still use `iter`, as there are more elements.
+ /// assert_eq!(iter.next(), Some(&3));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
+ Self: Sized,
+ P: FnMut(Self::Item) -> bool,
+ {
+ // `enumerate` might overflow.
+ for (i, x) in self.enumerate() {
+ if predicate(x) {
+ return Some(i);
+ }
+ }
+ None
+ }
+
+ /// Searches for an element in an iterator from the right, returning its
+ /// index.
+ ///
+ /// `rposition()` takes a closure that returns `true` or `false`. It applies
+ /// this closure to each element of the iterator, starting from the end,
+ /// and if one of them returns `true`, then `rposition()` returns
+ /// `Some(index)`. If all of them return `false`, it returns `None`.
+ ///
+ /// `rposition()` is short-circuiting; in other words, it will stop
+ /// processing as soon as it finds a `true`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
+ ///
+ /// assert_eq!(a.iter().rposition(|&x| x == 5), None);
+ /// ```
+ ///
+ /// Stopping at the first `true`:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter();
+ ///
+ /// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
+ ///
+ /// // we can still use `iter`, as there are more elements.
+ /// assert_eq!(iter.next(), Some(&1));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
+ P: FnMut(Self::Item) -> bool,
+ Self: Sized + ExactSizeIterator + DoubleEndedIterator
+ {
+ let mut i = self.len();
+
+ while let Some(v) = self.next_back() {
+ if predicate(v) {
+ return Some(i - 1);
+ }
+ // No need for an overflow check here, because `ExactSizeIterator`
+ // implies that the number of elements fits into a `usize`.
+ i -= 1;
+ }
+ None
+ }
+
+ /// Returns the maximum element of an iterator.
+ ///
+ /// If the two elements are equally maximum, the latest element is
+ /// returned.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert_eq!(a.iter().max(), Some(&3));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
+ {
+ select_fold1(self,
+ |_| (),
+ // switch to y even if it is only equal, to preserve
+ // stability.
+ |_, x, _, y| *x <= *y)
+ .map(|(_, x)| x)
+ }
+
+ /// Returns the minimum element of an iterator.
+ ///
+ /// If the two elements are equally minimum, the first element is
+ /// returned.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// assert_eq!(a.iter().min(), Some(&1));
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
+ {
+ select_fold1(self,
+ |_| (),
+ // only switch to y if it is strictly smaller, to
+ // preserve stability.
+ |_, x, _, y| *x > *y)
+ .map(|(_, x)| x)
+ }
+
+ /// Returns the element that gives the maximum value from the
+ /// specified function.
+ ///
+ /// Returns the rightmost element if the comparison determines two elements
+ /// to be equally maximum.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let a = [-3_i32, 0, 1, 5, -10];
+ /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
+ /// ```
+ #[inline]
+ #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
+ fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
+ where Self: Sized, F: FnMut(&Self::Item) -> B,
+ {
+ select_fold1(self,
+ f,
+ // switch to y even if it is only equal, to preserve
+ // stability.
+ |x_p, _, y_p, _| x_p <= y_p)
+ .map(|(_, x)| x)
+ }
+
+ /// Returns the element that gives the minimum value from the
+ /// specified function.
+ ///
+ /// Returns the latest element if the comparison determines two elements
+ /// to be equally minimum.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let a = [-3_i32, 0, 1, 5, -10];
+ /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
+ /// ```
+ #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
+ fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
+ where Self: Sized, F: FnMut(&Self::Item) -> B,
+ {
+ select_fold1(self,
+ f,
+ // only switch to y if it is strictly smaller, to
+ // preserve stability.
+ |x_p, _, y_p, _| x_p > y_p)
+ .map(|(_, x)| x)
+ }
+
+ /// Reverses an iterator's direction.
+ ///
+ /// Usually, iterators iterate from left to right. After using `rev()`,
+ /// an iterator will instead iterate from right to left.
+ ///
+ /// This is only possible if the iterator has an end, so `rev()` only
+ /// works on [`DoubleEndedIterator`]s.
+ ///
+ /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut iter = a.iter().rev();
+ ///
+ /// assert_eq!(iter.next(), Some(&3));
+ /// assert_eq!(iter.next(), Some(&2));
+ /// assert_eq!(iter.next(), Some(&1));
+ ///
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
+ Rev{iter: self}
+ }
+
+ /// Converts an iterator of pairs into a pair of containers.
+ ///
+ /// `unzip()` consumes an entire iterator of pairs, producing two
+ /// collections: one from the left elements of the pairs, and one
+ /// from the right elements.
+ ///
+ /// This function is, in some sense, the opposite of [`zip()`].
+ ///
+ /// [`zip()`]: #method.zip
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [(1, 2), (3, 4)];
+ ///
+ /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
+ ///
+ /// assert_eq!(left, [1, 3]);
+ /// assert_eq!(right, [2, 4]);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
+ FromA: Default + Extend<A>,
+ FromB: Default + Extend<B>,
+ Self: Sized + Iterator<Item=(A, B)>,
+ {
+ struct SizeHint<A>(usize, Option<usize>, marker::PhantomData<A>);
+ impl<A> Iterator for SizeHint<A> {
+ type Item = A;
+
+ fn next(&mut self) -> Option<A> { None }
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (self.0, self.1)
+ }
+ }
+
+ let (lo, hi) = self.size_hint();
+ let mut ts: FromA = Default::default();
+ let mut us: FromB = Default::default();
+
+ ts.extend(SizeHint(lo, hi, marker::PhantomData));
+ us.extend(SizeHint(lo, hi, marker::PhantomData));
+
+ for (t, u) in self {
+ ts.extend(Some(t));
+ us.extend(Some(u));
+ }
+
+ (ts, us)
+ }
+
+ /// Creates an iterator which `clone()`s all of its elements.
+ ///
+ /// This is useful when you have an iterator over `&T`, but you need an
+ /// iterator over `T`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let v_cloned: Vec<_> = a.iter().cloned().collect();
+ ///
+ /// // cloned is the same as .map(|&x| x), for integers
+ /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
+ ///
+ /// assert_eq!(v_cloned, vec![1, 2, 3]);
+ /// assert_eq!(v_map, vec![1, 2, 3]);
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ fn cloned<'a, T: 'a>(self) -> Cloned<Self>
+ where Self: Sized + Iterator<Item=&'a T>, T: Clone
+ {
+ Cloned { it: self }
+ }
+
+ /// Repeats an iterator endlessly.
+ ///
+ /// Instead of stopping at `None`, the iterator will instead start again,
+ /// from the beginning. After iterating again, it will start at the
+ /// beginning again. And again. And again. Forever.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let a = [1, 2, 3];
+ ///
+ /// let mut it = a.iter().cycle();
+ ///
+ /// assert_eq!(it.next(), Some(&1));
+ /// assert_eq!(it.next(), Some(&2));
+ /// assert_eq!(it.next(), Some(&3));
+ /// assert_eq!(it.next(), Some(&1));
+ /// assert_eq!(it.next(), Some(&2));
+ /// assert_eq!(it.next(), Some(&3));
+ /// assert_eq!(it.next(), Some(&1));
+ /// ```
+ #[stable(feature = "rust1", since = "1.0.0")]
+ #[inline]
+ fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
+ Cycle{orig: self.clone(), iter: self}
+ }
+
+ /// Sums the elements of an iterator.
+ ///
+ /// Takes each element, adds them together, and returns the result.
+ ///
+ /// An empty iterator returns the zero value of the type.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// #![feature(iter_arith)]
+ ///
+ /// let a = [1, 2, 3];
+ /// let sum: i32 = a.iter().sum();
+ ///
+ /// assert_eq!(sum, 6);
+ /// ```
+ #[unstable(feature = "iter_arith", reason = "bounds recently changed",
+ issue = "27739")]
+ fn sum<S>(self) -> S where
+ S: Add<Self::Item, Output=S> + Zero,
+ Self: Sized,
+ {
+ self.fold(Zero::zero(), |s, e| s + e)
+ }
+
+ /// Iterates over the entire iterator, multiplying all the elements
+ ///
+ /// An empty iterator returns the one value of the type.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// #![feature(iter_arith)]
+ ///
+ /// fn factorial(n: u32) -> u32 {
+ /// (1..).take_while(|&i| i <= n).product()
+ /// }
+ /// assert_eq!(factorial(0), 1);
+ /// assert_eq!(factorial(1), 1);
+ /// assert_eq!(factorial(5), 120);
+ /// ```
+ #[unstable(feature="iter_arith", reason = "bounds recently changed",
+ issue = "27739")]
+ fn product<P>(self) -> P where
+ P: Mul<Self::Item, Output=P> + One,
+ Self: Sized,
+ {
+ self.fold(One::one(), |p, e| p * e)
+ }
+
+ /// Lexicographically compares the elements of this `Iterator` with those
+ /// of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn cmp<I>(mut self, other: I) -> Ordering where
+ I: IntoIterator<Item = Self::Item>,
+ Self::Item: Ord,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return Ordering::Equal,
+ (None, _ ) => return Ordering::Less,
+ (_ , None) => return Ordering::Greater,
+ (Some(x), Some(y)) => match x.cmp(&y) {
+ Ordering::Equal => (),
+ non_eq => return non_eq,
+ },
+ }
+ }
+ }
+
+ /// Lexicographically compares the elements of this `Iterator` with those
+ /// of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
+ I: IntoIterator,
+ Self::Item: PartialOrd<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return Some(Ordering::Equal),
+ (None, _ ) => return Some(Ordering::Less),
+ (_ , None) => return Some(Ordering::Greater),
+ (Some(x), Some(y)) => match x.partial_cmp(&y) {
+ Some(Ordering::Equal) => (),
+ non_eq => return non_eq,
+ },
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are equal to those of
+ /// another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn eq<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialEq<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return true,
+ (None, _) | (_, None) => return false,
+ (Some(x), Some(y)) => if x != y { return false },
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are unequal to those of
+ /// another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn ne<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialEq<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return false,
+ (None, _) | (_, None) => return true,
+ (Some(x), Some(y)) => if x.ne(&y) { return true },
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are lexicographically
+ /// less than those of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn lt<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialOrd<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return false,
+ (None, _ ) => return true,
+ (_ , None) => return false,
+ (Some(x), Some(y)) => {
+ match x.partial_cmp(&y) {
+ Some(Ordering::Less) => return true,
+ Some(Ordering::Equal) => {}
+ Some(Ordering::Greater) => return false,
+ None => return false,
+ }
+ },
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are lexicographically
+ /// less or equal to those of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn le<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialOrd<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return true,
+ (None, _ ) => return true,
+ (_ , None) => return false,
+ (Some(x), Some(y)) => {
+ match x.partial_cmp(&y) {
+ Some(Ordering::Less) => return true,
+ Some(Ordering::Equal) => {}
+ Some(Ordering::Greater) => return false,
+ None => return false,
+ }
+ },
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are lexicographically
+ /// greater than those of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn gt<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialOrd<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return false,
+ (None, _ ) => return false,
+ (_ , None) => return true,
+ (Some(x), Some(y)) => {
+ match x.partial_cmp(&y) {
+ Some(Ordering::Less) => return false,
+ Some(Ordering::Equal) => {}
+ Some(Ordering::Greater) => return true,
+ None => return false,
+ }
+ }
+ }
+ }
+ }
+
+ /// Determines if the elements of this `Iterator` are lexicographically
+ /// greater than or equal to those of another.
+ #[stable(feature = "iter_order", since = "1.5.0")]
+ fn ge<I>(mut self, other: I) -> bool where
+ I: IntoIterator,
+ Self::Item: PartialOrd<I::Item>,
+ Self: Sized,
+ {
+ let mut other = other.into_iter();
+
+ loop {
+ match (self.next(), other.next()) {
+ (None, None) => return true,
+ (None, _ ) => return false,
+ (_ , None) => return true,
+ (Some(x), Some(y)) => {
+ match x.partial_cmp(&y) {
+ Some(Ordering::Less) => return false,
+ Some(Ordering::Equal) => {}
+ Some(Ordering::Greater) => return true,
+ None => return false,
+ }
+ },
+ }
+ }
+ }
+}
+
+/// Select an element from an iterator based on the given projection
+/// and "comparison" function.
+///
+/// This is an idiosyncratic helper to try to factor out the
+/// commonalities of {max,min}{,_by}. In particular, this avoids
+/// having to implement optimizations several times.
+#[inline]
+fn select_fold1<I,B, FProj, FCmp>(mut it: I,
+ mut f_proj: FProj,
+ mut f_cmp: FCmp) -> Option<(B, I::Item)>
+ where I: Iterator,
+ FProj: FnMut(&I::Item) -> B,
+ FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
+{
+ // start with the first element as our selection. This avoids
+ // having to use `Option`s inside the loop, translating to a
+ // sizeable performance gain (6x in one case).
+ it.next().map(|mut sel| {
+ let mut sel_p = f_proj(&sel);
+
+ for x in it {
+ let x_p = f_proj(&x);
+ if f_cmp(&sel_p, &sel, &x_p, &x) {
+ sel = x;
+ sel_p = x_p;
+ }
+ }
+ (sel_p, sel)
+ })
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, I: Iterator + ?Sized> Iterator for &'a mut I {
+ type Item = I::Item;
+ fn next(&mut self) -> Option<I::Item> { (**self).next() }
+ fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
+}
diff --git a/libcore/iter/mod.rs b/libcore/iter/mod.rs
new file mode 100644
index 0000000..abc199c
--- /dev/null
+++ b/libcore/iter/mod.rs
@@ -0,0 +1,1657 @@
+// 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.
+
+//! Composable external iteration.
+//!
+//! If you've found yourself with a collection of some kind, and needed to
+//! perform an operation on the elements of said collection, you'll quickly run
+//! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
+//! it's worth becoming familiar with them.
+//!
+//! Before explaining more, let's talk about how this module is structured:
+//!
+//! # Organization
+//!
+//! This module is largely organized by type:
+//!
+//! * [Traits] are the core portion: these traits define what kind of iterators
+//! exist and what you can do with them. The methods of these traits are worth
+//! putting some extra study time into.
+//! * [Functions] provide some helpful ways to create some basic iterators.
+//! * [Structs] are often the return types of the various methods on this
+//! module's traits. You'll usually want to look at the method that creates
+//! the `struct`, rather than the `struct` itself. For more detail about why,
+//! see '[Implementing Iterator](#implementing-iterator)'.
+//!
+//! [Traits]: #traits
+//! [Functions]: #functions
+//! [Structs]: #structs
+//!
+//! That's it! Let's dig into iterators.
+//!
+//! # Iterator
+//!
+//! The heart and soul of this module is the [`Iterator`] trait. The core of
+//! [`Iterator`] looks like this:
+//!
+//! ```
+//! trait Iterator {
+//! type Item;
+//! fn next(&mut self) -> Option<Self::Item>;
+//! }
+//! ```
+//!
+//! An iterator has a method, [`next()`], which when called, returns an
+//! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
+//! are elements, and once they've all been exhausted, will return `None` to
+//! indicate that iteration is finished. Individual iterators may choose to
+//! resume iteration, and so calling [`next()`] again may or may not eventually
+//! start returning `Some(Item)` again at some point.
+//!
+//! [`Iterator`]'s full definition includes a number of other methods as well,
+//! but they are default methods, built on top of [`next()`], and so you get
+//! them for free.
+//!
+//! Iterators are also composable, and it's common to chain them together to do
+//! more complex forms of processing. See the [Adapters](#adapters) section
+//! below for more details.
+//!
+//! [`Iterator`]: trait.Iterator.html
+//! [`next()`]: trait.Iterator.html#tymethod.next
+//! [`Option`]: ../../std/option/enum.Option.html
+//!
+//! # The three forms of iteration
+//!
+//! There are three common methods which can create iterators from a collection:
+//!
+//! * `iter()`, which iterates over `&T`.
+//! * `iter_mut()`, which iterates over `&mut T`.
+//! * `into_iter()`, which iterates over `T`.
+//!
+//! Various things in the standard library may implement one or more of the
+//! three, where appropriate.
+//!
+//! # Implementing Iterator
+//!
+//! Creating an iterator of your own involves two steps: creating a `struct` to
+//! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
+//! `struct`. This is why there are so many `struct`s in this module: there is
+//! one for each iterator and iterator adapter.
+//!
+//! Let's make an iterator named `Counter` which counts from `1` to `5`:
+//!
+//! ```
+//! // First, the struct:
+//!
+//! /// An iterator which counts from one to five
+//! struct Counter {
+//! count: usize,
+//! }
+//!
+//! // we want our count to start at one, so let's add a new() method to help.
+//! // This isn't strictly necessary, but is convenient. Note that we start
+//! // `count` at zero, we'll see why in `next()`'s implementation below.
+//! impl Counter {
+//! fn new() -> Counter {
+//! Counter { count: 0 }
+//! }
+//! }
+//!
+//! // Then, we implement `Iterator` for our `Counter`:
+//!
+//! impl Iterator for Counter {
+//! // we will be counting with usize
+//! type Item = usize;
+//!
+//! // next() is the only required method
+//! fn next(&mut self) -> Option<usize> {
+//! // increment our count. This is why we started at zero.
+//! self.count += 1;
+//!
+//! // check to see if we've finished counting or not.
+//! if self.count < 6 {
+//! Some(self.count)
+//! } else {
+//! None
+//! }
+//! }
+//! }
+//!
+//! // And now we can use it!
+//!
+//! let mut counter = Counter::new();
+//!
+//! let x = counter.next().unwrap();
+//! println!("{}", x);
+//!
+//! let x = counter.next().unwrap();
+//! println!("{}", x);
+//!
+//! let x = counter.next().unwrap();
+//! println!("{}", x);
+//!
+//! let x = counter.next().unwrap();
+//! println!("{}", x);
+//!
+//! let x = counter.next().unwrap();
+//! println!("{}", x);
+//! ```
+//!
+//! This will print `1` through `5`, each on their own line.
+//!
+//! Calling `next()` this way gets repetitive. Rust has a construct which can
+//! call `next()` on your iterator, until it reaches `None`. Let's go over that
+//! next.
+//!
+//! # for Loops and IntoIterator
+//!
+//! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
+//! example of `for`:
+//!
+//! ```
+//! let values = vec![1, 2, 3, 4, 5];
+//!
+//! for x in values {
+//! println!("{}", x);
+//! }
+//! ```
+//!
+//! This will print the numbers one through five, each on their own line. But
+//! you'll notice something here: we never called anything on our vector to
+//! produce an iterator. What gives?
+//!
+//! There's a trait in the standard library for converting something into an
+//! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
+//! which converts the thing implementing [`IntoIterator`] into an iterator.
+//! Let's take a look at that `for` loop again, and what the compiler converts
+//! it into:
+//!
+//! [`IntoIterator`]: trait.IntoIterator.html
+//! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
+//!
+//! ```
+//! let values = vec![1, 2, 3, 4, 5];
+//!
+//! for x in values {
+//! println!("{}", x);
+//! }
+//! ```
+//!
+//! Rust de-sugars this into:
+//!
+//! ```
+//! let values = vec![1, 2, 3, 4, 5];
+//! {
+//! let result = match IntoIterator::into_iter(values) {
+//! mut iter => loop {
+//! match iter.next() {
+//! Some(x) => { println!("{}", x); },
+//! None => break,
+//! }
+//! },
+//! };
+//! result
+//! }
+//! ```
+//!
+//! First, we call `into_iter()` on the value. Then, we match on the iterator
+//! that returns, calling [`next()`] over and over until we see a `None`. At
+//! that point, we `break` out of the loop, and we're done iterating.
+//!
+//! There's one more subtle bit here: the standard library contains an
+//! interesting implementation of [`IntoIterator`]:
+//!
+//! ```ignore
+//! impl<I: Iterator> IntoIterator for I
+//! ```
+//!
+//! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
+//! returning themselves. This means two things:
+//!
+//! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
+//! 2. If you're creating a collection, implementing [`IntoIterator`] for it
+//! will allow your collection to be used with the `for` loop.
+//!
+//! # Adapters
+//!
+//! Functions which take an [`Iterator`] and return another [`Iterator`] are
+//! often called 'iterator adapters', as they're a form of the 'adapter
+//! pattern'.
+//!
+//! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
+//! For more, see their documentation.
+//!
+//! [`map()`]: trait.Iterator.html#method.map
+//! [`take()`]: trait.Iterator.html#method.take
+//! [`collect()`]: trait.Iterator.html#method.collect
+//!
+//! # Laziness
+//!
+//! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
+//! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
+//! until you call [`next()`]. This is sometimes a source of confusion when
+//! creating an iterator solely for its side effects. For example, the [`map()`]
+//! method calls a closure on each element it iterates over:
+//!
+//! ```
+//! # #![allow(unused_must_use)]
+//! let v = vec![1, 2, 3, 4, 5];
+//! v.iter().map(|x| println!("{}", x));
+//! ```
+//!
+//! This will not print any values, as we only created an iterator, rather than
+//! using it. The compiler will warn us about this kind of behavior:
+//!
+//! ```text
+//! warning: unused result which must be used: iterator adaptors are lazy and
+//! do nothing unless consumed
+//! ```
+//!
+//! The idiomatic way to write a [`map()`] for its side effects is to use a
+//! `for` loop instead:
+//!
+//! ```
+//! let v = vec![1, 2, 3, 4, 5];
+//!
+//! for x in &v {
+//! println!("{}", x);
+//! }
+//! ```
+//!
+//! [`map()`]: trait.Iterator.html#method.map
+//!
+//! The two most common ways to evaluate an iterator are to use a `for` loop
+//! like this, or using the [`collect()`] adapter to produce a new collection.
+//!
+//! [`collect()`]: trait.Iterator.html#method.collect
+//!
+//! # Infinity
+//!
+//! Iterators do not have to be finite. As an example, an open-ended range is
+//! an infinite iterator:
+//!
+//! ```
+//! let numbers = 0..;
+//! ```
+//!
+//! It is common to use the [`take()`] iterator adapter to turn an infinite
+//! iterator into a finite one:
+//!
+//! ```
+//! let numbers = 0..;
+//! let five_numbers = numbers.take(5);
+//!
+//! for number in five_numbers {
+//! println!("{}", number);
+//! }
+//! ```
+//!
+//! This will print the numbers `0` through `4`, each on their own line.
+//!
+//! [`take()`]: trait.Iterator.html#method.take
+
+#![stable(feature = "rust1", since = "1.0.0")]
+
+use clone::Clone;
+use cmp;
+use fmt;
+use ops::FnMut;
+use option::Option::{self, Some, None};
+use usize;
+
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::iterator::Iterator;
+
+#[unstable(feature = "step_trait",
+ reason = "likely to be replaced by finer-grained traits",
+ issue = "27741")]
+pub use self::range::Step;
+#[unstable(feature = "step_by", reason = "recent addition",
+ issue = "27741")]
+pub use self::range::StepBy;
+
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::sources::{Repeat, repeat};
+#[stable(feature = "iter_empty", since = "1.2.0")]
+pub use self::sources::{Empty, empty};
+#[stable(feature = "iter_once", since = "1.2.0")]
+pub use self::sources::{Once, once};
+
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use self::traits::{FromIterator, IntoIterator, DoubleEndedIterator, Extend,
+ ExactSizeIterator};
+
+mod iterator;
+mod range;
+mod sources;
+mod traits;
+
+/// An double-ended iterator with the direction inverted.
+///
+/// This `struct` is created by the [`rev()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`rev()`]: trait.Iterator.html#method.rev
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Rev<T> {
+ iter: T
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Rev<I> where I: DoubleEndedIterator {
+ type Item = <I as Iterator>::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next_back() }
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> DoubleEndedIterator for Rev<I> where I: DoubleEndedIterator {
+ #[inline]
+ fn next_back(&mut self) -> Option<<I as Iterator>::Item> { self.iter.next() }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> ExactSizeIterator for Rev<I>
+ where I: ExactSizeIterator + DoubleEndedIterator {}
+
+/// An iterator that clones the elements of an underlying iterator.
+///
+/// This `struct` is created by the [`cloned()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`cloned()`]: trait.Iterator.html#method.cloned
+/// [`Iterator`]: trait.Iterator.html
+#[stable(feature = "iter_cloned", since = "1.1.0")]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[derive(Clone, Debug)]
+pub struct Cloned<I> {
+ it: I,
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, I, T: 'a> Iterator for Cloned<I>
+ where I: Iterator<Item=&'a T>, T: Clone
+{
+ type Item = T;
+
+ fn next(&mut self) -> Option<T> {
+ self.it.next().cloned()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.it.size_hint()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, I, T: 'a> DoubleEndedIterator for Cloned<I>
+ where I: DoubleEndedIterator<Item=&'a T>, T: Clone
+{
+ fn next_back(&mut self) -> Option<T> {
+ self.it.next_back().cloned()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<'a, I, T: 'a> ExactSizeIterator for Cloned<I>
+ where I: ExactSizeIterator<Item=&'a T>, T: Clone
+{}
+
+/// An iterator that repeats endlessly.
+///
+/// This `struct` is created by the [`cycle()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`cycle()`]: trait.Iterator.html#method.cycle
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Cycle<I> {
+ orig: I,
+ iter: I,
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
+ type Item = <I as Iterator>::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<<I as Iterator>::Item> {
+ match self.iter.next() {
+ None => { self.iter = self.orig.clone(); self.iter.next() }
+ y => y
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ // the cycle iterator is either empty or infinite
+ match self.orig.size_hint() {
+ sz @ (0, Some(0)) => sz,
+ (0, _) => (0, None),
+ _ => (usize::MAX, None)
+ }
+ }
+}
+
+/// 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 = "iterator adaptors 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,
+}
+
+// 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]
+ 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(),
+ }
+ }
+
+ #[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 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(),
+ }
+ }
+}
+
+/// 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 = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Zip<A, B> {
+ a: A,
+ b: B
+}
+
+#[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<(A::Item, B::Item)> {
+ self.a.next().and_then(|x| {
+ self.b.next().and_then(|y| {
+ Some((x, y))
+ })
+ })
+ }
+
+ #[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 = 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)
+ }
+}
+
+#[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)> {
+ 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!(),
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<A, B> ExactSizeIterator for Zip<A, B>
+ where A: ExactSizeIterator, B: ExactSizeIterator {}
+
+/// An iterator that maps the values of `iter` with `f`.
+///
+/// This `struct` is created by the [`map()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`map()`]: trait.Iterator.html#method.map
+/// [`Iterator`]: trait.Iterator.html
+///
+/// # Notes about side effects
+///
+/// The [`map()`] iterator implements [`DoubleEndedIterator`], meaning that
+/// you can also [`map()`] backwards:
+///
+/// ```rust
+/// let v: Vec<i32> = vec![1, 2, 3].into_iter().rev().map(|x| x + 1).collect();
+///
+/// assert_eq!(v, [4, 3, 2]);
+/// ```
+///
+/// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
+///
+/// But if your closure has state, iterating backwards may act in a way you do
+/// not expect. Let's go through an example. First, in the forward direction:
+///
+/// ```rust
+/// let mut c = 0;
+///
+/// for pair in vec!['a', 'b', 'c'].into_iter()
+/// .map(|letter| { c += 1; (letter, c) }) {
+/// println!("{:?}", pair);
+/// }
+/// ```
+///
+/// This will print "('a', 1), ('b', 2), ('c', 3)".
+///
+/// Now consider this twist where we add a call to `rev`. This version will
+/// print `('c', 1), ('b', 2), ('a', 3)`. Note that the letters are reversed,
+/// but the values of the counter still go in order. This is because `map()` is
+/// still being called lazilly on each item, but we are popping items off the
+/// back of the vector now, instead of shifting them from the front.
+///
+/// ```rust
+/// let mut c = 0;
+///
+/// for pair in vec!['a', 'b', 'c'].into_iter()
+/// .map(|letter| { c += 1; (letter, c) })
+/// .rev() {
+/// println!("{:?}", pair);
+/// }
+/// ```
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Map<I, F> {
+ iter: I,
+ f: F,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, F> fmt::Debug for Map<I, F> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Map")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I: Iterator, F> Iterator for Map<I, F> where F: FnMut(I::Item) -> B {
+ type Item = B;
+
+ #[inline]
+ fn next(&mut self) -> Option<B> {
+ self.iter.next().map(&mut self.f)
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for Map<I, F> where
+ F: FnMut(I::Item) -> B,
+{
+ #[inline]
+ fn next_back(&mut self) -> Option<B> {
+ self.iter.next_back().map(&mut self.f)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I: ExactSizeIterator, F> ExactSizeIterator for Map<I, F>
+ where F: FnMut(I::Item) -> B {}
+
+/// An iterator that filters the elements of `iter` with `predicate`.
+///
+/// This `struct` is created by the [`filter()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`filter()`]: trait.Iterator.html#method.filter
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Filter<I, P> {
+ iter: I,
+ predicate: P,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Filter")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool {
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ for x in self.iter.by_ref() {
+ if (self.predicate)(&x) {
+ return Some(x);
+ }
+ }
+ None
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the predicate
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: DoubleEndedIterator, P> DoubleEndedIterator for Filter<I, P>
+ where P: FnMut(&I::Item) -> bool,
+{
+ #[inline]
+ fn next_back(&mut self) -> Option<I::Item> {
+ for x in self.iter.by_ref().rev() {
+ if (self.predicate)(&x) {
+ return Some(x);
+ }
+ }
+ None
+ }
+}
+
+/// An iterator that uses `f` to both filter and map elements from `iter`.
+///
+/// This `struct` is created by the [`filter_map()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`filter_map()`]: trait.Iterator.html#method.filter_map
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct FilterMap<I, F> {
+ iter: I,
+ f: F,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, F> fmt::Debug for FilterMap<I, F> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("FilterMap")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I: Iterator, F> Iterator for FilterMap<I, F>
+ where F: FnMut(I::Item) -> Option<B>,
+{
+ type Item = B;
+
+ #[inline]
+ fn next(&mut self) -> Option<B> {
+ for x in self.iter.by_ref() {
+ if let Some(y) = (self.f)(x) {
+ return Some(y);
+ }
+ }
+ None
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the predicate
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I: DoubleEndedIterator, F> DoubleEndedIterator for FilterMap<I, F>
+ where F: FnMut(I::Item) -> Option<B>,
+{
+ #[inline]
+ fn next_back(&mut self) -> Option<B> {
+ for x in self.iter.by_ref().rev() {
+ if let Some(y) = (self.f)(x) {
+ return Some(y);
+ }
+ }
+ None
+ }
+}
+
+/// An iterator that yields the current count and the element during iteration.
+///
+/// This `struct` is created by the [`enumerate()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`enumerate()`]: trait.Iterator.html#method.enumerate
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Enumerate<I> {
+ iter: I,
+ count: usize,
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Enumerate<I> where I: Iterator {
+ type Item = (usize, <I as Iterator>::Item);
+
+ /// # Overflow Behavior
+ ///
+ /// The method does no guarding against overflows, so enumerating more than
+ /// `usize::MAX` elements either produces the wrong result or panics. If
+ /// debug assertions are enabled, a panic is guaranteed.
+ ///
+ /// # Panics
+ ///
+ /// Might panic if the index of the element overflows a `usize`.
+ #[inline]
+ fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
+ self.iter.next().map(|a| {
+ let ret = (self.count, a);
+ // Possible undefined overflow.
+ self.count += 1;
+ ret
+ })
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+
+ #[inline]
+ fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
+ self.iter.nth(n).map(|a| {
+ let i = self.count + n;
+ self.count = i + 1;
+ (i, a)
+ })
+ }
+
+ #[inline]
+ fn count(self) -> usize {
+ self.iter.count()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> DoubleEndedIterator for Enumerate<I> where
+ I: ExactSizeIterator + DoubleEndedIterator
+{
+ #[inline]
+ fn next_back(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
+ self.iter.next_back().map(|a| {
+ let len = self.iter.len();
+ // Can safely add, `ExactSizeIterator` promises that the number of
+ // elements fits into a `usize`.
+ (self.count + len, a)
+ })
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> ExactSizeIterator for Enumerate<I> where I: ExactSizeIterator {}
+
+/// An iterator with a `peek()` that returns an optional reference to the next
+/// element.
+///
+/// This `struct` is created by the [`peekable()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`peekable()`]: trait.Iterator.html#method.peekable
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Peekable<I: Iterator> {
+ iter: I,
+ peeked: Option<I::Item>,
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator> Iterator for Peekable<I> {
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ match self.peeked {
+ Some(_) => self.peeked.take(),
+ None => self.iter.next(),
+ }
+ }
+
+ #[inline]
+ fn count(self) -> usize {
+ (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
+ }
+
+ #[inline]
+ fn nth(&mut self, n: usize) -> Option<I::Item> {
+ match self.peeked {
+ Some(_) if n == 0 => self.peeked.take(),
+ Some(_) => {
+ self.peeked = None;
+ self.iter.nth(n-1)
+ },
+ None => self.iter.nth(n)
+ }
+ }
+
+ #[inline]
+ fn last(self) -> Option<I::Item> {
+ self.iter.last().or(self.peeked)
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (lo, hi) = self.iter.size_hint();
+ if self.peeked.is_some() {
+ let lo = lo.saturating_add(1);
+ let hi = hi.and_then(|x| x.checked_add(1));
+ (lo, hi)
+ } else {
+ (lo, hi)
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: ExactSizeIterator> ExactSizeIterator for Peekable<I> {}
+
+impl<I: Iterator> Peekable<I> {
+ /// Returns a reference to the next() value without advancing the iterator.
+ ///
+ /// The `peek()` method will return the value that a call to [`next()`] would
+ /// return, but does not advance the iterator. Like [`next()`], if there is
+ /// a value, it's wrapped in a `Some(T)`, but if the iterator is over, it
+ /// will return `None`.
+ ///
+ /// [`next()`]: trait.Iterator.html#tymethod.next
+ ///
+ /// Because `peek()` returns reference, and many iterators iterate over
+ /// references, this leads to a possibly confusing situation where the
+ /// return value is a double reference. You can see this effect in the
+ /// examples below, with `&&i32`.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// let xs = [1, 2, 3];
+ ///
+ /// let mut iter = xs.iter().peekable();
+ ///
+ /// // peek() lets us see into the future
+ /// assert_eq!(iter.peek(), Some(&&1));
+ /// assert_eq!(iter.next(), Some(&1));
+ ///
+ /// assert_eq!(iter.next(), Some(&2));
+ ///
+ /// // we can peek() multiple times, the iterator won't advance
+ /// assert_eq!(iter.peek(), Some(&&3));
+ /// assert_eq!(iter.peek(), Some(&&3));
+ ///
+ /// assert_eq!(iter.next(), Some(&3));
+ ///
+ /// // after the iterator is finished, so is peek()
+ /// assert_eq!(iter.peek(), None);
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ #[stable(feature = "rust1", since = "1.0.0")]
+ pub fn peek(&mut self) -> Option<&I::Item> {
+ if self.peeked.is_none() {
+ self.peeked = self.iter.next();
+ }
+ match self.peeked {
+ Some(ref value) => Some(value),
+ None => None,
+ }
+ }
+
+ /// Checks if the iterator has finished iterating.
+ ///
+ /// Returns `true` if there are no more elements in the iterator, and
+ /// `false` if there are.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// #![feature(peekable_is_empty)]
+ ///
+ /// let xs = [1, 2, 3];
+ ///
+ /// let mut iter = xs.iter().peekable();
+ ///
+ /// // there are still elements to iterate over
+ /// assert_eq!(iter.is_empty(), false);
+ ///
+ /// // let's consume the iterator
+ /// iter.next();
+ /// iter.next();
+ /// iter.next();
+ ///
+ /// assert_eq!(iter.is_empty(), true);
+ /// ```
+ #[unstable(feature = "peekable_is_empty", issue = "32111")]
+ #[inline]
+ pub fn is_empty(&mut self) -> bool {
+ self.peek().is_none()
+ }
+}
+
+/// An iterator that rejects elements while `predicate` is true.
+///
+/// This `struct` is created by the [`skip_while()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`skip_while()`]: trait.Iterator.html#method.skip_while
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct SkipWhile<I, P> {
+ iter: I,
+ flag: bool,
+ predicate: P,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, P> fmt::Debug for SkipWhile<I, P> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("SkipWhile")
+ .field("iter", &self.iter)
+ .field("flag", &self.flag)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator, P> Iterator for SkipWhile<I, P>
+ where P: FnMut(&I::Item) -> bool
+{
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ for x in self.iter.by_ref() {
+ if self.flag || !(self.predicate)(&x) {
+ self.flag = true;
+ return Some(x);
+ }
+ }
+ None
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the predicate
+ }
+}
+
+/// An iterator that only accepts elements while `predicate` is true.
+///
+/// This `struct` is created by the [`take_while()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`take_while()`]: trait.Iterator.html#method.take_while
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct TakeWhile<I, P> {
+ iter: I,
+ flag: bool,
+ predicate: P,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, P> fmt::Debug for TakeWhile<I, P> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("TakeWhile")
+ .field("iter", &self.iter)
+ .field("flag", &self.flag)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator, P> Iterator for TakeWhile<I, P>
+ where P: FnMut(&I::Item) -> bool
+{
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ if self.flag {
+ None
+ } else {
+ self.iter.next().and_then(|x| {
+ if (self.predicate)(&x) {
+ Some(x)
+ } else {
+ self.flag = true;
+ None
+ }
+ })
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the predicate
+ }
+}
+
+/// An iterator that skips over `n` elements of `iter`.
+///
+/// This `struct` is created by the [`skip()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`skip()`]: trait.Iterator.html#method.skip
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Skip<I> {
+ iter: I,
+ n: usize
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Skip<I> where I: Iterator {
+ type Item = <I as Iterator>::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ if self.n == 0 {
+ self.iter.next()
+ } else {
+ let old_n = self.n;
+ self.n = 0;
+ self.iter.nth(old_n)
+ }
+ }
+
+ #[inline]
+ fn nth(&mut self, n: usize) -> Option<I::Item> {
+ // Can't just add n + self.n due to overflow.
+ if self.n == 0 {
+ self.iter.nth(n)
+ } else {
+ let to_skip = self.n;
+ self.n = 0;
+ // nth(n) skips n+1
+ if self.iter.nth(to_skip-1).is_none() {
+ return None;
+ }
+ self.iter.nth(n)
+ }
+ }
+
+ #[inline]
+ fn count(self) -> usize {
+ self.iter.count().saturating_sub(self.n)
+ }
+
+ #[inline]
+ fn last(mut self) -> Option<I::Item> {
+ if self.n == 0 {
+ self.iter.last()
+ } else {
+ let next = self.next();
+ if next.is_some() {
+ // recurse. n should be 0.
+ self.last().or(next)
+ } else {
+ None
+ }
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (lower, upper) = self.iter.size_hint();
+
+ let lower = lower.saturating_sub(self.n);
+ let upper = upper.map(|x| x.saturating_sub(self.n));
+
+ (lower, upper)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> ExactSizeIterator for Skip<I> where I: ExactSizeIterator {}
+
+#[stable(feature = "double_ended_skip_iterator", since = "1.8.0")]
+impl<I> DoubleEndedIterator for Skip<I> where I: DoubleEndedIterator + ExactSizeIterator {
+ fn next_back(&mut self) -> Option<Self::Item> {
+ if self.len() > 0 {
+ self.iter.next_back()
+ } else {
+ None
+ }
+ }
+}
+
+/// An iterator that only iterates over the first `n` iterations of `iter`.
+///
+/// This `struct` is created by the [`take()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`take()`]: trait.Iterator.html#method.take
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Take<I> {
+ iter: I,
+ n: usize
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Take<I> where I: Iterator{
+ type Item = <I as Iterator>::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<<I as Iterator>::Item> {
+ if self.n != 0 {
+ self.n -= 1;
+ self.iter.next()
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ fn nth(&mut self, n: usize) -> Option<I::Item> {
+ if self.n > n {
+ self.n -= n + 1;
+ self.iter.nth(n)
+ } else {
+ if self.n > 0 {
+ self.iter.nth(self.n - 1);
+ self.n = 0;
+ }
+ None
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (lower, upper) = self.iter.size_hint();
+
+ let lower = cmp::min(lower, self.n);
+
+ let upper = match upper {
+ Some(x) if x < self.n => Some(x),
+ _ => Some(self.n)
+ };
+
+ (lower, upper)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> ExactSizeIterator for Take<I> where I: ExactSizeIterator {}
+
+
+/// An iterator to maintain state while iterating another iterator.
+///
+/// This `struct` is created by the [`scan()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`scan()`]: trait.Iterator.html#method.scan
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Scan<I, St, F> {
+ iter: I,
+ f: F,
+ state: St,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, St: fmt::Debug, F> fmt::Debug for Scan<I, St, F> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Scan")
+ .field("iter", &self.iter)
+ .field("state", &self.state)
+ .finish()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<B, I, St, F> Iterator for Scan<I, St, F> where
+ I: Iterator,
+ F: FnMut(&mut St, I::Item) -> Option<B>,
+{
+ type Item = B;
+
+ #[inline]
+ fn next(&mut self) -> Option<B> {
+ self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let (_, upper) = self.iter.size_hint();
+ (0, upper) // can't know a lower bound, due to the scan function
+ }
+}
+
+/// 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 = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct FlatMap<I, U: IntoIterator, F> {
+ iter: I,
+ f: F,
+ frontiter: Option<U::IntoIter>,
+ backiter: Option<U::IntoIter>,
+}
+
+#[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("iter", &self.iter)
+ .field("frontiter", &self.frontiter)
+ .field("backiter", &self.backiter)
+ .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> {
+ loop {
+ if let Some(ref mut inner) = self.frontiter {
+ if let Some(x) = inner.by_ref().next() {
+ return Some(x)
+ }
+ }
+ match self.iter.next().map(&mut self.f) {
+ None => return self.backiter.as_mut().and_then(|it| it.next()),
+ next => self.frontiter = next.map(IntoIterator::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)
+ }
+ }
+}
+
+#[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> {
+ loop {
+ if let Some(ref mut inner) = self.backiter {
+ if let Some(y) = inner.next_back() {
+ return Some(y)
+ }
+ }
+ match self.iter.next_back().map(&mut self.f) {
+ None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
+ next => self.backiter = next.map(IntoIterator::into_iter),
+ }
+ }
+ }
+}
+
+/// An iterator that yields `None` forever after the underlying iterator
+/// yields `None` once.
+///
+/// This `struct` is created by the [`fuse()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`fuse()`]: trait.Iterator.html#method.fuse
+/// [`Iterator`]: trait.Iterator.html
+#[derive(Clone, Debug)]
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub struct Fuse<I> {
+ iter: I,
+ done: bool
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> Iterator for Fuse<I> where I: Iterator {
+ type Item = <I as Iterator>::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<<I as Iterator>::Item> {
+ if self.done {
+ None
+ } else {
+ let next = self.iter.next();
+ self.done = next.is_none();
+ next
+ }
+ }
+
+ #[inline]
+ fn nth(&mut self, n: usize) -> Option<I::Item> {
+ if self.done {
+ None
+ } else {
+ let nth = self.iter.nth(n);
+ self.done = nth.is_none();
+ nth
+ }
+ }
+
+ #[inline]
+ fn last(self) -> Option<I::Item> {
+ if self.done {
+ None
+ } else {
+ self.iter.last()
+ }
+ }
+
+ #[inline]
+ fn count(self) -> usize {
+ if self.done {
+ 0
+ } else {
+ self.iter.count()
+ }
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ if self.done {
+ (0, Some(0))
+ } else {
+ self.iter.size_hint()
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
+ #[inline]
+ fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
+ if self.done {
+ None
+ } else {
+ let next = self.iter.next_back();
+ self.done = next.is_none();
+ next
+ }
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I> ExactSizeIterator for Fuse<I> where I: ExactSizeIterator {}
+
+/// An iterator that calls a function with a reference to each element before
+/// yielding it.
+///
+/// This `struct` is created by the [`inspect()`] method on [`Iterator`]. See its
+/// documentation for more.
+///
+/// [`inspect()`]: trait.Iterator.html#method.inspect
+/// [`Iterator`]: trait.Iterator.html
+#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
+#[stable(feature = "rust1", since = "1.0.0")]
+#[derive(Clone)]
+pub struct Inspect<I, F> {
+ iter: I,
+ f: F,
+}
+
+#[stable(feature = "core_impl_debug", since = "1.9.0")]
+impl<I: fmt::Debug, F> fmt::Debug for Inspect<I, F> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.debug_struct("Inspect")
+ .field("iter", &self.iter)
+ .finish()
+ }
+}
+
+impl<I: Iterator, F> Inspect<I, F> where F: FnMut(&I::Item) {
+ #[inline]
+ fn do_inspect(&mut self, elt: Option<I::Item>) -> Option<I::Item> {
+ if let Some(ref a) = elt {
+ (self.f)(a);
+ }
+
+ elt
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: Iterator, F> Iterator for Inspect<I, F> where F: FnMut(&I::Item) {
+ type Item = I::Item;
+
+ #[inline]
+ fn next(&mut self) -> Option<I::Item> {
+ let next = self.iter.next();
+ self.do_inspect(next)
+ }
+
+ #[inline]
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: DoubleEndedIterator, F> DoubleEndedIterator for Inspect<I, F>
+ where F: FnMut(&I::Item),
+{
+ #[inline]
+ fn next_back(&mut self) -> Option<I::Item> {
+ let next = self.iter.next_back();
+ self.do_inspect(next)
+ }
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
+ where F: FnMut(&I::Item) {}
diff --git a/libcore/iter/range.rs b/libcore/iter/range.rs
new file mode 100644
index 0000000..0814356
--- /dev/null
+++ b/libcore/iter/range.rs
@@ -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
+ }
+}
+
diff --git a/libcore/iter/sources.rs b/libcore/iter/sources.rs
new file mode 100644
index 0000000..ecd4a78
--- /dev/null
+++ b/libcore/iter/sources.rs
@@ -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() }
+}
diff --git a/libcore/iter/traits.rs b/libcore/iter/traits.rs
new file mode 100644
index 0000000..6750398
--- /dev/null
+++ b/libcore/iter/traits.rs
@@ -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 {}
+
diff --git a/libcore/lib.rs b/libcore/lib.rs
index e12c690..fa5e905 100644
--- a/libcore/lib.rs
+++ b/libcore/lib.rs
@@ -107,9 +107,7 @@ mod uint_macros;
#[path = "num/u32.rs"] pub mod u32;
#[path = "num/u64.rs"] pub mod u64;
-#[cfg(not(disable_float))]
#[path = "num/f32.rs"] pub mod f32;
-#[cfg(not(disable_float))]
#[path = "num/f64.rs"] pub mod f64;
#[macro_use]
diff --git a/libcore/macros.rs b/libcore/macros.rs
index f923668..ad90b44 100644
--- a/libcore/macros.rs
+++ b/libcore/macros.rs
@@ -182,7 +182,7 @@ macro_rules! debug_assert_eq {
/// fn write_to_file_using_match() -> Result<(), io::Error> {
/// let mut file = try!(File::create("my_best_friends.txt"));
/// match file.write_all(b"This is a list of my best friends.") {
-/// Ok(_) => (),
+/// Ok(v) => v,
/// Err(e) => return Err(e),
/// }
/// println!("I wrote to the file");
diff --git a/libcore/num/flt2dec/decoder.rs b/libcore/num/flt2dec/decoder.rs
index 0a28a14..6265691 100644
--- a/libcore/num/flt2dec/decoder.rs
+++ b/libcore/num/flt2dec/decoder.rs
@@ -12,7 +12,6 @@
use prelude::v1::*;
-#[cfg(not(disable_float))]
use {f32, f64};
use num::{Float, FpCategory};
@@ -58,12 +57,10 @@ pub trait DecodableFloat: Float + Copy {
fn min_pos_norm_value() -> Self;
}
-#[cfg(not(disable_float))]
impl DecodableFloat for f32 {
fn min_pos_norm_value() -> Self { f32::MIN_POSITIVE }
}
-#[cfg(not(disable_float))]
impl DecodableFloat for f64 {
fn min_pos_norm_value() -> Self { f64::MIN_POSITIVE }
}
diff --git a/libcore/num/mod.rs b/libcore/num/mod.rs
index e966d1b..589ac90 100644
--- a/libcore/num/mod.rs
+++ b/libcore/num/mod.rs
@@ -14,7 +14,7 @@
#![allow(missing_docs)]
use char::CharExt;
-use cmp::{Eq, PartialOrd};
+use cmp::PartialOrd;
use convert::From;
use fmt;
use intrinsics;
@@ -38,15 +38,27 @@ use slice::SliceExt;
/// all standard arithmetic operations on the underlying value are
/// intended to have wrapping semantics.
#[stable(feature = "rust1", since = "1.0.0")]
-#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug, Default)]
+#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.0.fmt(f)
+ }
+}
+
+#[stable(feature = "wrapping_display", since = "1.10.0")]
+impl<T: fmt::Display> fmt::Display for Wrapping<T> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.0.fmt(f)
+ }
+}
+
mod wrapping;
// All these modules are technically private and only exposed for libcoretest:
-#[cfg(not(disable_float))]
pub mod flt2dec;
-#[cfg(not(disable_float))]
pub mod dec2flt;
pub mod bignum;
pub mod diy_float;
@@ -113,7 +125,6 @@ macro_rules! zero_one_impl_float {
}
)*)
}
-#[cfg(not(disable_float))]
zero_one_impl_float! { f32 f64 }
macro_rules! checked_op {
@@ -152,7 +163,7 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
+ /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
@@ -166,9 +177,9 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0b01001100u8;
+ /// let n = -0b1000_0000i8;
///
- /// assert_eq!(n.count_ones(), 3);
+ /// assert_eq!(n.count_ones(), 1);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -181,9 +192,9 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0b01001100u8;
+ /// let n = -0b1000_0000i8;
///
- /// assert_eq!(n.count_zeros(), 5);
+ /// assert_eq!(n.count_zeros(), 7);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -199,9 +210,9 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0b0101000u16;
+ /// let n = -1i16;
///
- /// assert_eq!(n.leading_zeros(), 10);
+ /// assert_eq!(n.leading_zeros(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -217,9 +228,9 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0b0101000u16;
+ /// let n = -4i8;
///
- /// assert_eq!(n.trailing_zeros(), 3);
+ /// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -235,10 +246,10 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0x3456789ABCDEF012u64;
+ /// let n = 0x0123456789ABCDEFi64;
+ /// let m = -0x76543210FEDCBA99i64;
///
- /// assert_eq!(n.rotate_left(12), m);
+ /// assert_eq!(n.rotate_left(32), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -255,10 +266,10 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xDEF0123456789ABCu64;
+ /// let n = 0x0123456789ABCDEFi64;
+ /// let m = -0xFEDCBA987654322i64;
///
- /// assert_eq!(n.rotate_right(12), m);
+ /// assert_eq!(n.rotate_right(4), m);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -273,8 +284,8 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
- /// let m = 0xEFCDAB8967452301u64;
+ /// let n = 0x0123456789ABCDEFi64;
+ /// let m = -0x1032547698BADCFFi64;
///
/// assert_eq!(n.swap_bytes(), m);
/// ```
@@ -294,12 +305,12 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
+ /// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "big") {
- /// assert_eq!(u64::from_be(n), n)
+ /// assert_eq!(i64::from_be(n), n)
/// } else {
- /// assert_eq!(u64::from_be(n), n.swap_bytes())
+ /// assert_eq!(i64::from_be(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@@ -318,12 +329,12 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
+ /// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "little") {
- /// assert_eq!(u64::from_le(n), n)
+ /// assert_eq!(i64::from_le(n), n)
/// } else {
- /// assert_eq!(u64::from_le(n), n.swap_bytes())
+ /// assert_eq!(i64::from_le(n), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@@ -342,7 +353,7 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
+ /// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
@@ -366,7 +377,7 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// let n = 0x0123456789ABCDEFu64;
+ /// let n = 0x0123456789ABCDEFi64;
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
@@ -388,8 +399,8 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(5u16.checked_add(65530), Some(65535));
- /// assert_eq!(6u16.checked_add(65530), None);
+ /// assert_eq!(7i16.checked_add(32760), Some(32767));
+ /// assert_eq!(8i16.checked_add(32760), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -424,8 +435,8 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(5u8.checked_mul(51), Some(255));
- /// assert_eq!(5u8.checked_mul(52), None);
+ /// assert_eq!(6i8.checked_mul(21), Some(126));
+ /// assert_eq!(6i8.checked_mul(22), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
@@ -756,8 +767,8 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(1u8.wrapping_shl(7), 128);
- /// assert_eq!(1u8.wrapping_shl(8), 1);
+ /// assert_eq!((-1i8).wrapping_shl(7), -128);
+ /// assert_eq!((-1i8).wrapping_shl(8), -1);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
@@ -781,8 +792,8 @@ macro_rules! int_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(128u8.wrapping_shr(7), 1);
- /// assert_eq!(128u8.wrapping_shr(8), 128);
+ /// assert_eq!((-128i8).wrapping_shr(7), -1);
+ /// assert_eq!((-128i8).wrapping_shr(8), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
@@ -1196,15 +1207,13 @@ macro_rules! uint_impl {
///
/// Leading and trailing whitespace represent an error.
///
- /// # Arguments
- ///
- /// * src - A string slice
- /// * radix - The base to use. Must lie in the range [2 .. 36]
+ /// # Examples
///
- /// # Return value
+ /// Basic usage:
///
- /// `Err(ParseIntError)` if the string did not represent a valid number.
- /// Otherwise, `Ok(n)` where `n` is the integer represented by `src`.
+ /// ```
+ /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
+ /// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
from_str_radix(src, radix)
@@ -1748,7 +1757,7 @@ macro_rules! uint_impl {
/// Basic usage:
///
/// ```
- /// assert_eq!(100i8.wrapping_rem(10), 0);
+ /// assert_eq!(100u8.wrapping_rem(10), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[inline(always)]
@@ -1786,6 +1795,13 @@ macro_rules! uint_impl {
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
+ /// Note that this is *not* the same as a rotate-left; the
+ /// RHS of a wrapping shift-left is restricted to the range
+ /// of the type, rather than the bits shifted out of the LHS
+ /// being returned to the other end. The primitive integer
+ /// types all implement a `rotate_left` function, which may
+ /// be what you want instead.
+ ///
/// # Examples
///
/// Basic usage:
@@ -1804,6 +1820,13 @@ macro_rules! uint_impl {
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
+ /// Note that this is *not* the same as a rotate-right; the
+ /// RHS of a wrapping shift-right is restricted to the range
+ /// of the type, rather than the bits shifted out of the LHS
+ /// being returned to the other end. The primitive integer
+ /// types all implement a `rotate_right` function, which may
+ /// be what you want instead.
+ ///
/// # Examples
///
/// Basic usage:
@@ -2216,7 +2239,6 @@ pub enum FpCategory {
#[unstable(feature = "core_float",
reason = "stable interface is via `impl f{32,64}` in later crates",
issue = "32110")]
-#[cfg(not(disable_float))]
pub trait Float: Sized {
/// Returns the NaN value.
#[unstable(feature = "float_extras", reason = "needs removal",
@@ -2455,7 +2477,6 @@ impl fmt::Display for ParseIntError {
}
#[stable(feature = "rust1", since = "1.0.0")]
-#[cfg(not(disable_float))]
pub use num::dec2flt::ParseFloatError;
// Conversion traits for primitive integer and float types
@@ -2503,9 +2524,6 @@ impl_from! { u32, i64 }
// they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
// Lossy float conversions are not implemented at this time.
-#[cfg(not(disable_float))]
-mod _int_flot_conv {
-use convert::From;
// Signed -> Float
impl_from! { i8, f32 }
impl_from! { i8, f64 }
@@ -2522,4 +2540,3 @@ impl_from! { u32, f64 }
// Float -> Float
impl_from! { f32, f64 }
-}
diff --git a/libcore/ops.rs b/libcore/ops.rs
index 9c4bc3b..a2f8423 100644
--- a/libcore/ops.rs
+++ b/libcore/ops.rs
@@ -215,9 +215,7 @@ macro_rules! add_impl {
)*)
}
-add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-add_impl! { f32 f64 }
+add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `Sub` trait is used to specify the functionality of `-`.
///
@@ -270,9 +268,7 @@ macro_rules! sub_impl {
)*)
}
-sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-sub_impl! { f32 f64 }
+sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `Mul` trait is used to specify the functionality of `*`.
///
@@ -325,9 +321,7 @@ macro_rules! mul_impl {
)*)
}
-mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-mul_impl! { f32 f64 }
+mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `Div` trait is used to specify the functionality of `/`.
///
@@ -398,7 +392,6 @@ macro_rules! div_impl_float {
)*)
}
-#[cfg(not(disable_float))]
div_impl_float! { f32 f64 }
/// The `Rem` trait is used to specify the functionality of `%`.
@@ -470,7 +463,6 @@ macro_rules! rem_impl_float {
)*)
}
-#[cfg(not(disable_float))]
rem_impl_float! { f32 f64 }
/// The `Neg` trait is used to specify the functionality of unary `-`.
@@ -538,9 +530,7 @@ macro_rules! neg_impl_unsigned {
}
// neg_impl_unsigned! { usize u8 u16 u32 u64 }
-neg_impl_numeric! { isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-neg_impl_numeric! { f32 f64 }
+neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 }
/// The `Not` trait is used to specify the functionality of unary `!`.
///
@@ -938,9 +928,7 @@ macro_rules! add_assign_impl {
)+)
}
-add_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-add_assign_impl! { f32 f64 }
+add_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `SubAssign` trait is used to specify the functionality of `-=`.
///
@@ -984,9 +972,7 @@ macro_rules! sub_assign_impl {
)+)
}
-sub_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-sub_assign_impl! { f32 f64 }
+sub_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `MulAssign` trait is used to specify the functionality of `*=`.
///
@@ -1030,9 +1016,7 @@ macro_rules! mul_assign_impl {
)+)
}
-mul_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-mul_assign_impl! { f32 f64 }
+mul_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `DivAssign` trait is used to specify the functionality of `/=`.
///
@@ -1076,9 +1060,7 @@ macro_rules! div_assign_impl {
)+)
}
-div_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-div_assign_impl! { f32 f64 }
+div_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `RemAssign` trait is used to specify the functionality of `%=`.
///
@@ -1122,9 +1104,7 @@ macro_rules! rem_assign_impl {
)+)
}
-rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
-#[cfg(not(disable_float))]
-rem_assign_impl! { f32 f64 }
+rem_assign_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
/// The `BitAndAssign` trait is used to specify the functionality of `&=`.
///
@@ -1559,6 +1539,11 @@ impl<Idx: PartialOrd<Idx>> Range<Idx> {
///
/// See the [`contains()`](#method.contains) method for its characterization.
///
+/// Note: Currently, no overflow checking is done for the iterator
+/// implementation; if you use an integer range and the integer overflows, it
+/// might panic in debug mode or create an endless loop in release mode. This
+/// overflow behavior might change in the future.
+///
/// # Examples
///
/// ```
diff --git a/libcore/option.rs b/libcore/option.rs
index beed207..045c1f9 100644
--- a/libcore/option.rs
+++ b/libcore/option.rs
@@ -142,7 +142,6 @@
use self::Option::*;
use clone::Clone;
-use cmp::{Eq, Ord};
use default::Default;
use iter::ExactSizeIterator;
use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
diff --git a/libcore/ptr.rs b/libcore/ptr.rs
index 42aef3a..8b3a14b 100644
--- a/libcore/ptr.rs
+++ b/libcore/ptr.rs
@@ -119,6 +119,17 @@ pub unsafe fn replace<T>(dest: *mut T, mut src: T) -> T {
/// `src` is not used before the data is overwritten again (e.g. with `write`,
/// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
/// because it will attempt to drop the value previously at `*src`.
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// let x = 12;
+/// let y = &x as *const i32;
+///
+/// unsafe { println!("{}", std::ptr::read(y)); }
+/// ```
#[inline(always)]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn read<T>(src: *const T) -> T {
@@ -155,6 +166,21 @@ pub unsafe fn read_and_drop<T>(dest: *mut T) -> T {
///
/// This is appropriate for initializing uninitialized memory, or overwriting
/// memory that has previously been `read` from.
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// let mut x = 0;
+/// let y = &mut x as *mut i32;
+/// let z = 12;
+///
+/// unsafe {
+/// std::ptr::write(y, z);
+/// println!("{}", std::ptr::read(y));
+/// }
+/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn write<T>(dst: *mut T, src: T) {
@@ -166,9 +192,16 @@ pub unsafe fn write<T>(dst: *mut T, src: T) {
///
/// Volatile operations are intended to act on I/O memory, and are guaranteed
/// to not be elided or reordered by the compiler across other volatile
-/// operations. See the LLVM documentation on [[volatile]].
+/// operations.
+///
+/// # Notes
///
-/// [volatile]: http://llvm.org/docs/LangRef.html#volatile-memory-accesses
+/// Rust does not currently have a rigorously and formally defined memory model,
+/// so the precise semantics of what "volatile" means here is subject to change
+/// over time. That being said, the semantics will almost always end up pretty
+/// similar to [C11's definition of volatile][c11].
+///
+/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
///
/// # Safety
///
@@ -178,8 +211,19 @@ pub unsafe fn write<T>(dst: *mut T, src: T) {
/// `src` is not used before the data is overwritten again (e.g. with `write`,
/// `zero_memory`, or `copy_memory`). Note that `*src = foo` counts as a use
/// because it will attempt to drop the value previously at `*src`.
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// let x = 12;
+/// let y = &x as *const i32;
+///
+/// unsafe { println!("{}", std::ptr::read_volatile(y)); }
+/// ```
#[inline]
-#[unstable(feature = "volatile", reason = "recently added", issue = "31756")]
+#[stable(feature = "volatile", since = "1.9.0")]
pub unsafe fn read_volatile<T>(src: *const T) -> T {
intrinsics::volatile_load(src)
}
@@ -189,9 +233,16 @@ pub unsafe fn read_volatile<T>(src: *const T) -> T {
///
/// Volatile operations are intended to act on I/O memory, and are guaranteed
/// to not be elided or reordered by the compiler across other volatile
-/// operations. See the LLVM documentation on [[volatile]].
+/// operations.
+///
+/// # Notes
///
-/// [volatile]: http://llvm.org/docs/LangRef.html#volatile-memory-accesses
+/// Rust does not currently have a rigorously and formally defined memory model,
+/// so the precise semantics of what "volatile" means here is subject to change
+/// over time. That being said, the semantics will almost always end up pretty
+/// similar to [C11's definition of volatile][c11].
+///
+/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
///
/// # Safety
///
@@ -203,8 +254,23 @@ pub unsafe fn read_volatile<T>(src: *const T) -> T {
///
/// This is appropriate for initializing uninitialized memory, or overwriting
/// memory that has previously been `read` from.
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// let mut x = 0;
+/// let y = &mut x as *mut i32;
+/// let z = 12;
+///
+/// unsafe {
+/// std::ptr::write_volatile(y, z);
+/// println!("{}", std::ptr::read_volatile(y));
+/// }
+/// ```
#[inline]
-#[unstable(feature = "volatile", reason = "recently added", issue = "31756")]
+#[stable(feature = "volatile", since = "1.9.0")]
pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
intrinsics::volatile_store(dst, src);
}
@@ -238,6 +304,9 @@ impl<T: ?Sized> *const T {
/// operation because the returned value could be pointing to invalid
/// memory.
///
+ /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
+ /// not necessarily reflect the actual lifetime of the data.
+ ///
/// # Examples
///
/// Basic usage:
@@ -251,17 +320,13 @@ impl<T: ?Sized> *const T {
/// }
/// }
/// ```
- #[unstable(feature = "ptr_as_ref",
- reason = "Option is not clearly the right return type, and we \
- may want to tie the return lifetime to a borrow of \
- the raw pointer",
- issue = "27780")]
+ #[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[inline]
- pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
+ pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
if self.is_null() {
None
} else {
- Some(&**self)
+ Some(&*self)
}
}
@@ -324,6 +389,9 @@ impl<T: ?Sized> *mut T {
/// operation because the returned value could be pointing to invalid
/// memory.
///
+ /// Additionally, the lifetime `'a` returned is arbitrarily chosen and does
+ /// not necessarily reflect the actual lifetime of the data.
+ ///
/// # Examples
///
/// Basic usage:
@@ -337,17 +405,13 @@ impl<T: ?Sized> *mut T {
/// }
/// }
/// ```
- #[unstable(feature = "ptr_as_ref",
- reason = "Option is not clearly the right return type, and we \
- may want to tie the return lifetime to a borrow of \
- the raw pointer",
- issue = "27780")]
+ #[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[inline]
- pub unsafe fn as_ref<'a>(&self) -> Option<&'a T> where T: Sized {
+ pub unsafe fn as_ref<'a>(self) -> Option<&'a T> where T: Sized {
if self.is_null() {
None
} else {
- Some(&**self)
+ Some(&*self)
}
}
@@ -385,7 +449,8 @@ impl<T: ?Sized> *mut T {
/// # Safety
///
/// As with `as_ref`, this is unsafe because it cannot verify the validity
- /// of the returned pointer.
+ /// of the returned pointer, nor can it ensure that the lifetime `'a`
+ /// returned is indeed a valid lifetime for the contained data.
///
/// # Examples
///
@@ -394,17 +459,17 @@ impl<T: ?Sized> *mut T {
/// ```
/// let mut s = [1, 2, 3];
/// let ptr: *mut u32 = s.as_mut_ptr();
+ /// let first_value = unsafe { ptr.as_mut().unwrap() };
+ /// *first_value = 4;
+ /// println!("{:?}", s); // It'll print: "[4, 2, 3]".
/// ```
- #[unstable(feature = "ptr_as_ref",
- reason = "return value does not necessarily convey all possible \
- information",
- issue = "27780")]
+ #[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[inline]
- pub unsafe fn as_mut<'a>(&self) -> Option<&'a mut T> where T: Sized {
+ pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> where T: Sized {
if self.is_null() {
None
} else {
- Some(&mut **self)
+ Some(&mut *self)
}
}
}
diff --git a/libcore/raw.rs b/libcore/raw.rs
index 20c85b5..19226d8 100644
--- a/libcore/raw.rs
+++ b/libcore/raw.rs
@@ -60,12 +60,17 @@ use mem;
/// ```
#[repr(C)]
#[allow(missing_debug_implementations)]
+#[rustc_deprecated(reason = "use raw accessors/constructors in `slice` module",
+ since = "1.9.0")]
+#[unstable(feature = "raw", issue = "27751")]
pub struct Slice<T> {
pub data: *const T,
pub len: usize,
}
+#[allow(deprecated)]
impl<T> Copy for Slice<T> {}
+#[allow(deprecated)]
impl<T> Clone for Slice<T> {
fn clone(&self) -> Slice<T> { *self }
}
@@ -152,6 +157,9 @@ pub struct TraitObject {
/// This trait is meant to map equivalences between raw structs and their
/// corresponding rust values.
+#[rustc_deprecated(reason = "use raw accessors/constructors in `slice` module",
+ since = "1.9.0")]
+#[unstable(feature = "raw", issue = "27751")]
pub unsafe trait Repr<T> {
/// This function "unwraps" a rust value (without consuming it) into its raw
/// struct representation. This can be used to read/write different values
@@ -161,5 +169,7 @@ pub unsafe trait Repr<T> {
fn repr(&self) -> T { unsafe { mem::transmute_copy(&self) } }
}
+#[allow(deprecated)]
unsafe impl<T> Repr<Slice<T>> for [T] {}
+#[allow(deprecated)]
unsafe impl Repr<Slice<u8>> for str {}
diff --git a/libcore/result.rs b/libcore/result.rs
index 7f8cf53..4d9f042 100644
--- a/libcore/result.rs
+++ b/libcore/result.rs
@@ -19,7 +19,7 @@
//! # #[allow(dead_code)]
//! enum Result<T, E> {
//! Ok(T),
-//! Err(E)
+//! Err(E),
//! }
//! ```
//!
@@ -39,7 +39,7 @@
//! None => Err("invalid header length"),
//! Some(&1) => Ok(Version::Version1),
//! Some(&2) => Ok(Version::Version2),
-//! Some(_) => Err("invalid version")
+//! Some(_) => Err("invalid version"),
//! }
//! }
//!
@@ -254,7 +254,7 @@ pub enum Result<T, E> {
/// Contains the error value
#[stable(feature = "rust1", since = "1.0.0")]
- Err(#[stable(feature = "rust1", since = "1.0.0")] E)
+ Err(#[stable(feature = "rust1", since = "1.0.0")] E),
}
/////////////////////////////////////////////////////////////////////////////
@@ -270,6 +270,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<i32, &str> = Ok(-3);
/// assert_eq!(x.is_ok(), true);
@@ -290,6 +292,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<i32, &str> = Ok(-3);
/// assert_eq!(x.is_err(), false);
@@ -314,6 +318,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.ok(), Some(2));
@@ -337,6 +343,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.err(), None);
@@ -362,6 +370,10 @@ impl<T, E> Result<T, E> {
/// Produces a new `Result`, containing a reference
/// into the original, leaving the original in place.
///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.as_ref(), Ok(&2));
@@ -380,6 +392,10 @@ impl<T, E> Result<T, E> {
/// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`
///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
/// ```
/// fn mutate(r: &mut Result<i32, i32>) {
/// match r.as_mut() {
@@ -445,6 +461,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// fn stringify(x: u32) -> String { format!("error code: {}", x) }
///
@@ -471,6 +489,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(7);
/// assert_eq!(x.iter().next(), Some(&7));
@@ -488,6 +508,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let mut x: Result<u32, &str> = Ok(7);
/// match x.iter_mut().next() {
@@ -513,6 +535,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// let y: Result<&str, &str> = Err("late error");
@@ -545,6 +569,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
/// fn err(x: u32) -> Result<u32, u32> { Err(x) }
@@ -567,6 +593,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// let y: Result<u32, &str> = Err("late error");
@@ -599,6 +627,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
/// fn err(x: u32) -> Result<u32, u32> { Err(x) }
@@ -622,6 +652,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let optb = 2;
/// let x: Result<u32, &str> = Ok(9);
@@ -644,6 +676,8 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// fn count(x: &str) -> usize { x.len() }
///
@@ -670,6 +704,8 @@ impl<T, E: fmt::Debug> Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(2);
/// assert_eq!(x.unwrap(), 2);
@@ -696,6 +732,9 @@ impl<T, E: fmt::Debug> Result<T, E> {
/// passed message, and the content of the `Err`.
///
/// # Examples
+ ///
+ /// Basic usage:
+ ///
/// ```{.should_panic}
/// let x: Result<u32, &str> = Err("emergency failure");
/// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
@@ -759,6 +798,8 @@ impl<T, E> IntoIterator for Result<T, E> {
///
/// # Examples
///
+ /// Basic usage:
+ ///
/// ```
/// let x: Result<u32, &str> = Ok(5);
/// let v: Vec<u32> = x.into_iter().collect();
diff --git a/libcore/slice.rs b/libcore/slice.rs
index 25082ee..07f76ac 100644
--- a/libcore/slice.rs
+++ b/libcore/slice.rs
@@ -41,7 +41,7 @@ use default::Default;
use fmt;
use intrinsics::assume;
use iter::*;
-use ops::{FnMut, self, Index};
+use ops::{FnMut, self};
use ops::RangeFull;
use option::Option;
use option::Option::{None, Some};
@@ -50,10 +50,12 @@ use result::Result::{Ok, Err};
use ptr;
use mem;
use marker::{Copy, Send, Sync, self};
-use raw::Repr;
-// Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
-use raw::Slice as RawSlice;
+#[repr(C)]
+struct Repr<T> {
+ pub data: *const T,
+ pub len: usize,
+}
//
// Extension traits
@@ -152,9 +154,14 @@ pub trait SliceExt {
fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
#[stable(feature = "clone_from_slice", since = "1.7.0")]
- fn clone_from_slice(&mut self, &[Self::Item]) where Self::Item: Clone;
- #[unstable(feature = "copy_from_slice", issue = "31755")]
+ fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
+ #[stable(feature = "copy_from_slice", since = "1.9.0")]
fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
+
+ #[unstable(feature = "slice_binary_search_by_key", reason = "recently added", issue = "33018")]
+ fn binary_search_by_key<B, F>(&self, b: &B, f: F) -> Result<usize, usize>
+ where F: FnMut(&Self::Item) -> B,
+ B: Ord;
}
// Use macros to be generic over const/mut
@@ -317,7 +324,11 @@ impl<T> SliceExt for [T] {
}
#[inline]
- fn len(&self) -> usize { self.repr().len }
+ fn len(&self) -> usize {
+ unsafe {
+ mem::transmute::<&[T], Repr<T>>(self).len
+ }
+ }
#[inline]
fn get_mut(&mut self, index: usize) -> Option<&mut T> {
@@ -501,6 +512,14 @@ impl<T> SliceExt for [T] {
src.as_ptr(), self.as_mut_ptr(), self.len());
}
}
+
+ #[inline]
+ fn binary_search_by_key<B, F>(&self, b: &B, mut f: F) -> Result<usize, usize>
+ where F: FnMut(&Self::Item) -> B,
+ B: Ord
+ {
+ self.binary_search_by(|k| f(k).cmp(b))
+ }
}
#[stable(feature = "rust1", since = "1.0.0")]
@@ -871,6 +890,20 @@ macro_rules! make_mut_slice {
}
/// Immutable slice iterator
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
+/// let slice = &[1, 2, 3];
+///
+/// // Then, we iterate over it:
+/// for element in slice.iter() {
+/// println!("{}", element);
+/// }
+/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, T: 'a> {
ptr: *const T,
@@ -897,6 +930,26 @@ impl<'a, T> Iter<'a, T> {
///
/// This has the same lifetime as the original slice, and so the
/// iterator can continue to be used while this exists.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// // First, we declare a type which has the `iter` method to get the `Iter`
+ /// // struct (&[usize here]):
+ /// let slice = &[1, 2, 3];
+ ///
+ /// // Then, we get the iterator:
+ /// let mut iter = slice.iter();
+ /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
+ /// println!("{:?}", iter.as_slice());
+ ///
+ /// // Next, we move to the second element of the slice:
+ /// iter.next();
+ /// // Now `as_slice` returns "[2, 3]":
+ /// println!("{:?}", iter.as_slice());
+ /// ```
#[stable(feature = "iter_to_slice", since = "1.4.0")]
pub fn as_slice(&self) -> &'a [T] {
make_slice!(self.ptr, self.end)
@@ -928,6 +981,24 @@ impl<'a, T> Clone for Iter<'a, T> {
}
/// Mutable slice iterator.
+///
+/// # Examples
+///
+/// Basic usage:
+///
+/// ```
+/// // First, we declare a type which has `iter_mut` method to get the `IterMut`
+/// // struct (&[usize here]):
+/// let mut slice = &mut [1, 2, 3];
+///
+/// // Then, we iterate over it and increment each element value:
+/// for element in slice.iter_mut() {
+/// *element += 1;
+/// }
+///
+/// // We now have "[2, 3, 4]":
+/// println!("{:?}", slice);
+/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IterMut<'a, T: 'a> {
ptr: *mut T,
@@ -956,6 +1027,35 @@ impl<'a, T> IterMut<'a, T> {
/// to consume the iterator. Consider using the `Slice` and
/// `SliceMut` implementations for obtaining slices with more
/// restricted lifetimes that do not consume the iterator.
+ ///
+ /// # Examples
+ ///
+ /// Basic usage:
+ ///
+ /// ```
+ /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
+ /// // struct (&[usize here]):
+ /// let mut slice = &mut [1, 2, 3];
+ ///
+ /// {
+ /// // Then, we get the iterator:
+ /// let mut iter = slice.iter_mut();
+ /// // We move to next element:
+ /// iter.next();
+ /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
+ /// println!("{:?}", iter.into_slice());
+ /// }
+ ///
+ /// // Now let's modify a value of the slice:
+ /// {
+ /// // First we get back the iterator:
+ /// let mut iter = slice.iter_mut();
+ /// // We change the value of the first element of the slice returned by the `next` method:
+ /// *iter.next().unwrap() += 1;
+ /// }
+ /// // Now slice is "[2, 2, 3]":
+ /// println!("{:?}", slice);
+ /// ```
#[stable(feature = "iter_to_slice", since = "1.4.0")]
pub fn into_slice(self) -> &'a mut [T] {
make_mut_slice!(self.ptr, self.end)
@@ -1614,7 +1714,7 @@ impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
- mem::transmute(RawSlice { data: p, len: len })
+ mem::transmute(Repr { data: p, len: len })
}
/// Performs the same functionality as `from_raw_parts`, except that a mutable
@@ -1626,7 +1726,7 @@ pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
- mem::transmute(RawSlice { data: p, len: len })
+ mem::transmute(Repr { data: p, len: len })
}
//
diff --git a/libcore/str/mod.rs b/libcore/str/mod.rs
index 305546d..2c34caf 100644
--- a/libcore/str/mod.rs
+++ b/libcore/str/mod.rs
@@ -19,7 +19,6 @@ use self::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
use char::{self, CharExt};
use clone::Clone;
-use cmp::Eq;
use convert::AsRef;
use default::Default;
use fmt;
@@ -29,7 +28,6 @@ use marker::Sized;
use mem;
use ops::{Fn, FnMut, FnOnce};
use option::Option::{self, None, Some};
-use raw::{Repr, Slice};
use result::Result::{self, Ok, Err};
use slice::{self, SliceExt};
@@ -1320,7 +1318,6 @@ Section: Trait implementations
mod traits {
use cmp::{Ord, Ordering, PartialEq, PartialOrd, Eq};
- use iter::Iterator;
use option::Option;
use option::Option::Some;
use ops;
@@ -1664,24 +1661,23 @@ pub trait StrExt {
#[stable(feature = "core", since = "1.6.0")]
fn trim_right_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str
where P::Searcher: ReverseSearcher<'a>;
- #[unstable(feature = "str_char",
- reason = "it is unclear whether this method pulls its weight \
- with the existence of the char_indices iterator or \
- this method may want to be replaced with checked \
- slicing",
- issue = "27754")]
+ #[stable(feature = "is_char_boundary", since = "1.9.0")]
fn is_char_boundary(&self, index: usize) -> bool;
#[unstable(feature = "str_char",
reason = "often replaced by char_indices, this method may \
be removed in favor of just char_at() or eventually \
removed altogether",
issue = "27754")]
+ #[rustc_deprecated(reason = "use slicing plus chars() plus len_utf8",
+ since = "1.9.0")]
fn char_range_at(&self, start: usize) -> CharRange;
#[unstable(feature = "str_char",
reason = "often replaced by char_indices, this method may \
be removed in favor of just char_at_reverse() or \
eventually removed altogether",
issue = "27754")]
+ #[rustc_deprecated(reason = "use slicing plus chars().rev() plus len_utf8",
+ since = "1.9.0")]
fn char_range_at_reverse(&self, start: usize) -> CharRange;
#[unstable(feature = "str_char",
reason = "frequently replaced by the chars() iterator, this \
@@ -1690,12 +1686,16 @@ pub trait StrExt {
iterators or by getting the first char from a \
subslice",
issue = "27754")]
+ #[rustc_deprecated(reason = "use slicing plus chars()",
+ since = "1.9.0")]
fn char_at(&self, i: usize) -> char;
#[unstable(feature = "str_char",
reason = "see char_at for more details, but reverse semantics \
are also somewhat unclear, especially with which \
cases generate panics",
issue = "27754")]
+ #[rustc_deprecated(reason = "use slicing plus chars().rev()",
+ since = "1.9.0")]
fn char_at_reverse(&self, i: usize) -> char;
#[stable(feature = "core", since = "1.6.0")]
fn as_bytes(&self) -> &[u8];
@@ -1714,6 +1714,8 @@ pub trait StrExt {
may not be warranted with the existence of the chars \
and/or char_indices iterators",
issue = "27754")]
+ #[rustc_deprecated(reason = "use chars() plus Chars::as_str",
+ since = "1.9.0")]
fn slice_shift_char(&self) -> Option<(char, &str)>;
#[stable(feature = "core", since = "1.6.0")]
fn as_ptr(&self) -> *const u8;
@@ -1857,18 +1859,16 @@ impl StrExt for str {
#[inline]
unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
- mem::transmute(Slice {
- data: self.as_ptr().offset(begin as isize),
- len: end - begin,
- })
+ let ptr = self.as_ptr().offset(begin as isize);
+ let len = end - begin;
+ from_utf8_unchecked(slice::from_raw_parts(ptr, len))
}
#[inline]
unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
- mem::transmute(Slice {
- data: self.as_ptr().offset(begin as isize),
- len: end - begin,
- })
+ let ptr = self.as_ptr().offset(begin as isize);
+ let len = end - begin;
+ mem::transmute(slice::from_raw_parts_mut(ptr as *mut u8, len))
}
#[inline]
@@ -1940,7 +1940,8 @@ impl StrExt for str {
if index == 0 || index == self.len() { return true; }
match self.as_bytes().get(index) {
None => false,
- Some(&b) => b < 128 || b >= 192,
+ // This is bit magic equivalent to: b < 128 || b >= 192
+ Some(&b) => (b as i8) >= -0x40,
}
}
@@ -1982,11 +1983,13 @@ impl StrExt for str {
}
#[inline]
+ #[allow(deprecated)]
fn char_at(&self, i: usize) -> char {
self.char_range_at(i).ch
}
#[inline]
+ #[allow(deprecated)]
fn char_at_reverse(&self, i: usize) -> char {
self.char_range_at_reverse(i).ch
}
@@ -2038,6 +2041,7 @@ impl StrExt for str {
}
#[inline]
+ #[allow(deprecated)]
fn slice_shift_char(&self) -> Option<(char, &str)> {
if self.is_empty() {
None
@@ -2054,7 +2058,9 @@ impl StrExt for str {
}
#[inline]
- fn len(&self) -> usize { self.repr().len }
+ fn len(&self) -> usize {
+ self.as_bytes().len()
+ }
#[inline]
fn is_empty(&self) -> bool { self.len() == 0 }
diff --git a/libcore/sync/atomic.rs b/libcore/sync/atomic.rs
index 483c382..e74dc08 100644
--- a/libcore/sync/atomic.rs
+++ b/libcore/sync/atomic.rs
@@ -1380,7 +1380,6 @@ unsafe fn atomic_sub<T>(dst: *mut T, val: T, order: Ordering) -> T {
}
#[inline]
-#[cfg(any(not(stage0), cargobuild))]
unsafe fn atomic_compare_exchange<T>(dst: *mut T,
old: T,
new: T,
@@ -1408,29 +1407,6 @@ unsafe fn atomic_compare_exchange<T>(dst: *mut T,
}
#[inline]
-#[cfg(all(stage0, not(cargobuild)))]
-unsafe fn atomic_compare_exchange<T>(dst: *mut T,
- old: T,
- new: T,
- success: Ordering,
- _: Ordering) -> Result<T, T>
- where T: ::cmp::Eq + ::marker::Copy
-{
- let val = match success {
- Acquire => intrinsics::atomic_cxchg_acq(dst, old, new),
- Release => intrinsics::atomic_cxchg_rel(dst, old, new),
- AcqRel => intrinsics::atomic_cxchg_acqrel(dst, old, new),
- Relaxed => intrinsics::atomic_cxchg_relaxed(dst, old, new),
- SeqCst => intrinsics::atomic_cxchg(dst, old, new),
- };
- if val == old {
- Ok(val)
- } else {
- Err(val)
- }
-}
-
-#[inline]
unsafe fn atomic_compare_exchange_weak<T>(dst: *mut T,
old: T,
new: T,
diff --git a/librustc_unicode/char.rs b/librustc_unicode/char.rs
index 4d80211..863cada 100644
--- a/librustc_unicode/char.rs
+++ b/librustc_unicode/char.rs
@@ -29,8 +29,7 @@
#![stable(feature = "rust1", since = "1.0.0")]
use core::char::CharExt as C;
-use core::option::Option::{self, Some, None};
-use core::iter::Iterator;
+use core::fmt;
use tables::{derived_property, property, general_category, conversions};
// stable reexports
@@ -739,7 +738,7 @@ impl char {
}
/// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
-#[unstable(feature = "decode_utf16", reason = "recently exposed", issue = "27830")]
+#[stable(feature = "decode_utf16", since = "1.9.0")]
#[derive(Clone)]
pub struct DecodeUtf16<I>
where I: Iterator<Item = u16>
@@ -748,6 +747,13 @@ pub struct DecodeUtf16<I>
buf: Option<u16>,
}
+/// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
+#[stable(feature = "decode_utf16", since = "1.9.0")]
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct DecodeUtf16Error {
+ code: u16,
+}
+
/// Create an iterator over the UTF-16 encoded code points in `iter`,
/// returning unpaired surrogates as `Err`s.
///
@@ -756,8 +762,6 @@ pub struct DecodeUtf16<I>
/// Basic usage:
///
/// ```
-/// #![feature(decode_utf16)]
-///
/// use std::char::decode_utf16;
///
/// fn main() {
@@ -766,7 +770,9 @@ pub struct DecodeUtf16<I>
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
-/// assert_eq!(decode_utf16(v.iter().cloned()).collect::<Vec<_>>(),
+/// assert_eq!(decode_utf16(v.iter().cloned())
+/// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
+/// .collect::<Vec<_>>(),
/// vec![Ok('𝄞'),
/// Ok('m'), Ok('u'), Ok('s'),
/// Err(0xDD1E),
@@ -778,8 +784,6 @@ pub struct DecodeUtf16<I>
/// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
///
/// ```
-/// #![feature(decode_utf16)]
-///
/// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
///
/// fn main() {
@@ -794,7 +798,7 @@ pub struct DecodeUtf16<I>
/// "𝄞mus�ic�");
/// }
/// ```
-#[unstable(feature = "decode_utf16", reason = "recently exposed", issue = "27830")]
+#[stable(feature = "decode_utf16", since = "1.9.0")]
#[inline]
pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
DecodeUtf16 {
@@ -803,11 +807,11 @@ pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::Into
}
}
-#[unstable(feature = "decode_utf16", reason = "recently exposed", issue = "27830")]
+#[stable(feature = "decode_utf16", since = "1.9.0")]
impl<I: Iterator<Item=u16>> Iterator for DecodeUtf16<I> {
- type Item = Result<char, u16>;
+ type Item = Result<char, DecodeUtf16Error>;
- fn next(&mut self) -> Option<Result<char, u16>> {
+ fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
let u = match self.buf.take() {
Some(buf) => buf,
None => match self.iter.next() {
@@ -821,18 +825,18 @@ impl<I: Iterator<Item=u16>> Iterator for DecodeUtf16<I> {
Some(Ok(unsafe { from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 {
// a trailing surrogate
- Some(Err(u))
+ Some(Err(DecodeUtf16Error { code: u }))
} else {
let u2 = match self.iter.next() {
Some(u2) => u2,
// eof
- None => return Some(Err(u)),
+ None => return Some(Err(DecodeUtf16Error { code: u })),
};
if u2 < 0xDC00 || u2 > 0xDFFF {
// not a trailing surrogate so we're not a valid
// surrogate pair, so rewind to redecode u2 next time.
self.buf = Some(u2);
- return Some(Err(u));
+ return Some(Err(DecodeUtf16Error { code: u }));
}
// all ok, so lets decode it.
@@ -850,8 +854,25 @@ impl<I: Iterator<Item=u16>> Iterator for DecodeUtf16<I> {
}
}
-/// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a decoding error.
+impl DecodeUtf16Error {
+ /// Returns the unpaired surrogate which caused this error.
+ #[stable(feature = "decode_utf16", since = "1.9.0")]
+ pub fn unpaired_surrogate(&self) -> u16 {
+ self.code
+ }
+}
+
+#[stable(feature = "decode_utf16", since = "1.9.0")]
+impl fmt::Display for DecodeUtf16Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "unpaired surrogate found: {:x}", self.code)
+ }
+}
+
+/// `U+FFFD REPLACEMENT CHARACTER` (�) is used in Unicode to represent a
+/// decoding error.
+///
/// It can occur, for example, when giving ill-formed UTF-8 bytes to
/// [`String::from_utf8_lossy`](../../std/string/struct.String.html#method.from_utf8_lossy).
-#[unstable(feature = "decode_utf16", reason = "recently added", issue = "27830")]
+#[stable(feature = "decode_utf16", since = "1.9.0")]
pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';