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