forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiter.rs
4825 lines (4571 loc) · 142 KB
/
iter.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Composable external iteration
//!
//! If you've found yourself with a collection of some kind, and needed to
//! perform an operation on the elements of said collection, you'll quickly run
//! into 'iterators'. Iterators are heavily used in idiomatic Rust code, so
//! it's worth becoming familiar with them.
//!
//! Before explaining more, let's talk about how this module is structured:
//!
//! # Organization
//!
//! This module is largely organized by type:
//!
//! * [Traits] are the core portion: these traits define what kind of iterators
//! exist and what you can do with them. The methods of these traits are worth
//! putting some extra study time into.
//! * [Functions] provide some helpful ways to create some basic iterators.
//! * [Structs] are often the return types of the various methods on this
//! module's traits. You'll usually want to look at the method that creates
//! the `struct`, rather than the `struct` itself. For more detail about why,
//! see '[Implementing Iterator](#implementing-iterator)'.
//!
//! [Traits]: #traits
//! [Functions]: #functions
//! [Structs]: #structs
//!
//! That's it! Let's dig into iterators.
//!
//! # Iterator
//!
//! The heart and soul of this module is the [`Iterator`] trait. The core of
//! [`Iterator`] looks like this:
//!
//! ```
//! trait Iterator {
//! type Item;
//! fn next(&mut self) -> Option<Self::Item>;
//! }
//! ```
//!
//! An iterator has a method, [`next()`], which when called, returns an
//! [`Option`]`<Item>`. [`next()`] will return `Some(Item)` as long as there
//! are elements, and once they've all been exhausted, will return `None` to
//! indicate that iteration is finished. Individual iterators may choose to
//! resume iteration, and so calling [`next()`] again may or may not eventually
//! start returning `Some(Item)` again at some point.
//!
//! [`Iterator`]'s full definition includes a number of other methods as well,
//! but they are default methods, built on top of [`next()`], and so you get
//! them for free.
//!
//! Iterators are also composable, and it's common to chain them together to do
//! more complex forms of processing. See the [Adapters](#adapters) section
//! below for more details.
//!
//! [`Iterator`]: trait.Iterator.html
//! [`next()`]: trait.Iterator.html#tymethod.next
//! [`Option`]: ../option/enum.Option.html
//!
//! # The three forms of iteration
//!
//! There are three common methods which can create iterators from a collection:
//!
//! * `iter()`, which iterates over `&T`.
//! * `iter_mut()`, which iterates over `&mut T`.
//! * `into_iter()`, which iterates over `T`.
//!
//! Various things in the standard library may implement one or more of the
//! three, where appropriate.
//!
//! # Implementing Iterator
//!
//! Creating an iterator of your own involves two steps: creating a `struct` to
//! hold the iterator's state, and then `impl`ementing [`Iterator`] for that
//! `struct`. This is why there are so many `struct`s in this module: there is
//! one for each iterator and iterator adapter.
//!
//! Let's make an iterator named `Counter` which counts from `1` to `5`:
//!
//! ```
//! // First, the struct:
//!
//! /// An iterator which counts from one to five
//! struct Counter {
//! count: usize,
//! }
//!
//! // we want our count to start at one, so let's add a new() method to help.
//! // This isn't strictly necessary, but is convenient. Note that we start
//! // `count` at zero, we'll see why in `next()`'s implementation below.
//! impl Counter {
//! fn new() -> Counter {
//! Counter { count: 0 }
//! }
//! }
//!
//! // Then, we implement `Iterator` for our `Counter`:
//!
//! impl Iterator for Counter {
//! // we will be counting with usize
//! type Item = usize;
//!
//! // next() is the only required method
//! fn next(&mut self) -> Option<usize> {
//! // increment our count. This is why we started at zero.
//! self.count += 1;
//!
//! // check to see if we've finished counting or not.
//! if self.count < 6 {
//! Some(self.count)
//! } else {
//! None
//! }
//! }
//! }
//!
//! // And now we can use it!
//!
//! let mut counter = Counter::new();
//!
//! let x = counter.next().unwrap();
//! println!("{}", x);
//!
//! let x = counter.next().unwrap();
//! println!("{}", x);
//!
//! let x = counter.next().unwrap();
//! println!("{}", x);
//!
//! let x = counter.next().unwrap();
//! println!("{}", x);
//!
//! let x = counter.next().unwrap();
//! println!("{}", x);
//! ```
//!
//! This will print `1` through `5`, each on their own line.
//!
//! Calling `next()` this way gets repetitive. Rust has a construct which can
//! call `next()` on your iterator, until it reaches `None`. Let's go over that
//! next.
//!
//! # for Loops and IntoIterator
//!
//! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic
//! example of `for`:
//!
//! ```
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! }
//! ```
//!
//! This will print the numbers one through five, each on their own line. But
//! you'll notice something here: we never called anything on our vector to
//! produce an iterator. What gives?
//!
//! There's a trait in the standard library for converting something into an
//! iterator: [`IntoIterator`]. This trait has one method, [`into_iter()`],
//! which converts the thing implementing [`IntoIterator`] into an iterator.
//! Let's take a look at that `for` loop again, and what the compiler converts
//! it into:
//!
//! [`IntoIterator`]: trait.IntoIterator.html
//! [`into_iter()`]: trait.IntoIterator.html#tymethod.into_iter
//!
//! ```
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! }
//! ```
//!
//! Rust de-sugars this into:
//!
//! ```
//! let values = vec![1, 2, 3, 4, 5];
//! {
//! let result = match IntoIterator::into_iter(values) {
//! mut iter => loop {
//! match iter.next() {
//! Some(x) => { println!("{}", x); },
//! None => break,
//! }
//! },
//! };
//! result
//! }
//! ```
//!
//! First, we call `into_iter()` on the value. Then, we match on the iterator
//! that returns, calling [`next()`] over and over until we see a `None`. At
//! that point, we `break` out of the loop, and we're done iterating.
//!
//! There's one more subtle bit here: the standard library contains an
//! interesting implementation of [`IntoIterator`]:
//!
//! ```ignore
//! impl<I: Iterator> IntoIterator for I
//! ```
//!
//! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
//! returning themselves. This means two things:
//!
//! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
//! 2. If you're creating a collection, implementing [`IntoIterator`] for it
//! will allow your collection to be used with the `for` loop.
//!
//! # Adapters
//!
//! Functions which take an [`Iterator`] and return another [`Iterator`] are
//! often called 'iterator adapters', as they're a form of the 'adapter
//! pattern'.
//!
//! Common iterator adapters include [`map()`], [`take()`], and [`collect()`].
//! For more, see their documentation.
//!
//! [`map()`]: trait.Iterator.html#method.map
//! [`take()`]: trait.Iterator.html#method.take
//! [`collect()`]: trait.Iterator.html#method.collect
//!
//! # Laziness
//!
//! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
//! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
//! until you call [`next()`]. This is sometimes a source of confusion when
//! creating an iterator solely for its side effects. For example, the [`map()`]
//! method calls a closure on each element it iterates over:
//!
//! ```
//! # #![allow(unused_must_use)]
//! let v = vec![1, 2, 3, 4, 5];
//! v.iter().map(|x| println!("{}", x));
//! ```
//!
//! This will not print any values, as we only created an iterator, rather than
//! using it. The compiler will warn us about this kind of behavior:
//!
//! ```text
//! warning: unused result which must be used: iterator adaptors are lazy and
//! do nothing unless consumed
//! ```
//!
//! The idiomatic way to write a [`map()`] for its side effects is to use a
//! `for` loop instead:
//!
//! ```
//! let v = vec![1, 2, 3, 4, 5];
//!
//! for x in &v {
//! println!("{}", x);
//! }
//! ```
//!
//! [`map()`]: trait.Iterator.html#method.map
//!
//! The two most common ways to evaluate an iterator are to use a `for` loop
//! like this, or using the [`collect()`] adapter to produce a new collection.
//!
//! [`collect()`]: trait.Iterator.html#method.collect
//!
//! # Infinity
//!
//! Iterators do not have to be finite. As an example, an open-ended range is
//! an infinite iterator:
//!
//! ```
//! let numbers = 0..;
//! ```
//!
//! It is common to use the [`take()`] iterator adapter to turn an infinite
//! iterator into a finite one:
//!
//! ```
//! let numbers = 0..;
//! let five_numbers = numbers.take(5);
//!
//! for number in five_numbers {
//! println!("{}", number);
//! }
//! ```
//!
//! This will print the numbers `0` through `4`, each on their own line.
//!
//! [`take()`]: trait.Iterator.html#method.take
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp;
use cmp::{Ord, PartialOrd, PartialEq, Ordering};
use default::Default;
use marker;
use mem;
use num::{Zero, One};
use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
use option::Option::{self, Some, None};
use marker::Sized;
use usize;
fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
/// An interface for dealing with iterators.
///
/// This is the main iterator trait. For more about the concept of iterators
/// generally, please see the [module-level documentation]. In particular, you
/// may want to know how to [implement `Iterator`][impl].
///
/// [module-level documentation]: index.html
/// [impl]: index.html#implementing-iterator
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented = "`{Self}` is not an iterator; maybe try calling \
`.iter()` or a similar method"]
pub trait Iterator {
/// The type of the elements being iterated over.
#[stable(feature = "rust1", since = "1.0.0")]
type Item;
/// Advances the iterator and returns the next value.
///
/// Returns `None` when iteration is finished. Individual iterator
/// implementations may choose to resume iteration, and so calling `next()`
/// again may or may not eventually start returning `Some(Item)` again at some
/// point.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// // A call to next() returns the next value...
/// assert_eq!(Some(&1), iter.next());
/// assert_eq!(Some(&2), iter.next());
/// assert_eq!(Some(&3), iter.next());
///
/// // ... and then None once it's over.
/// assert_eq!(None, iter.next());
///
/// // More calls may or may not return None. Here, they always will.
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<Self::Item>;
/// Returns the bounds on the remaining length of the iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an `Option<usize>`. A
/// `None` here means that either there is no known upper bound, or the
/// upper bound is larger than `usize`.
///
/// # Implementation notes
///
/// It is not enforced that an iterator implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be
/// trusted to e.g. omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns `(0, None)` which is correct for any
/// iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let iter = a.iter();
///
/// assert_eq!((3, Some(3)), iter.size_hint());
/// ```
///
/// A more complex example:
///
/// ```
/// // The even numbers from zero to ten.
/// let iter = (0..10).filter(|x| x % 2 == 0);
///
/// // We might iterate from zero to ten times. Knowing that it's five
/// // exactly wouldn't be possible without executing filter().
/// assert_eq!((0, Some(10)), iter.size_hint());
///
/// // Let's add one five more numbers with chain()
/// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
///
/// // now both bounds are increased by five
/// assert_eq!((5, Some(15)), iter.size_hint());
/// ```
///
/// Returning `None` for an upper bound:
///
/// ```
/// // an infinite iterator has no upper bound
/// let iter = 0..;
///
/// assert_eq!((0, None), iter.size_hint());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
/// Consumes the iterator, counting the number of iterations and returning it.
///
/// This method will evaluate the iterator until its [`next()`] returns
/// `None`. Once `None` is encountered, `count()` returns the number of
/// times it called [`next()`].
///
/// [`next()`]: #method.next
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so counting elements of
/// an iterator with more than `usize::MAX` elements either produces the
/// wrong result or panics. If debug assertions are enabled, a panic is
/// guaranteed.
///
/// # Panics
///
/// This function might panic if the iterator has more than `usize::MAX`
/// elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().count(), 3);
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().count(), 5);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn count(self) -> usize where Self: Sized {
// Might overflow.
self.fold(0, |cnt, _| cnt + 1)
}
/// Consumes the iterator, returning the last element.
///
/// This method will evaluate the iterator until it returns `None`. While
/// doing so, it keeps track of the current element. After `None` is
/// returned, `last()` will then return the last element it saw.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().last(), Some(&3));
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().last(), Some(&5));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn last(self) -> Option<Self::Item> where Self: Sized {
let mut last = None;
for x in self { last = Some(x); }
last
}
/// Consumes the `n` first elements of the iterator, then returns the
/// `next()` one.
///
/// This method will evaluate the iterator `n` times, discarding those elements.
/// After it does so, it will call [`next()`] and return its value.
///
/// [`next()`]: #method.next
///
/// Like most indexing operations, the count starts from zero, so `nth(0)`
/// returns the first value, `nth(1)` the second, and so on.
///
/// `nth()` will return `None` if `n` is larger than the length of the
/// iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(1), Some(&2));
/// ```
///
/// Calling `nth()` multiple times doesn't rewind the iterator:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.nth(1), Some(&2));
/// assert_eq!(iter.nth(1), None);
/// ```
///
/// Returning `None` if there are less than `n` elements:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(10), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn nth(&mut self, mut n: usize) -> Option<Self::Item> where Self: Sized {
for x in self {
if n == 0 { return Some(x) }
n -= 1;
}
None
}
/// Takes two iterators and creates a new iterator over both in sequence.
///
/// `chain()` will return a new iterator which will first iterate over
/// values from the first iterator and then over values from the second
/// iterator.
///
/// In other words, it links two iterators together, in a chain. 🔗
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().chain(a2.iter());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `chain()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `chain()` directly:
///
/// [`IntoIterator`]: trait.IntoIterator.html
/// [`Iterator`]: trait.Iterator.html
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().chain(s2);
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
Self: Sized, U: IntoIterator<Item=Self::Item>,
{
Chain{a: self, b: other.into_iter(), state: ChainState::Both}
}
/// 'Zips up' two iterators into a single iterator of pairs.
///
/// `zip()` returns a new iterator that will iterate over two other
/// iterators, returning a tuple where the first element comes from the
/// first iterator, and the second element comes from the second iterator.
///
/// In other words, it zips two iterators together, into a single one.
///
/// When either iterator returns `None`, all further calls to `next()`
/// will return `None`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().zip(a2.iter());
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `zip()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `zip()` directly:
///
/// [`IntoIterator`]: trait.IntoIterator.html
/// [`Iterator`]: trait.Iterator.html
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().zip(s2);
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `zip()` is often used to zip an infinite iterator to a finite one.
/// This works because the finite iterator will eventually return `None`,
/// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate()`]:
///
/// ```
/// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
///
/// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
///
/// assert_eq!((0, 'f'), enumerate[0]);
/// assert_eq!((0, 'f'), zipper[0]);
///
/// assert_eq!((1, 'o'), enumerate[1]);
/// assert_eq!((1, 'o'), zipper[1]);
///
/// assert_eq!((2, 'o'), enumerate[2]);
/// assert_eq!((2, 'o'), zipper[2]);
/// ```
///
/// [`enumerate()`]: trait.Iterator.html#method.enumerate
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
Self: Sized, U: IntoIterator
{
Zip{a: self, b: other.into_iter()}
}
/// Takes a closure and creates an iterator which calls that closure on each
/// element.
///
/// `map()` transforms one iterator into another, by means of its argument:
/// something that implements `FnMut`. It produces a new iterator which
/// calls this closure on each element of the original iterator.
///
/// If you are good at thinking in types, you can think of `map()` like this:
/// If you have an iterator that gives you elements of some type `A`, and
/// you want an iterator of some other type `B`, you can use `map()`,
/// passing a closure that takes an `A` and returns a `B`.
///
/// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
/// lazy, it is best used when you're already working with other iterators.
/// If you're doing some sort of looping for a side effect, it's considered
/// more idiomatic to use [`for`] than `map()`.
///
/// [`for`]: ../../book/loops.html#for
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.into_iter().map(|x| 2 * x);
///
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If you're doing some sort of side effect, prefer [`for`] to `map()`:
///
/// ```
/// # #![allow(unused_must_use)]
/// // don't do this:
/// (0..5).map(|x| println!("{}", x));
///
/// // it won't even execute, as it is lazy. Rust will warn you about this.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn map<B, F>(self, f: F) -> Map<Self, F> where
Self: Sized, F: FnMut(Self::Item) -> B,
{
Map{iter: self, f: f}
}
/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
/// The closure must return `true` or `false`. `filter()` creates an
/// iterator which calls this closure on each element. If the closure
/// returns `true`, then the element is returned. If the closure returns
/// `false`, it will try again, and call the closure on the next element,
/// seeing if it passes the test.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0i32, 1, 2];
///
/// let mut iter = a.into_iter().filter(|x| x.is_positive());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `filter()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// It's common to instead use destructuring on the argument to strip away
/// one:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// or both:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// of these layers.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter<P>(self, predicate: P) -> Filter<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,
{
Filter{iter: self, predicate: predicate}
}
/// Creates an iterator that both filters and maps.
///
/// The closure must return an [`Option<T>`]. `filter_map()` creates an
/// iterator which calls this closure on each element. If the closure
/// returns `Some(element)`, then that element is returned. If the
/// closure returns `None`, it will try again, and call the closure on the
/// next element, seeing if it will return `Some`.
///
/// [`Option<T>`]: ../option/enum.Option.html
///
/// Why `filter_map()` and not just [`filter()`].[`map()`]? The key is in this
/// part:
///
/// [`filter()`]: #method.filter
/// [`map()`]: #method.map
///
/// > If the closure returns `Some(element)`, then that element is returned.
///
/// In other words, it removes the [`Option<T>`] layer automatically. If your
/// mapping is already returning an [`Option<T>`] and you want to skip over
/// `None`s, then `filter_map()` is much, much nicer to use.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = ["1", "2", "lol"];
///
/// let mut iter = a.iter().filter_map(|s| s.parse().ok());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`filter()`] and [`map()`]:
///
/// ```
/// let a = ["1", "2", "lol"];
///
/// let mut iter = a.iter()
/// .map(|s| s.parse().ok())
/// .filter(|s| s.is_some());
///
/// assert_eq!(iter.next(), Some(Some(1)));
/// assert_eq!(iter.next(), Some(Some(2)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// There's an extra layer of `Some` in there.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
Self: Sized, F: FnMut(Self::Item) -> Option<B>,
{
FilterMap { iter: self, f: f }
}
/// Creates an iterator which gives the current iteration count as well as
/// the next value.
///
/// The iterator returned yields pairs `(i, val)`, where `i` is the
/// current index of iteration and `val` is the value returned by the
/// iterator.
///
/// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
/// different sized integer, the [`zip()`] function provides similar
/// functionality.
///
/// [`usize`]: ../primitive.usize.html
/// [`zip()`]: #method.zip
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so enumerating more than
/// [`usize::MAX`] elements either produces the wrong result or panics. If
/// debug assertions are enabled, a panic is guaranteed.
///
/// [`usize::MAX`]: ../usize/constant.MAX.html
///
/// # Panics
///
/// The returned iterator might panic if the to-be-returned index would
/// overflow a `usize`.
///
/// # Examples
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().enumerate();
///
/// assert_eq!(iter.next(), Some((0, &1)));
/// assert_eq!(iter.next(), Some((1, &2)));
/// assert_eq!(iter.next(), Some((2, &3)));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn enumerate(self) -> Enumerate<Self> where Self: Sized {
Enumerate { iter: self, count: 0 }
}
/// Creates an iterator which can look at the `next()` element without
/// consuming it.
///
/// Adds a [`peek()`] method to an iterator. See its documentation for
/// more information.
///
/// [`peek()`]: struct.Peekable.html#method.peek
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // peek() lets us see into the future
/// assert_eq!(iter.peek(), Some(&&1));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), Some(&2));
///
/// // we can peek() multiple times, the iterator won't advance
/// assert_eq!(iter.peek(), Some(&&3));
/// assert_eq!(iter.peek(), Some(&&3));
///
/// assert_eq!(iter.next(), Some(&3));
///
/// // after the iterator is finished, so is peek()
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn peekable(self) -> Peekable<Self> where Self: Sized {
Peekable{iter: self, peeked: None}
}
/// Creates an iterator that [`skip()`]s elements based on a predicate.
///
/// [`skip()`]: #method.skip
///
/// `skip_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and ignore elements
/// until it returns `false`.
///
/// After `false` is returned, `skip_while()`'s job is over, and the
/// rest of the elements are yielded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [-1i32, 0, 1];
///
/// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `skip_while()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [-1, 0, 1];
///
/// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial `false`:
///
/// ```
/// let a = [-1, 0, 1, -2];
///
/// let mut iter = a.into_iter().skip_while(|x| **x < 0);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
///
/// // while this would have been false, since we already got a false,
/// // skip_while() isn't used any more
/// assert_eq!(iter.next(), Some(&-2));
///
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,