]> git.lizzy.rs Git - rust.git/blob - src/libcore/iter/traits.rs
Fix conversion from Miri Value to ConstValue
[rust.git] / src / libcore / iter / traits.rs
1 // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 use ops::{Mul, Add, Try};
11 use num::Wrapping;
12
13 use super::{AlwaysOk, LoopState};
14
15 /// Conversion from an `Iterator`.
16 ///
17 /// By implementing `FromIterator` for a type, you define how it will be
18 /// created from an iterator. This is common for types which describe a
19 /// collection of some kind.
20 ///
21 /// `FromIterator`'s [`from_iter`] is rarely called explicitly, and is instead
22 /// used through [`Iterator`]'s [`collect`] method. See [`collect`]'s
23 /// documentation for more examples.
24 ///
25 /// [`from_iter`]: #tymethod.from_iter
26 /// [`Iterator`]: trait.Iterator.html
27 /// [`collect`]: trait.Iterator.html#method.collect
28 ///
29 /// See also: [`IntoIterator`].
30 ///
31 /// [`IntoIterator`]: trait.IntoIterator.html
32 ///
33 /// # Examples
34 ///
35 /// Basic usage:
36 ///
37 /// ```
38 /// use std::iter::FromIterator;
39 ///
40 /// let five_fives = std::iter::repeat(5).take(5);
41 ///
42 /// let v = Vec::from_iter(five_fives);
43 ///
44 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
45 /// ```
46 ///
47 /// Using [`collect`] to implicitly use `FromIterator`:
48 ///
49 /// ```
50 /// let five_fives = std::iter::repeat(5).take(5);
51 ///
52 /// let v: Vec<i32> = five_fives.collect();
53 ///
54 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
55 /// ```
56 ///
57 /// Implementing `FromIterator` for your type:
58 ///
59 /// ```
60 /// use std::iter::FromIterator;
61 ///
62 /// // A sample collection, that's just a wrapper over Vec<T>
63 /// #[derive(Debug)]
64 /// struct MyCollection(Vec<i32>);
65 ///
66 /// // Let's give it some methods so we can create one and add things
67 /// // to it.
68 /// impl MyCollection {
69 ///     fn new() -> MyCollection {
70 ///         MyCollection(Vec::new())
71 ///     }
72 ///
73 ///     fn add(&mut self, elem: i32) {
74 ///         self.0.push(elem);
75 ///     }
76 /// }
77 ///
78 /// // and we'll implement FromIterator
79 /// impl FromIterator<i32> for MyCollection {
80 ///     fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
81 ///         let mut c = MyCollection::new();
82 ///
83 ///         for i in iter {
84 ///             c.add(i);
85 ///         }
86 ///
87 ///         c
88 ///     }
89 /// }
90 ///
91 /// // Now we can make a new iterator...
92 /// let iter = (0..5).into_iter();
93 ///
94 /// // ... and make a MyCollection out of it
95 /// let c = MyCollection::from_iter(iter);
96 ///
97 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
98 ///
99 /// // collect works too!
100 ///
101 /// let iter = (0..5).into_iter();
102 /// let c: MyCollection = iter.collect();
103 ///
104 /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]);
105 /// ```
106 #[stable(feature = "rust1", since = "1.0.0")]
107 #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \
108                           built from an iterator over elements of type `{A}`"]
109 pub trait FromIterator<A>: Sized {
110     /// Creates a value from an iterator.
111     ///
112     /// See the [module-level documentation] for more.
113     ///
114     /// [module-level documentation]: index.html
115     ///
116     /// # Examples
117     ///
118     /// Basic usage:
119     ///
120     /// ```
121     /// use std::iter::FromIterator;
122     ///
123     /// let five_fives = std::iter::repeat(5).take(5);
124     ///
125     /// let v = Vec::from_iter(five_fives);
126     ///
127     /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
128     /// ```
129     #[stable(feature = "rust1", since = "1.0.0")]
130     fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self;
131 }
132
133 /// Conversion into an `Iterator`.
134 ///
135 /// By implementing `IntoIterator` for a type, you define how it will be
136 /// converted to an iterator. This is common for types which describe a
137 /// collection of some kind.
138 ///
139 /// One benefit of implementing `IntoIterator` is that your type will [work
140 /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator).
141 ///
142 /// See also: [`FromIterator`].
143 ///
144 /// [`FromIterator`]: trait.FromIterator.html
145 ///
146 /// # Examples
147 ///
148 /// Basic usage:
149 ///
150 /// ```
151 /// let v = vec![1, 2, 3];
152 /// let mut iter = v.into_iter();
153 ///
154 /// assert_eq!(Some(1), iter.next());
155 /// assert_eq!(Some(2), iter.next());
156 /// assert_eq!(Some(3), iter.next());
157 /// assert_eq!(None, iter.next());
158 /// ```
159 /// Implementing `IntoIterator` for your type:
160 ///
161 /// ```
162 /// // A sample collection, that's just a wrapper over Vec<T>
163 /// #[derive(Debug)]
164 /// struct MyCollection(Vec<i32>);
165 ///
166 /// // Let's give it some methods so we can create one and add things
167 /// // to it.
168 /// impl MyCollection {
169 ///     fn new() -> MyCollection {
170 ///         MyCollection(Vec::new())
171 ///     }
172 ///
173 ///     fn add(&mut self, elem: i32) {
174 ///         self.0.push(elem);
175 ///     }
176 /// }
177 ///
178 /// // and we'll implement IntoIterator
179 /// impl IntoIterator for MyCollection {
180 ///     type Item = i32;
181 ///     type IntoIter = ::std::vec::IntoIter<i32>;
182 ///
183 ///     fn into_iter(self) -> Self::IntoIter {
184 ///         self.0.into_iter()
185 ///     }
186 /// }
187 ///
188 /// // Now we can make a new collection...
189 /// let mut c = MyCollection::new();
190 ///
191 /// // ... add some stuff to it ...
192 /// c.add(0);
193 /// c.add(1);
194 /// c.add(2);
195 ///
196 /// // ... and then turn it into an Iterator:
197 /// for (i, n) in c.into_iter().enumerate() {
198 ///     assert_eq!(i as i32, n);
199 /// }
200 /// ```
201 ///
202 /// It is common to use `IntoIterator` as a trait bound. This allows
203 /// the input collection type to change, so long as it is still an
204 /// iterator. Additional bounds can be specified by restricting on
205 /// `Item`:
206 ///
207 /// ```rust
208 /// fn collect_as_strings<T>(collection: T) -> Vec<String>
209 ///     where T: IntoIterator,
210 ///           T::Item : std::fmt::Debug,
211 /// {
212 ///     collection
213 ///         .into_iter()
214 ///         .map(|item| format!("{:?}", item))
215 ///         .collect()
216 /// }
217 /// ```
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub trait IntoIterator {
220     /// The type of the elements being iterated over.
221     #[stable(feature = "rust1", since = "1.0.0")]
222     type Item;
223
224     /// Which kind of iterator are we turning this into?
225     #[stable(feature = "rust1", since = "1.0.0")]
226     type IntoIter: Iterator<Item=Self::Item>;
227
228     /// Creates an iterator from a value.
229     ///
230     /// See the [module-level documentation] for more.
231     ///
232     /// [module-level documentation]: index.html
233     ///
234     /// # Examples
235     ///
236     /// Basic usage:
237     ///
238     /// ```
239     /// let v = vec![1, 2, 3];
240     /// let mut iter = v.into_iter();
241     ///
242     /// assert_eq!(Some(1), iter.next());
243     /// assert_eq!(Some(2), iter.next());
244     /// assert_eq!(Some(3), iter.next());
245     /// assert_eq!(None, iter.next());
246     /// ```
247     #[stable(feature = "rust1", since = "1.0.0")]
248     fn into_iter(self) -> Self::IntoIter;
249 }
250
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<I: Iterator> IntoIterator for I {
253     type Item = I::Item;
254     type IntoIter = I;
255
256     fn into_iter(self) -> I {
257         self
258     }
259 }
260
261 /// Extend a collection with the contents of an iterator.
262 ///
263 /// Iterators produce a series of values, and collections can also be thought
264 /// of as a series of values. The `Extend` trait bridges this gap, allowing you
265 /// to extend a collection by including the contents of that iterator. When
266 /// extending a collection with an already existing key, that entry is updated
267 /// or, in the case of collections that permit multiple entries with equal
268 /// keys, that entry is inserted.
269 ///
270 /// # Examples
271 ///
272 /// Basic usage:
273 ///
274 /// ```
275 /// // You can extend a String with some chars:
276 /// let mut message = String::from("The first three letters are: ");
277 ///
278 /// message.extend(&['a', 'b', 'c']);
279 ///
280 /// assert_eq!("abc", &message[29..32]);
281 /// ```
282 ///
283 /// Implementing `Extend`:
284 ///
285 /// ```
286 /// // A sample collection, that's just a wrapper over Vec<T>
287 /// #[derive(Debug)]
288 /// struct MyCollection(Vec<i32>);
289 ///
290 /// // Let's give it some methods so we can create one and add things
291 /// // to it.
292 /// impl MyCollection {
293 ///     fn new() -> MyCollection {
294 ///         MyCollection(Vec::new())
295 ///     }
296 ///
297 ///     fn add(&mut self, elem: i32) {
298 ///         self.0.push(elem);
299 ///     }
300 /// }
301 ///
302 /// // since MyCollection has a list of i32s, we implement Extend for i32
303 /// impl Extend<i32> for MyCollection {
304 ///
305 ///     // This is a bit simpler with the concrete type signature: we can call
306 ///     // extend on anything which can be turned into an Iterator which gives
307 ///     // us i32s. Because we need i32s to put into MyCollection.
308 ///     fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) {
309 ///
310 ///         // The implementation is very straightforward: loop through the
311 ///         // iterator, and add() each element to ourselves.
312 ///         for elem in iter {
313 ///             self.add(elem);
314 ///         }
315 ///     }
316 /// }
317 ///
318 /// let mut c = MyCollection::new();
319 ///
320 /// c.add(5);
321 /// c.add(6);
322 /// c.add(7);
323 ///
324 /// // let's extend our collection with three more numbers
325 /// c.extend(vec![1, 2, 3]);
326 ///
327 /// // we've added these elements onto the end
328 /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
329 /// ```
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub trait Extend<A> {
332     /// Extends a collection with the contents of an iterator.
333     ///
334     /// As this is the only method for this trait, the [trait-level] docs
335     /// contain more details.
336     ///
337     /// [trait-level]: trait.Extend.html
338     ///
339     /// # Examples
340     ///
341     /// Basic usage:
342     ///
343     /// ```
344     /// // You can extend a String with some chars:
345     /// let mut message = String::from("abc");
346     ///
347     /// message.extend(['d', 'e', 'f'].iter());
348     ///
349     /// assert_eq!("abcdef", &message);
350     /// ```
351     #[stable(feature = "rust1", since = "1.0.0")]
352     fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T);
353 }
354
355 /// An iterator able to yield elements from both ends.
356 ///
357 /// Something that implements `DoubleEndedIterator` has one extra capability
358 /// over something that implements [`Iterator`]: the ability to also take
359 /// `Item`s from the back, as well as the front.
360 ///
361 /// It is important to note that both back and forth work on the same range,
362 /// and do not cross: iteration is over when they meet in the middle.
363 ///
364 /// In a similar fashion to the [`Iterator`] protocol, once a
365 /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
366 /// may or may not ever return `Some` again. `next()` and `next_back()` are
367 /// interchangeable for this purpose.
368 ///
369 /// [`Iterator`]: trait.Iterator.html
370 ///
371 /// # Examples
372 ///
373 /// Basic usage:
374 ///
375 /// ```
376 /// let numbers = vec![1, 2, 3, 4, 5, 6];
377 ///
378 /// let mut iter = numbers.iter();
379 ///
380 /// assert_eq!(Some(&1), iter.next());
381 /// assert_eq!(Some(&6), iter.next_back());
382 /// assert_eq!(Some(&5), iter.next_back());
383 /// assert_eq!(Some(&2), iter.next());
384 /// assert_eq!(Some(&3), iter.next());
385 /// assert_eq!(Some(&4), iter.next());
386 /// assert_eq!(None, iter.next());
387 /// assert_eq!(None, iter.next_back());
388 /// ```
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub trait DoubleEndedIterator: Iterator {
391     /// Removes and returns an element from the end of the iterator.
392     ///
393     /// Returns `None` when there are no more elements.
394     ///
395     /// The [trait-level] docs contain more details.
396     ///
397     /// [trait-level]: trait.DoubleEndedIterator.html
398     ///
399     /// # Examples
400     ///
401     /// Basic usage:
402     ///
403     /// ```
404     /// let numbers = vec![1, 2, 3, 4, 5, 6];
405     ///
406     /// let mut iter = numbers.iter();
407     ///
408     /// assert_eq!(Some(&1), iter.next());
409     /// assert_eq!(Some(&6), iter.next_back());
410     /// assert_eq!(Some(&5), iter.next_back());
411     /// assert_eq!(Some(&2), iter.next());
412     /// assert_eq!(Some(&3), iter.next());
413     /// assert_eq!(Some(&4), iter.next());
414     /// assert_eq!(None, iter.next());
415     /// assert_eq!(None, iter.next_back());
416     /// ```
417     #[stable(feature = "rust1", since = "1.0.0")]
418     fn next_back(&mut self) -> Option<Self::Item>;
419
420     /// This is the reverse version of [`try_fold()`]: it takes elements
421     /// starting from the back of the iterator.
422     ///
423     /// [`try_fold()`]: trait.Iterator.html#method.try_fold
424     ///
425     /// # Examples
426     ///
427     /// Basic usage:
428     ///
429     /// ```
430     /// let a = ["1", "2", "3"];
431     /// let sum = a.iter()
432     ///     .map(|&s| s.parse::<i32>())
433     ///     .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
434     /// assert_eq!(sum, Ok(6));
435     /// ```
436     ///
437     /// Short-circuiting:
438     ///
439     /// ```
440     /// let a = ["1", "rust", "3"];
441     /// let mut it = a.iter();
442     /// let sum = it
443     ///     .by_ref()
444     ///     .map(|&s| s.parse::<i32>())
445     ///     .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
446     /// assert!(sum.is_err());
447     ///
448     /// // Because it short-circuited, the remaining elements are still
449     /// // available through the iterator.
450     /// assert_eq!(it.next_back(), Some(&"1"));
451     /// ```
452     #[inline]
453     #[stable(feature = "iterator_try_fold", since = "1.27.0")]
454     fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
455         Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
456     {
457         let mut accum = init;
458         while let Some(x) = self.next_back() {
459             accum = f(accum, x)?;
460         }
461         Try::from_ok(accum)
462     }
463
464     /// An iterator method that reduces the iterator's elements to a single,
465     /// final value, starting from the back.
466     ///
467     /// This is the reverse version of [`fold()`]: it takes elements starting from
468     /// the back of the iterator.
469     ///
470     /// `rfold()` takes two arguments: an initial value, and a closure with two
471     /// arguments: an 'accumulator', and an element. The closure returns the value that
472     /// the accumulator should have for the next iteration.
473     ///
474     /// The initial value is the value the accumulator will have on the first
475     /// call.
476     ///
477     /// After applying this closure to every element of the iterator, `rfold()`
478     /// returns the accumulator.
479     ///
480     /// This operation is sometimes called 'reduce' or 'inject'.
481     ///
482     /// Folding is useful whenever you have a collection of something, and want
483     /// to produce a single value from it.
484     ///
485     /// [`fold()`]: trait.Iterator.html#method.fold
486     ///
487     /// # Examples
488     ///
489     /// Basic usage:
490     ///
491     /// ```
492     /// let a = [1, 2, 3];
493     ///
494     /// // the sum of all of the elements of a
495     /// let sum = a.iter()
496     ///            .rfold(0, |acc, &x| acc + x);
497     ///
498     /// assert_eq!(sum, 6);
499     /// ```
500     ///
501     /// This example builds a string, starting with an initial value
502     /// and continuing with each element from the back until the front:
503     ///
504     /// ```
505     /// let numbers = [1, 2, 3, 4, 5];
506     ///
507     /// let zero = "0".to_string();
508     ///
509     /// let result = numbers.iter().rfold(zero, |acc, &x| {
510     ///     format!("({} + {})", x, acc)
511     /// });
512     ///
513     /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
514     /// ```
515     #[inline]
516     #[stable(feature = "iter_rfold", since = "1.27.0")]
517     fn rfold<B, F>(mut self, accum: B, mut f: F) -> B where
518         Self: Sized, F: FnMut(B, Self::Item) -> B,
519     {
520         self.try_rfold(accum, move |acc, x| AlwaysOk(f(acc, x))).0
521     }
522
523     /// Searches for an element of an iterator from the back that satisfies a predicate.
524     ///
525     /// `rfind()` takes a closure that returns `true` or `false`. It applies
526     /// this closure to each element of the iterator, starting at the end, and if any
527     /// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
528     /// `false`, it returns [`None`].
529     ///
530     /// `rfind()` is short-circuiting; in other words, it will stop processing
531     /// as soon as the closure returns `true`.
532     ///
533     /// Because `rfind()` takes a reference, and many iterators iterate over
534     /// references, this leads to a possibly confusing situation where the
535     /// argument is a double reference. You can see this effect in the
536     /// examples below, with `&&x`.
537     ///
538     /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
539     /// [`None`]: ../../std/option/enum.Option.html#variant.None
540     ///
541     /// # Examples
542     ///
543     /// Basic usage:
544     ///
545     /// ```
546     /// let a = [1, 2, 3];
547     ///
548     /// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
549     ///
550     /// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
551     /// ```
552     ///
553     /// Stopping at the first `true`:
554     ///
555     /// ```
556     /// let a = [1, 2, 3];
557     ///
558     /// let mut iter = a.iter();
559     ///
560     /// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
561     ///
562     /// // we can still use `iter`, as there are more elements.
563     /// assert_eq!(iter.next_back(), Some(&1));
564     /// ```
565     #[inline]
566     #[stable(feature = "iter_rfind", since = "1.27.0")]
567     fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
568         Self: Sized,
569         P: FnMut(&Self::Item) -> bool
570     {
571         self.try_rfold((), move |(), x| {
572             if predicate(&x) { LoopState::Break(x) }
573             else { LoopState::Continue(()) }
574         }).break_value()
575     }
576 }
577
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
580     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
581 }
582
583 /// An iterator that knows its exact length.
584 ///
585 /// Many [`Iterator`]s don't know how many times they will iterate, but some do.
586 /// If an iterator knows how many times it can iterate, providing access to
587 /// that information can be useful. For example, if you want to iterate
588 /// backwards, a good start is to know where the end is.
589 ///
590 /// When implementing an `ExactSizeIterator`, You must also implement
591 /// [`Iterator`]. When doing so, the implementation of [`size_hint`] *must*
592 /// return the exact size of the iterator.
593 ///
594 /// [`Iterator`]: trait.Iterator.html
595 /// [`size_hint`]: trait.Iterator.html#method.size_hint
596 ///
597 /// The [`len`] method has a default implementation, so you usually shouldn't
598 /// implement it. However, you may be able to provide a more performant
599 /// implementation than the default, so overriding it in this case makes sense.
600 ///
601 /// [`len`]: #method.len
602 ///
603 /// # Examples
604 ///
605 /// Basic usage:
606 ///
607 /// ```
608 /// // a finite range knows exactly how many times it will iterate
609 /// let five = 0..5;
610 ///
611 /// assert_eq!(5, five.len());
612 /// ```
613 ///
614 /// In the [module level docs][moddocs], we implemented an [`Iterator`],
615 /// `Counter`. Let's implement `ExactSizeIterator` for it as well:
616 ///
617 /// [moddocs]: index.html
618 ///
619 /// ```
620 /// # struct Counter {
621 /// #     count: usize,
622 /// # }
623 /// # impl Counter {
624 /// #     fn new() -> Counter {
625 /// #         Counter { count: 0 }
626 /// #     }
627 /// # }
628 /// # impl Iterator for Counter {
629 /// #     type Item = usize;
630 /// #     fn next(&mut self) -> Option<usize> {
631 /// #         self.count += 1;
632 /// #         if self.count < 6 {
633 /// #             Some(self.count)
634 /// #         } else {
635 /// #             None
636 /// #         }
637 /// #     }
638 /// # }
639 /// impl ExactSizeIterator for Counter {
640 ///     // We can easily calculate the remaining number of iterations.
641 ///     fn len(&self) -> usize {
642 ///         5 - self.count
643 ///     }
644 /// }
645 ///
646 /// // And now we can use it!
647 ///
648 /// let counter = Counter::new();
649 ///
650 /// assert_eq!(5, counter.len());
651 /// ```
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub trait ExactSizeIterator: Iterator {
654     /// Returns the exact number of times the iterator will iterate.
655     ///
656     /// This method has a default implementation, so you usually should not
657     /// implement it directly. However, if you can provide a more efficient
658     /// implementation, you can do so. See the [trait-level] docs for an
659     /// example.
660     ///
661     /// This function has the same safety guarantees as the [`size_hint`]
662     /// function.
663     ///
664     /// [trait-level]: trait.ExactSizeIterator.html
665     /// [`size_hint`]: trait.Iterator.html#method.size_hint
666     ///
667     /// # Examples
668     ///
669     /// Basic usage:
670     ///
671     /// ```
672     /// // a finite range knows exactly how many times it will iterate
673     /// let five = 0..5;
674     ///
675     /// assert_eq!(5, five.len());
676     /// ```
677     #[inline]
678     #[stable(feature = "rust1", since = "1.0.0")]
679     fn len(&self) -> usize {
680         let (lower, upper) = self.size_hint();
681         // Note: This assertion is overly defensive, but it checks the invariant
682         // guaranteed by the trait. If this trait were rust-internal,
683         // we could use debug_assert!; assert_eq! will check all Rust user
684         // implementations too.
685         assert_eq!(upper, Some(lower));
686         lower
687     }
688
689     /// Returns whether the iterator is empty.
690     ///
691     /// This method has a default implementation using `self.len()`, so you
692     /// don't need to implement it yourself.
693     ///
694     /// # Examples
695     ///
696     /// Basic usage:
697     ///
698     /// ```
699     /// #![feature(exact_size_is_empty)]
700     ///
701     /// let mut one_element = std::iter::once(0);
702     /// assert!(!one_element.is_empty());
703     ///
704     /// assert_eq!(one_element.next(), Some(0));
705     /// assert!(one_element.is_empty());
706     ///
707     /// assert_eq!(one_element.next(), None);
708     /// ```
709     #[inline]
710     #[unstable(feature = "exact_size_is_empty", issue = "35428")]
711     fn is_empty(&self) -> bool {
712         self.len() == 0
713     }
714 }
715
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {
718     fn len(&self) -> usize {
719         (**self).len()
720     }
721     fn is_empty(&self) -> bool {
722         (**self).is_empty()
723     }
724 }
725
726 /// Trait to represent types that can be created by summing up an iterator.
727 ///
728 /// This trait is used to implement the [`sum`] method on iterators. Types which
729 /// implement the trait can be generated by the [`sum`] method. Like
730 /// [`FromIterator`] this trait should rarely be called directly and instead
731 /// interacted with through [`Iterator::sum`].
732 ///
733 /// [`sum`]: ../../std/iter/trait.Sum.html#tymethod.sum
734 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
735 /// [`Iterator::sum`]: ../../std/iter/trait.Iterator.html#method.sum
736 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
737 pub trait Sum<A = Self>: Sized {
738     /// Method which takes an iterator and generates `Self` from the elements by
739     /// "summing up" the items.
740     #[stable(feature = "iter_arith_traits", since = "1.12.0")]
741     fn sum<I: Iterator<Item=A>>(iter: I) -> Self;
742 }
743
744 /// Trait to represent types that can be created by multiplying elements of an
745 /// iterator.
746 ///
747 /// This trait is used to implement the [`product`] method on iterators. Types
748 /// which implement the trait can be generated by the [`product`] method. Like
749 /// [`FromIterator`] this trait should rarely be called directly and instead
750 /// interacted with through [`Iterator::product`].
751 ///
752 /// [`product`]: ../../std/iter/trait.Product.html#tymethod.product
753 /// [`FromIterator`]: ../../std/iter/trait.FromIterator.html
754 /// [`Iterator::product`]: ../../std/iter/trait.Iterator.html#method.product
755 #[stable(feature = "iter_arith_traits", since = "1.12.0")]
756 pub trait Product<A = Self>: Sized {
757     /// Method which takes an iterator and generates `Self` from the elements by
758     /// multiplying the items.
759     #[stable(feature = "iter_arith_traits", since = "1.12.0")]
760     fn product<I: Iterator<Item=A>>(iter: I) -> Self;
761 }
762
763 // NB: explicitly use Add and Mul here to inherit overflow checks
764 macro_rules! integer_sum_product {
765     (@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(
766         #[$attr]
767         impl Sum for $a {
768             fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
769                 iter.fold($zero, Add::add)
770             }
771         }
772
773         #[$attr]
774         impl Product for $a {
775             fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
776                 iter.fold($one, Mul::mul)
777             }
778         }
779
780         #[$attr]
781         impl<'a> Sum<&'a $a> for $a {
782             fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
783                 iter.fold($zero, Add::add)
784             }
785         }
786
787         #[$attr]
788         impl<'a> Product<&'a $a> for $a {
789             fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
790                 iter.fold($one, Mul::mul)
791             }
792         }
793     )*);
794     ($($a:ty)*) => (
795         integer_sum_product!(@impls 0, 1,
796                 #[stable(feature = "iter_arith_traits", since = "1.12.0")],
797                 $($a)+);
798         integer_sum_product!(@impls Wrapping(0), Wrapping(1),
799                 #[stable(feature = "wrapping_iter_arith", since = "1.14.0")],
800                 $(Wrapping<$a>)+);
801     );
802 }
803
804 macro_rules! float_sum_product {
805     ($($a:ident)*) => ($(
806         #[stable(feature = "iter_arith_traits", since = "1.12.0")]
807         impl Sum for $a {
808             fn sum<I: Iterator<Item=$a>>(iter: I) -> $a {
809                 iter.fold(0.0, |a, b| a + b)
810             }
811         }
812
813         #[stable(feature = "iter_arith_traits", since = "1.12.0")]
814         impl Product for $a {
815             fn product<I: Iterator<Item=$a>>(iter: I) -> $a {
816                 iter.fold(1.0, |a, b| a * b)
817             }
818         }
819
820         #[stable(feature = "iter_arith_traits", since = "1.12.0")]
821         impl<'a> Sum<&'a $a> for $a {
822             fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
823                 iter.fold(0.0, |a, b| a + *b)
824             }
825         }
826
827         #[stable(feature = "iter_arith_traits", since = "1.12.0")]
828         impl<'a> Product<&'a $a> for $a {
829             fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a {
830                 iter.fold(1.0, |a, b| a * *b)
831             }
832         }
833     )*)
834 }
835
836 integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
837 float_sum_product! { f32 f64 }
838
839 /// An iterator adapter that produces output as long as the underlying
840 /// iterator produces `Result::Ok` values.
841 ///
842 /// If an error is encountered, the iterator stops and the error is
843 /// stored. The error may be recovered later via `reconstruct`.
844 struct ResultShunt<I, E> {
845     iter: I,
846     error: Option<E>,
847 }
848
849 impl<I, T, E> ResultShunt<I, E>
850     where I: Iterator<Item = Result<T, E>>
851 {
852     /// Process the given iterator as if it yielded a `T` instead of a
853     /// `Result<T, _>`. Any errors will stop the inner iterator and
854     /// the overall result will be an error.
855     pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
856         where F: FnMut(&mut Self) -> U
857     {
858         let mut shunt = ResultShunt::new(iter);
859         let value = f(shunt.by_ref());
860         shunt.reconstruct(value)
861     }
862
863     fn new(iter: I) -> Self {
864         ResultShunt {
865             iter,
866             error: None,
867         }
868     }
869
870     /// Consume the adapter and rebuild a `Result` value. This should
871     /// *always* be called, otherwise any potential error would be
872     /// lost.
873     fn reconstruct<U>(self, val: U) -> Result<U, E> {
874         match self.error {
875             None => Ok(val),
876             Some(e) => Err(e),
877         }
878     }
879 }
880
881 impl<I, T, E> Iterator for ResultShunt<I, E>
882     where I: Iterator<Item = Result<T, E>>
883 {
884     type Item = T;
885
886     fn next(&mut self) -> Option<Self::Item> {
887         match self.iter.next() {
888             Some(Ok(v)) => Some(v),
889             Some(Err(e)) => {
890                 self.error = Some(e);
891                 None
892             }
893             None => None,
894         }
895     }
896
897     fn size_hint(&self) -> (usize, Option<usize>) {
898         if self.error.is_some() {
899             (0, Some(0))
900         } else {
901             let (_, upper) = self.iter.size_hint();
902             (0, upper)
903         }
904     }
905 }
906
907 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
908 impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
909     where T: Sum<U>,
910 {
911     /// Takes each element in the `Iterator`: if it is an `Err`, no further
912     /// elements are taken, and the `Err` is returned. Should no `Err` occur,
913     /// the sum of all elements is returned.
914     ///
915     /// # Examples
916     ///
917     /// This sums up every integer in a vector, rejecting the sum if a negative
918     /// element is encountered:
919     ///
920     /// ```
921     /// let v = vec![1, 2];
922     /// let res: Result<i32, &'static str> = v.iter().map(|&x: &i32|
923     ///     if x < 0 { Err("Negative element found") }
924     ///     else { Ok(x) }
925     /// ).sum();
926     /// assert_eq!(res, Ok(3));
927     /// ```
928     fn sum<I>(iter: I) -> Result<T, E>
929         where I: Iterator<Item = Result<U, E>>,
930     {
931         ResultShunt::process(iter, |i| i.sum())
932     }
933 }
934
935 #[stable(feature = "iter_arith_traits_result", since="1.16.0")]
936 impl<T, U, E> Product<Result<U, E>> for Result<T, E>
937     where T: Product<U>,
938 {
939     /// Takes each element in the `Iterator`: if it is an `Err`, no further
940     /// elements are taken, and the `Err` is returned. Should no `Err` occur,
941     /// the product of all elements is returned.
942     fn product<I>(iter: I) -> Result<T, E>
943         where I: Iterator<Item = Result<U, E>>,
944     {
945         ResultShunt::process(iter, |i| i.product())
946     }
947 }
948
949 /// An iterator that always continues to yield `None` when exhausted.
950 ///
951 /// Calling next on a fused iterator that has returned `None` once is guaranteed
952 /// to return [`None`] again. This trait should be implemented by all iterators
953 /// that behave this way because it allows for some significant optimizations.
954 ///
955 /// Note: In general, you should not use `FusedIterator` in generic bounds if
956 /// you need a fused iterator. Instead, you should just call [`Iterator::fuse`]
957 /// on the iterator. If the iterator is already fused, the additional [`Fuse`]
958 /// wrapper will be a no-op with no performance penalty.
959 ///
960 /// [`None`]: ../../std/option/enum.Option.html#variant.None
961 /// [`Iterator::fuse`]: ../../std/iter/trait.Iterator.html#method.fuse
962 /// [`Fuse`]: ../../std/iter/struct.Fuse.html
963 #[stable(feature = "fused", since = "1.26.0")]
964 pub trait FusedIterator: Iterator {}
965
966 #[stable(feature = "fused", since = "1.26.0")]
967 impl<'a, I: FusedIterator + ?Sized> FusedIterator for &'a mut I {}
968
969 /// An iterator that reports an accurate length using size_hint.
970 ///
971 /// The iterator reports a size hint where it is either exact
972 /// (lower bound is equal to upper bound), or the upper bound is [`None`].
973 /// The upper bound must only be [`None`] if the actual iterator length is
974 /// larger than [`usize::MAX`]. In that case, the lower bound must be
975 /// [`usize::MAX`], resulting in a [`.size_hint`] of `(usize::MAX, None)`.
976 ///
977 /// The iterator must produce exactly the number of elements it reported
978 /// or diverge before reaching the end.
979 ///
980 /// # Safety
981 ///
982 /// This trait must only be implemented when the contract is upheld.
983 /// Consumers of this trait must inspect [`.size_hint`]’s upper bound.
984 ///
985 /// [`None`]: ../../std/option/enum.Option.html#variant.None
986 /// [`usize::MAX`]: ../../std/usize/constant.MAX.html
987 /// [`.size_hint`]: ../../std/iter/trait.Iterator.html#method.size_hint
988 #[unstable(feature = "trusted_len", issue = "37572")]
989 pub unsafe trait TrustedLen : Iterator {}
990
991 #[unstable(feature = "trusted_len", issue = "37572")]
992 unsafe impl<'a, I: TrustedLen + ?Sized> TrustedLen for &'a mut I {}