]>
Commit | Line | Data |
---|---|---|
a7813a04 XL |
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. | |
9e0c209e | 10 | use ops::{Mul, Add}; |
c30ab7b3 | 11 | use num::Wrapping; |
a7813a04 XL |
12 | |
13 | /// Conversion from an `Iterator`. | |
14 | /// | |
15 | /// By implementing `FromIterator` for a type, you define how it will be | |
16 | /// created from an iterator. This is common for types which describe a | |
17 | /// collection of some kind. | |
18 | /// | |
19 | /// `FromIterator`'s [`from_iter()`] is rarely called explicitly, and is instead | |
20 | /// used through [`Iterator`]'s [`collect()`] method. See [`collect()`]'s | |
21 | /// documentation for more examples. | |
22 | /// | |
23 | /// [`from_iter()`]: #tymethod.from_iter | |
24 | /// [`Iterator`]: trait.Iterator.html | |
25 | /// [`collect()`]: trait.Iterator.html#method.collect | |
26 | /// | |
27 | /// See also: [`IntoIterator`]. | |
28 | /// | |
29 | /// [`IntoIterator`]: trait.IntoIterator.html | |
30 | /// | |
31 | /// # Examples | |
32 | /// | |
33 | /// Basic usage: | |
34 | /// | |
35 | /// ``` | |
36 | /// use std::iter::FromIterator; | |
37 | /// | |
38 | /// let five_fives = std::iter::repeat(5).take(5); | |
39 | /// | |
40 | /// let v = Vec::from_iter(five_fives); | |
41 | /// | |
42 | /// assert_eq!(v, vec![5, 5, 5, 5, 5]); | |
43 | /// ``` | |
44 | /// | |
45 | /// Using [`collect()`] to implicitly use `FromIterator`: | |
46 | /// | |
47 | /// ``` | |
48 | /// let five_fives = std::iter::repeat(5).take(5); | |
49 | /// | |
50 | /// let v: Vec<i32> = five_fives.collect(); | |
51 | /// | |
52 | /// assert_eq!(v, vec![5, 5, 5, 5, 5]); | |
53 | /// ``` | |
54 | /// | |
55 | /// Implementing `FromIterator` for your type: | |
56 | /// | |
57 | /// ``` | |
58 | /// use std::iter::FromIterator; | |
59 | /// | |
60 | /// // A sample collection, that's just a wrapper over Vec<T> | |
61 | /// #[derive(Debug)] | |
62 | /// struct MyCollection(Vec<i32>); | |
63 | /// | |
64 | /// // Let's give it some methods so we can create one and add things | |
65 | /// // to it. | |
66 | /// impl MyCollection { | |
67 | /// fn new() -> MyCollection { | |
68 | /// MyCollection(Vec::new()) | |
69 | /// } | |
70 | /// | |
71 | /// fn add(&mut self, elem: i32) { | |
72 | /// self.0.push(elem); | |
73 | /// } | |
74 | /// } | |
75 | /// | |
76 | /// // and we'll implement FromIterator | |
77 | /// impl FromIterator<i32> for MyCollection { | |
78 | /// fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self { | |
79 | /// let mut c = MyCollection::new(); | |
80 | /// | |
81 | /// for i in iter { | |
82 | /// c.add(i); | |
83 | /// } | |
84 | /// | |
85 | /// c | |
86 | /// } | |
87 | /// } | |
88 | /// | |
89 | /// // Now we can make a new iterator... | |
90 | /// let iter = (0..5).into_iter(); | |
91 | /// | |
92 | /// // ... and make a MyCollection out of it | |
93 | /// let c = MyCollection::from_iter(iter); | |
94 | /// | |
95 | /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]); | |
96 | /// | |
97 | /// // collect works too! | |
98 | /// | |
99 | /// let iter = (0..5).into_iter(); | |
100 | /// let c: MyCollection = iter.collect(); | |
101 | /// | |
102 | /// assert_eq!(c.0, vec![0, 1, 2, 3, 4]); | |
103 | /// ``` | |
104 | #[stable(feature = "rust1", since = "1.0.0")] | |
105 | #[rustc_on_unimplemented="a collection of type `{Self}` cannot be \ | |
106 | built from an iterator over elements of type `{A}`"] | |
107 | pub trait FromIterator<A>: Sized { | |
108 | /// Creates a value from an iterator. | |
109 | /// | |
110 | /// See the [module-level documentation] for more. | |
111 | /// | |
112 | /// [module-level documentation]: trait.FromIterator.html | |
113 | /// | |
114 | /// # Examples | |
115 | /// | |
116 | /// Basic usage: | |
117 | /// | |
118 | /// ``` | |
119 | /// use std::iter::FromIterator; | |
120 | /// | |
121 | /// let five_fives = std::iter::repeat(5).take(5); | |
122 | /// | |
123 | /// let v = Vec::from_iter(five_fives); | |
124 | /// | |
125 | /// assert_eq!(v, vec![5, 5, 5, 5, 5]); | |
126 | /// ``` | |
127 | #[stable(feature = "rust1", since = "1.0.0")] | |
128 | fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> Self; | |
129 | } | |
130 | ||
131 | /// Conversion into an `Iterator`. | |
132 | /// | |
133 | /// By implementing `IntoIterator` for a type, you define how it will be | |
134 | /// converted to an iterator. This is common for types which describe a | |
135 | /// collection of some kind. | |
136 | /// | |
137 | /// One benefit of implementing `IntoIterator` is that your type will [work | |
138 | /// with Rust's `for` loop syntax](index.html#for-loops-and-intoiterator). | |
139 | /// | |
140 | /// See also: [`FromIterator`]. | |
141 | /// | |
142 | /// [`FromIterator`]: trait.FromIterator.html | |
143 | /// | |
144 | /// # Examples | |
145 | /// | |
146 | /// Basic usage: | |
147 | /// | |
148 | /// ``` | |
149 | /// let v = vec![1, 2, 3]; | |
150 | /// | |
151 | /// let mut iter = v.into_iter(); | |
152 | /// | |
153 | /// let n = iter.next(); | |
154 | /// assert_eq!(Some(1), n); | |
155 | /// | |
156 | /// let n = iter.next(); | |
157 | /// assert_eq!(Some(2), n); | |
158 | /// | |
159 | /// let n = iter.next(); | |
160 | /// assert_eq!(Some(3), n); | |
161 | /// | |
162 | /// let n = iter.next(); | |
163 | /// assert_eq!(None, n); | |
164 | /// ``` | |
165 | /// | |
166 | /// Implementing `IntoIterator` for your type: | |
167 | /// | |
168 | /// ``` | |
169 | /// // A sample collection, that's just a wrapper over Vec<T> | |
170 | /// #[derive(Debug)] | |
171 | /// struct MyCollection(Vec<i32>); | |
172 | /// | |
173 | /// // Let's give it some methods so we can create one and add things | |
174 | /// // to it. | |
175 | /// impl MyCollection { | |
176 | /// fn new() -> MyCollection { | |
177 | /// MyCollection(Vec::new()) | |
178 | /// } | |
179 | /// | |
180 | /// fn add(&mut self, elem: i32) { | |
181 | /// self.0.push(elem); | |
182 | /// } | |
183 | /// } | |
184 | /// | |
185 | /// // and we'll implement IntoIterator | |
186 | /// impl IntoIterator for MyCollection { | |
187 | /// type Item = i32; | |
188 | /// type IntoIter = ::std::vec::IntoIter<i32>; | |
189 | /// | |
190 | /// fn into_iter(self) -> Self::IntoIter { | |
191 | /// self.0.into_iter() | |
192 | /// } | |
193 | /// } | |
194 | /// | |
195 | /// // Now we can make a new collection... | |
196 | /// let mut c = MyCollection::new(); | |
197 | /// | |
198 | /// // ... add some stuff to it ... | |
199 | /// c.add(0); | |
200 | /// c.add(1); | |
201 | /// c.add(2); | |
202 | /// | |
203 | /// // ... and then turn it into an Iterator: | |
204 | /// for (i, n) in c.into_iter().enumerate() { | |
205 | /// assert_eq!(i as i32, n); | |
206 | /// } | |
207 | /// ``` | |
208 | #[stable(feature = "rust1", since = "1.0.0")] | |
209 | pub trait IntoIterator { | |
210 | /// The type of the elements being iterated over. | |
211 | #[stable(feature = "rust1", since = "1.0.0")] | |
212 | type Item; | |
213 | ||
214 | /// Which kind of iterator are we turning this into? | |
215 | #[stable(feature = "rust1", since = "1.0.0")] | |
216 | type IntoIter: Iterator<Item=Self::Item>; | |
217 | ||
218 | /// Creates an iterator from a value. | |
219 | /// | |
220 | /// See the [module-level documentation] for more. | |
221 | /// | |
222 | /// [module-level documentation]: trait.IntoIterator.html | |
223 | /// | |
224 | /// # Examples | |
225 | /// | |
226 | /// Basic usage: | |
227 | /// | |
228 | /// ``` | |
229 | /// let v = vec![1, 2, 3]; | |
230 | /// | |
231 | /// let mut iter = v.into_iter(); | |
232 | /// | |
233 | /// let n = iter.next(); | |
234 | /// assert_eq!(Some(1), n); | |
235 | /// | |
236 | /// let n = iter.next(); | |
237 | /// assert_eq!(Some(2), n); | |
238 | /// | |
239 | /// let n = iter.next(); | |
240 | /// assert_eq!(Some(3), n); | |
241 | /// | |
242 | /// let n = iter.next(); | |
243 | /// assert_eq!(None, n); | |
244 | /// ``` | |
245 | #[stable(feature = "rust1", since = "1.0.0")] | |
246 | fn into_iter(self) -> Self::IntoIter; | |
247 | } | |
248 | ||
249 | #[stable(feature = "rust1", since = "1.0.0")] | |
250 | impl<I: Iterator> IntoIterator for I { | |
251 | type Item = I::Item; | |
252 | type IntoIter = I; | |
253 | ||
254 | fn into_iter(self) -> I { | |
255 | self | |
256 | } | |
257 | } | |
258 | ||
259 | /// Extend a collection with the contents of an iterator. | |
260 | /// | |
261 | /// Iterators produce a series of values, and collections can also be thought | |
262 | /// of as a series of values. The `Extend` trait bridges this gap, allowing you | |
263 | /// to extend a collection by including the contents of that iterator. | |
264 | /// | |
265 | /// # Examples | |
266 | /// | |
267 | /// Basic usage: | |
268 | /// | |
269 | /// ``` | |
270 | /// // You can extend a String with some chars: | |
271 | /// let mut message = String::from("The first three letters are: "); | |
272 | /// | |
273 | /// message.extend(&['a', 'b', 'c']); | |
274 | /// | |
275 | /// assert_eq!("abc", &message[29..32]); | |
276 | /// ``` | |
277 | /// | |
278 | /// Implementing `Extend`: | |
279 | /// | |
280 | /// ``` | |
281 | /// // A sample collection, that's just a wrapper over Vec<T> | |
282 | /// #[derive(Debug)] | |
283 | /// struct MyCollection(Vec<i32>); | |
284 | /// | |
285 | /// // Let's give it some methods so we can create one and add things | |
286 | /// // to it. | |
287 | /// impl MyCollection { | |
288 | /// fn new() -> MyCollection { | |
289 | /// MyCollection(Vec::new()) | |
290 | /// } | |
291 | /// | |
292 | /// fn add(&mut self, elem: i32) { | |
293 | /// self.0.push(elem); | |
294 | /// } | |
295 | /// } | |
296 | /// | |
297 | /// // since MyCollection has a list of i32s, we implement Extend for i32 | |
298 | /// impl Extend<i32> for MyCollection { | |
299 | /// | |
300 | /// // This is a bit simpler with the concrete type signature: we can call | |
301 | /// // extend on anything which can be turned into an Iterator which gives | |
302 | /// // us i32s. Because we need i32s to put into MyCollection. | |
303 | /// fn extend<T: IntoIterator<Item=i32>>(&mut self, iter: T) { | |
304 | /// | |
305 | /// // The implementation is very straightforward: loop through the | |
306 | /// // iterator, and add() each element to ourselves. | |
307 | /// for elem in iter { | |
308 | /// self.add(elem); | |
309 | /// } | |
310 | /// } | |
311 | /// } | |
312 | /// | |
313 | /// let mut c = MyCollection::new(); | |
314 | /// | |
315 | /// c.add(5); | |
316 | /// c.add(6); | |
317 | /// c.add(7); | |
318 | /// | |
319 | /// // let's extend our collection with three more numbers | |
320 | /// c.extend(vec![1, 2, 3]); | |
321 | /// | |
322 | /// // we've added these elements onto the end | |
323 | /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c)); | |
324 | /// ``` | |
325 | #[stable(feature = "rust1", since = "1.0.0")] | |
326 | pub trait Extend<A> { | |
327 | /// Extends a collection with the contents of an iterator. | |
328 | /// | |
329 | /// As this is the only method for this trait, the [trait-level] docs | |
330 | /// contain more details. | |
331 | /// | |
332 | /// [trait-level]: trait.Extend.html | |
333 | /// | |
334 | /// # Examples | |
335 | /// | |
336 | /// Basic usage: | |
337 | /// | |
338 | /// ``` | |
339 | /// // You can extend a String with some chars: | |
340 | /// let mut message = String::from("abc"); | |
341 | /// | |
342 | /// message.extend(['d', 'e', 'f'].iter()); | |
343 | /// | |
344 | /// assert_eq!("abcdef", &message); | |
345 | /// ``` | |
346 | #[stable(feature = "rust1", since = "1.0.0")] | |
347 | fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T); | |
348 | } | |
349 | ||
350 | /// An iterator able to yield elements from both ends. | |
351 | /// | |
352 | /// Something that implements `DoubleEndedIterator` has one extra capability | |
353 | /// over something that implements [`Iterator`]: the ability to also take | |
354 | /// `Item`s from the back, as well as the front. | |
355 | /// | |
356 | /// It is important to note that both back and forth work on the same range, | |
357 | /// and do not cross: iteration is over when they meet in the middle. | |
358 | /// | |
359 | /// In a similar fashion to the [`Iterator`] protocol, once a | |
360 | /// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again | |
361 | /// may or may not ever return `Some` again. `next()` and `next_back()` are | |
362 | /// interchangable for this purpose. | |
363 | /// | |
364 | /// [`Iterator`]: trait.Iterator.html | |
365 | /// | |
366 | /// # Examples | |
367 | /// | |
368 | /// Basic usage: | |
369 | /// | |
370 | /// ``` | |
5bcae85e | 371 | /// let numbers = vec![1, 2, 3, 4, 5, 6]; |
a7813a04 XL |
372 | /// |
373 | /// let mut iter = numbers.iter(); | |
374 | /// | |
375 | /// assert_eq!(Some(&1), iter.next()); | |
5bcae85e SL |
376 | /// assert_eq!(Some(&6), iter.next_back()); |
377 | /// assert_eq!(Some(&5), iter.next_back()); | |
378 | /// assert_eq!(Some(&2), iter.next()); | |
379 | /// assert_eq!(Some(&3), iter.next()); | |
380 | /// assert_eq!(Some(&4), iter.next()); | |
a7813a04 XL |
381 | /// assert_eq!(None, iter.next()); |
382 | /// assert_eq!(None, iter.next_back()); | |
383 | /// ``` | |
384 | #[stable(feature = "rust1", since = "1.0.0")] | |
385 | pub trait DoubleEndedIterator: Iterator { | |
5bcae85e | 386 | /// Removes and returns an element from the end of the iterator. |
a7813a04 | 387 | /// |
5bcae85e SL |
388 | /// Returns `None` when there are no more elements. |
389 | /// | |
390 | /// The [trait-level] docs contain more details. | |
a7813a04 XL |
391 | /// |
392 | /// [trait-level]: trait.DoubleEndedIterator.html | |
393 | /// | |
394 | /// # Examples | |
395 | /// | |
396 | /// Basic usage: | |
397 | /// | |
398 | /// ``` | |
5bcae85e | 399 | /// let numbers = vec![1, 2, 3, 4, 5, 6]; |
a7813a04 XL |
400 | /// |
401 | /// let mut iter = numbers.iter(); | |
402 | /// | |
403 | /// assert_eq!(Some(&1), iter.next()); | |
5bcae85e SL |
404 | /// assert_eq!(Some(&6), iter.next_back()); |
405 | /// assert_eq!(Some(&5), iter.next_back()); | |
406 | /// assert_eq!(Some(&2), iter.next()); | |
407 | /// assert_eq!(Some(&3), iter.next()); | |
408 | /// assert_eq!(Some(&4), iter.next()); | |
a7813a04 XL |
409 | /// assert_eq!(None, iter.next()); |
410 | /// assert_eq!(None, iter.next_back()); | |
411 | /// ``` | |
412 | #[stable(feature = "rust1", since = "1.0.0")] | |
413 | fn next_back(&mut self) -> Option<Self::Item>; | |
414 | } | |
415 | ||
416 | #[stable(feature = "rust1", since = "1.0.0")] | |
417 | impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I { | |
418 | fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } | |
419 | } | |
420 | ||
421 | /// An iterator that knows its exact length. | |
422 | /// | |
423 | /// Many [`Iterator`]s don't know how many times they will iterate, but some do. | |
424 | /// If an iterator knows how many times it can iterate, providing access to | |
425 | /// that information can be useful. For example, if you want to iterate | |
426 | /// backwards, a good start is to know where the end is. | |
427 | /// | |
428 | /// When implementing an `ExactSizeIterator`, You must also implement | |
429 | /// [`Iterator`]. When doing so, the implementation of [`size_hint()`] *must* | |
430 | /// return the exact size of the iterator. | |
431 | /// | |
432 | /// [`Iterator`]: trait.Iterator.html | |
433 | /// [`size_hint()`]: trait.Iterator.html#method.size_hint | |
434 | /// | |
435 | /// The [`len()`] method has a default implementation, so you usually shouldn't | |
436 | /// implement it. However, you may be able to provide a more performant | |
437 | /// implementation than the default, so overriding it in this case makes sense. | |
438 | /// | |
439 | /// [`len()`]: #method.len | |
440 | /// | |
441 | /// # Examples | |
442 | /// | |
443 | /// Basic usage: | |
444 | /// | |
445 | /// ``` | |
446 | /// // a finite range knows exactly how many times it will iterate | |
447 | /// let five = 0..5; | |
448 | /// | |
449 | /// assert_eq!(5, five.len()); | |
450 | /// ``` | |
451 | /// | |
452 | /// In the [module level docs][moddocs], we implemented an [`Iterator`], | |
453 | /// `Counter`. Let's implement `ExactSizeIterator` for it as well: | |
454 | /// | |
455 | /// [moddocs]: index.html | |
456 | /// | |
457 | /// ``` | |
458 | /// # struct Counter { | |
459 | /// # count: usize, | |
460 | /// # } | |
461 | /// # impl Counter { | |
462 | /// # fn new() -> Counter { | |
463 | /// # Counter { count: 0 } | |
464 | /// # } | |
465 | /// # } | |
466 | /// # impl Iterator for Counter { | |
467 | /// # type Item = usize; | |
468 | /// # fn next(&mut self) -> Option<usize> { | |
469 | /// # self.count += 1; | |
470 | /// # if self.count < 6 { | |
471 | /// # Some(self.count) | |
472 | /// # } else { | |
473 | /// # None | |
474 | /// # } | |
475 | /// # } | |
476 | /// # } | |
477 | /// impl ExactSizeIterator for Counter { | |
478 | /// // We already have the number of iterations, so we can use it directly. | |
479 | /// fn len(&self) -> usize { | |
480 | /// self.count | |
481 | /// } | |
482 | /// } | |
483 | /// | |
484 | /// // And now we can use it! | |
485 | /// | |
486 | /// let counter = Counter::new(); | |
487 | /// | |
488 | /// assert_eq!(0, counter.len()); | |
489 | /// ``` | |
490 | #[stable(feature = "rust1", since = "1.0.0")] | |
491 | pub trait ExactSizeIterator: Iterator { | |
a7813a04 XL |
492 | /// Returns the exact number of times the iterator will iterate. |
493 | /// | |
494 | /// This method has a default implementation, so you usually should not | |
495 | /// implement it directly. However, if you can provide a more efficient | |
496 | /// implementation, you can do so. See the [trait-level] docs for an | |
497 | /// example. | |
498 | /// | |
499 | /// This function has the same safety guarantees as the [`size_hint()`] | |
500 | /// function. | |
501 | /// | |
502 | /// [trait-level]: trait.ExactSizeIterator.html | |
503 | /// [`size_hint()`]: trait.Iterator.html#method.size_hint | |
504 | /// | |
505 | /// # Examples | |
506 | /// | |
507 | /// Basic usage: | |
508 | /// | |
509 | /// ``` | |
510 | /// // a finite range knows exactly how many times it will iterate | |
511 | /// let five = 0..5; | |
512 | /// | |
513 | /// assert_eq!(5, five.len()); | |
514 | /// ``` | |
5bcae85e SL |
515 | #[inline] |
516 | #[stable(feature = "rust1", since = "1.0.0")] | |
a7813a04 XL |
517 | fn len(&self) -> usize { |
518 | let (lower, upper) = self.size_hint(); | |
519 | // Note: This assertion is overly defensive, but it checks the invariant | |
520 | // guaranteed by the trait. If this trait were rust-internal, | |
521 | // we could use debug_assert!; assert_eq! will check all Rust user | |
522 | // implementations too. | |
523 | assert_eq!(upper, Some(lower)); | |
524 | lower | |
525 | } | |
5bcae85e SL |
526 | |
527 | /// Returns whether the iterator is empty. | |
528 | /// | |
529 | /// This method has a default implementation using `self.len()`, so you | |
530 | /// don't need to implement it yourself. | |
531 | /// | |
532 | /// # Examples | |
533 | /// | |
534 | /// Basic usage: | |
535 | /// | |
536 | /// ``` | |
537 | /// #![feature(exact_size_is_empty)] | |
538 | /// | |
539 | /// let mut one_element = 0..1; | |
540 | /// assert!(!one_element.is_empty()); | |
541 | /// | |
542 | /// assert_eq!(one_element.next(), Some(0)); | |
543 | /// assert!(one_element.is_empty()); | |
544 | /// | |
545 | /// assert_eq!(one_element.next(), None); | |
546 | /// ``` | |
547 | #[inline] | |
548 | #[unstable(feature = "exact_size_is_empty", issue = "35428")] | |
549 | fn is_empty(&self) -> bool { | |
550 | self.len() == 0 | |
551 | } | |
a7813a04 XL |
552 | } |
553 | ||
554 | #[stable(feature = "rust1", since = "1.0.0")] | |
555 | impl<'a, I: ExactSizeIterator + ?Sized> ExactSizeIterator for &'a mut I {} | |
556 | ||
3157f602 XL |
557 | /// Trait to represent types that can be created by summing up an iterator. |
558 | /// | |
559 | /// This trait is used to implement the `sum` method on iterators. Types which | |
560 | /// implement the trait can be generated by the `sum` method. Like | |
561 | /// `FromIterator` this trait should rarely be called directly and instead | |
562 | /// interacted with through `Iterator::sum`. | |
5bcae85e | 563 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
564 | pub trait Sum<A = Self>: Sized { |
565 | /// Method which takes an iterator and generates `Self` from the elements by | |
566 | /// "summing up" the items. | |
5bcae85e | 567 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
568 | fn sum<I: Iterator<Item=A>>(iter: I) -> Self; |
569 | } | |
570 | ||
571 | /// Trait to represent types that can be created by multiplying elements of an | |
572 | /// iterator. | |
573 | /// | |
574 | /// This trait is used to implement the `product` method on iterators. Types | |
575 | /// which implement the trait can be generated by the `product` method. Like | |
576 | /// `FromIterator` this trait should rarely be called directly and instead | |
577 | /// interacted with through `Iterator::product`. | |
5bcae85e | 578 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
579 | pub trait Product<A = Self>: Sized { |
580 | /// Method which takes an iterator and generates `Self` from the elements by | |
581 | /// multiplying the items. | |
5bcae85e | 582 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
583 | fn product<I: Iterator<Item=A>>(iter: I) -> Self; |
584 | } | |
585 | ||
9e0c209e | 586 | // NB: explicitly use Add and Mul here to inherit overflow checks |
3157f602 | 587 | macro_rules! integer_sum_product { |
c30ab7b3 | 588 | (@impls $zero:expr, $one:expr, $($a:ty)*) => ($( |
5bcae85e | 589 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
590 | impl Sum for $a { |
591 | fn sum<I: Iterator<Item=$a>>(iter: I) -> $a { | |
c30ab7b3 | 592 | iter.fold($zero, Add::add) |
3157f602 XL |
593 | } |
594 | } | |
595 | ||
5bcae85e | 596 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
597 | impl Product for $a { |
598 | fn product<I: Iterator<Item=$a>>(iter: I) -> $a { | |
c30ab7b3 | 599 | iter.fold($one, Mul::mul) |
3157f602 XL |
600 | } |
601 | } | |
602 | ||
5bcae85e | 603 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
604 | impl<'a> Sum<&'a $a> for $a { |
605 | fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a { | |
c30ab7b3 | 606 | iter.fold($zero, Add::add) |
3157f602 XL |
607 | } |
608 | } | |
609 | ||
5bcae85e | 610 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
611 | impl<'a> Product<&'a $a> for $a { |
612 | fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a { | |
c30ab7b3 | 613 | iter.fold($one, Mul::mul) |
3157f602 XL |
614 | } |
615 | } | |
c30ab7b3 SL |
616 | )*); |
617 | ($($a:ty)*) => ( | |
618 | integer_sum_product!(@impls 0, 1, $($a)+); | |
619 | integer_sum_product!(@impls Wrapping(0), Wrapping(1), $(Wrapping<$a>)+); | |
620 | ); | |
3157f602 XL |
621 | } |
622 | ||
623 | macro_rules! float_sum_product { | |
624 | ($($a:ident)*) => ($( | |
5bcae85e | 625 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
626 | impl Sum for $a { |
627 | fn sum<I: Iterator<Item=$a>>(iter: I) -> $a { | |
628 | iter.fold(0.0, |a, b| a + b) | |
629 | } | |
630 | } | |
631 | ||
5bcae85e | 632 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
633 | impl Product for $a { |
634 | fn product<I: Iterator<Item=$a>>(iter: I) -> $a { | |
635 | iter.fold(1.0, |a, b| a * b) | |
636 | } | |
637 | } | |
638 | ||
5bcae85e | 639 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
640 | impl<'a> Sum<&'a $a> for $a { |
641 | fn sum<I: Iterator<Item=&'a $a>>(iter: I) -> $a { | |
642 | iter.fold(0.0, |a, b| a + *b) | |
643 | } | |
644 | } | |
645 | ||
5bcae85e | 646 | #[stable(feature = "iter_arith_traits", since = "1.12.0")] |
3157f602 XL |
647 | impl<'a> Product<&'a $a> for $a { |
648 | fn product<I: Iterator<Item=&'a $a>>(iter: I) -> $a { | |
649 | iter.fold(1.0, |a, b| a * *b) | |
650 | } | |
651 | } | |
652 | )*) | |
653 | } | |
654 | ||
655 | integer_sum_product! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } | |
656 | float_sum_product! { f32 f64 } | |
9e0c209e SL |
657 | |
658 | /// An iterator that always continues to yield `None` when exhausted. | |
659 | /// | |
660 | /// Calling next on a fused iterator that has returned `None` once is guaranteed | |
661 | /// to return `None` again. This trait is should be implemented by all iterators | |
662 | /// that behave this way because it allows for some significant optimizations. | |
663 | /// | |
664 | /// Note: In general, you should not use `FusedIterator` in generic bounds if | |
665 | /// you need a fused iterator. Instead, you should just call `Iterator::fused()` | |
666 | /// on the iterator. If the iterator is already fused, the additional `Fuse` | |
667 | /// wrapper will be a no-op with no performance penalty. | |
668 | #[unstable(feature = "fused", issue = "35602")] | |
669 | pub trait FusedIterator: Iterator {} | |
670 | ||
671 | #[unstable(feature = "fused", issue = "35602")] | |
672 | impl<'a, I: FusedIterator + ?Sized> FusedIterator for &'a mut I {} | |
c30ab7b3 SL |
673 | |
674 | /// An iterator that reports an accurate length using size_hint. | |
675 | /// | |
676 | /// The iterator reports a size hint where it is either exact | |
677 | /// (lower bound is equal to upper bound), or the upper bound is `None`. | |
678 | /// The upper bound must only be `None` if the actual iterator length is | |
679 | /// larger than `usize::MAX`. | |
680 | /// | |
681 | /// The iterator must produce exactly the number of elements it reported. | |
682 | /// | |
683 | /// # Safety | |
684 | /// | |
685 | /// This trait must only be implemented when the contract is upheld. | |
686 | /// Consumers of this trait must inspect `.size_hint()`’s upper bound. | |
687 | #[unstable(feature = "trusted_len", issue = "37572")] | |
688 | pub unsafe trait TrustedLen : Iterator {} | |
689 | ||
690 | #[unstable(feature = "trusted_len", issue = "37572")] | |
691 | unsafe impl<'a, I: TrustedLen + ?Sized> TrustedLen for &'a mut I {} |