-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
iterator.rs
3434 lines (3321 loc) · 108 KB
/
iterator.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
// ignore-tidy-filelength
// This file almost exclusively consists of the definition of `Iterator`. We
// can't split that into multiple files.
use crate::cmp::{self, Ordering};
use crate::ops::{ControlFlow, Try};
use super::super::TrustedRandomAccess;
use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse};
use super::super::{FlatMap, Flatten};
use super::super::{FromIterator, Intersperse, IntersperseWith, Product, Sum, Zip};
use super::super::{
Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile,
};
fn _assert_is_object_safe(_: &dyn 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]: crate::iter
/// [impl]: crate::iter#implementing-iterator
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented(
on(
_Self = "[std::ops::Range<Idx>; 1]",
label = "if you meant to iterate between two values, remove the square brackets",
note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
without the brackets: `start..end`"
),
on(
_Self = "[std::ops::RangeFrom<Idx>; 1]",
label = "if you meant to iterate from a value onwards, remove the square brackets",
note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
`RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
unbounded iterator will run forever unless you `break` or `return` from within the \
loop"
),
on(
_Self = "[std::ops::RangeTo<Idx>; 1]",
label = "if you meant to iterate until a value, remove the square brackets and add a \
starting value",
note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
`Range` without the brackets: `0..end`"
),
on(
_Self = "[std::ops::RangeInclusive<Idx>; 1]",
label = "if you meant to iterate between two values, remove the square brackets",
note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
`RangeInclusive` without the brackets: `start..=end`"
),
on(
_Self = "[std::ops::RangeToInclusive<Idx>; 1]",
label = "if you meant to iterate until a value (including it), remove the square brackets \
and add a starting value",
note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
bounded `RangeInclusive` without the brackets: `0..=end`"
),
on(
_Self = "std::ops::RangeTo<Idx>",
label = "if you meant to iterate until a value, add a starting value",
note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
bounded `Range`: `0..end`"
),
on(
_Self = "std::ops::RangeToInclusive<Idx>",
label = "if you meant to iterate until a value (including it), add a starting value",
note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
to have a bounded `RangeInclusive`: `0..=end`"
),
on(
_Self = "&str",
label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self = "std::string::String",
label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self = "[]",
label = "arrays do not yet implement `IntoIterator`; try using `std::array::IntoIter::new(arr)`",
note = "see <https://github.com/rust-lang/rust/pull/65819> for more details"
),
on(
_Self = "{integral}",
note = "if you want to iterate between `start` until a value `end`, use the exclusive range \
syntax `start..end` or the inclusive range syntax `start..=end`"
),
label = "`{Self}` is not an iterator",
message = "`{Self}` is not an iterator"
)]
#[cfg_attr(bootstrap, doc(spotlight))]
#[cfg_attr(not(bootstrap), doc(notable_trait))]
#[rustc_diagnostic_item = "Iterator"]
#[must_use = "iterators are lazy and do nothing unless consumed"]
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.
///
/// [`Some(Item)`]: Some
///
/// # 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());
/// ```
#[lang = "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.
///
/// [`usize`]: type@usize
///
/// # 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 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
/// // and the maximum possible lower bound
/// let iter = 0..;
///
/// assert_eq!((usize::MAX, 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 call [`next`] repeatedly until [`None`] is encountered,
/// returning the number of times it saw [`Some`]. Note that [`next`] has to be
/// called at least once even if the iterator does not have any elements.
///
/// [`next`]: Iterator::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,
{
self.fold(
0,
#[rustc_inherit_overflow_checks]
|count, _| count + 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,
{
#[inline]
fn some<T>(_: Option<T>, x: T) -> Option<T> {
Some(x)
}
self.fold(None, some)
}
/// Advances the iterator by `n` elements.
///
/// This method will eagerly skip `n` elements by calling [`next`] up to `n`
/// times until [`None`] is encountered.
///
/// `advance_by(n)` will return [`Ok(())`][Ok] if the iterator successfully advances by
/// `n` elements, or [`Err(k)`][Err] if [`None`] is encountered, where `k` is the number
/// of elements the iterator is advanced by before running out of elements (i.e. the
/// length of the iterator). Note that `k` is always less than `n`.
///
/// Calling `advance_by(0)` does not consume any elements and always returns [`Ok(())`][Ok].
///
/// [`next`]: Iterator::next
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_advance_by)]
///
/// let a = [1, 2, 3, 4];
/// let mut iter = a.iter();
///
/// assert_eq!(iter.advance_by(2), Ok(()));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.advance_by(0), Ok(()));
/// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped
/// ```
#[inline]
#[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")]
fn advance_by(&mut self, n: usize) -> Result<(), usize> {
for i in 0..n {
self.next().ok_or(i)?;
}
Ok(())
}
/// Returns the `n`th element of the iterator.
///
/// Like most indexing operations, the count starts from zero, so `nth(0)`
/// returns the first value, `nth(1)` the second, and so on.
///
/// Note that all preceding elements, as well as the returned element, will be
/// consumed from the iterator. That means that the preceding elements will be
/// discarded, and also that calling `nth(0)` multiple times on the same iterator
/// will return different elements.
///
/// `nth()` will return [`None`] if `n` is greater than or equal to 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 + 1` 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, n: usize) -> Option<Self::Item> {
self.advance_by(n).ok()?;
self.next()
}
/// Creates an iterator starting at the same point, but stepping by
/// the given amount at each iteration.
///
/// Note 1: The first element of the iterator will always be returned,
/// regardless of the step given.
///
/// Note 2: The time at which ignored elements are pulled is not fixed.
/// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
/// but is also free to behave like the sequence
/// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
/// Which way is used may change for some iterators for performance reasons.
/// The second way will advance the iterator earlier and may consume more items.
///
/// `advance_n_and_return_first` is the equivalent of:
/// ```
/// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
/// where
/// I: Iterator,
/// {
/// let next = iter.next();
/// if total_step > 1 {
/// iter.nth(total_step-2);
/// }
/// next
/// }
/// ```
///
/// # Panics
///
/// The method will panic if the given step is `0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0, 1, 2, 3, 4, 5];
/// let mut iter = a.iter().step_by(2);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "iterator_step_by", since = "1.28.0")]
fn step_by(self, step: usize) -> StepBy<Self>
where
Self: Sized,
{
StepBy::new(self, step)
}
/// 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. 🔗
///
/// [`once`] is commonly used to adapt a single value into a chain of
/// other kinds of iteration.
///
/// # 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:
///
/// ```
/// 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);
/// ```
///
/// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
///
/// ```
/// #[cfg(windows)]
/// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
/// use std::os::windows::ffi::OsStrExt;
/// s.encode_wide().chain(std::iter::once(0)).collect()
/// }
/// ```
///
/// [`once`]: crate::iter::once
/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
#[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::new(self, other.into_iter())
}
/// '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.
///
/// If either iterator returns [`None`], [`next`] from the zipped iterator
/// will return [`None`]. If the first iterator returns [`None`], `zip` will
/// short-circuit and `next` will not be called on the second iterator.
///
/// # 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:
///
/// ```
/// 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`]: Iterator::enumerate
/// [`next`]: Iterator::next
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
where
Self: Sized,
U: IntoIterator,
{
Zip::new(self, other.into_iter())
}
/// Creates a new iterator which places a copy of `separator` between adjacent
/// items of the original iterator.
///
/// In case `separator` does not implement [`Clone`] or needs to be
/// computed every time, use [`intersperse_with`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_intersperse)]
///
/// let mut a = [0, 1, 2].iter().intersperse(&100);
/// assert_eq!(a.next(), Some(&0)); // The first element from `a`.
/// assert_eq!(a.next(), Some(&100)); // The separator.
/// assert_eq!(a.next(), Some(&1)); // The next element from `a`.
/// assert_eq!(a.next(), Some(&100)); // The separator.
/// assert_eq!(a.next(), Some(&2)); // The last element from `a`.
/// assert_eq!(a.next(), None); // The iterator is finished.
/// ```
///
/// `intersperse` can be very useful to join an iterator's items using a common element:
/// ```
/// #![feature(iter_intersperse)]
///
/// let hello = ["Hello", "World", "!"].iter().copied().intersperse(" ").collect::<String>();
/// assert_eq!(hello, "Hello World !");
/// ```
///
/// [`Clone`]: crate::clone::Clone
/// [`intersperse_with`]: Iterator::intersperse_with
#[inline]
#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
where
Self: Sized,
Self::Item: Clone,
{
Intersperse::new(self, separator)
}
/// Creates a new iterator which places an item generated by `separator`
/// between adjacent items of the original iterator.
///
/// The closure will be called exactly once each time an item is placed
/// between two adjacent items from the underlying iterator; specifically,
/// the closure is not called if the underlying iterator yields less than
/// two items and after the last item is yielded.
///
/// If the iterator's item implements [`Clone`], it may be easier to use
/// [`intersperse`].
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(iter_intersperse)]
///
/// #[derive(PartialEq, Debug)]
/// struct NotClone(usize);
///
/// let v = vec![NotClone(0), NotClone(1), NotClone(2)];
/// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
///
/// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
/// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
/// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
/// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
/// assert_eq!(it.next(), Some(NotClone(2))); // The last element from from `v`.
/// assert_eq!(it.next(), None); // The iterator is finished.
/// ```
///
/// `intersperse_with` can be used in situations where the separator needs
/// to be computed:
/// ```
/// #![feature(iter_intersperse)]
///
/// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
///
/// // The closure mutably borrows its context to generate an item.
/// let mut happy_emojis = [" ❤️ ", " 😀 "].iter().copied();
/// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
///
/// let result = src.intersperse_with(separator).collect::<String>();
/// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
/// ```
/// [`Clone`]: crate::clone::Clone
/// [`intersperse`]: Iterator::intersperse
#[inline]
#[unstable(feature = "iter_intersperse", reason = "recently added", issue = "79524")]
fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
where
Self: Sized,
G: FnMut() -> Self::Item,
{
IntersperseWith::new(self, separator)
}
/// 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/ch03-05-control-flow.html#looping-through-a-collection-with-for
/// [`FnMut`]: crate::ops::FnMut
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.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::new(self, f)
}
/// Calls a closure on each element of an iterator.
///
/// This is equivalent to using a [`for`] loop on the iterator, although
/// `break` and `continue` are not possible from a closure. It's generally
/// more idiomatic to use a `for` loop, but `for_each` may be more legible
/// when processing items at the end of longer iterator chains. In some
/// cases `for_each` may also be faster than a loop, because it will use
/// internal iteration on adaptors like `Chain`.
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::sync::mpsc::channel;
///
/// let (tx, rx) = channel();
/// (0..5).map(|x| x * 2 + 1)
/// .for_each(move |x| tx.send(x).unwrap());
///
/// let v: Vec<_> = rx.iter().collect();
/// assert_eq!(v, vec![1, 3, 5, 7, 9]);
/// ```
///
/// For such a small example, a `for` loop may be cleaner, but `for_each`
/// might be preferable to keep a functional style with longer iterators:
///
/// ```
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// ```
#[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")]
fn for_each<F>(self, f: F)
where
Self: Sized,
F: FnMut(Self::Item),
{
#[inline]
fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
move |(), item| f(item)
}
self.fold((), call(f));
}
/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
/// Given an element the closure must return `true` or `false`. The returned
/// iterator will yield only the elements for which the closure returns
/// true.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0i32, 1, 2];
///
/// let mut iter = a.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.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.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.iter().filter(|&&x| x > 1); // two &s
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// of these layers.
///
/// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
#[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::new(self, predicate)
}
/// Creates an iterator that both filters and maps.
///
/// The returned iterator yields only the `value`s for which the supplied
/// closure returns `Some(value)`.
///
/// `filter_map` can be used to make chains of [`filter`] and [`map`] more
/// concise. The example below shows how a `map().filter().map()` can be
/// shortened to a single call to `filter_map`.
///
/// [`filter`]: Iterator::filter
/// [`map`]: Iterator::map
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = ["1", "two", "NaN", "four", "5"];
///
/// let mut iter = a.iter().filter_map(|s| s.parse().ok());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`filter`] and [`map`]:
///
/// ```
/// let a = ["1", "two", "NaN", "four", "5"];
/// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
#[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::new(self, 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.
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so enumerating more than
/// [`usize::MAX`] elements either produces the wrong result or panics. If
/// debug assertions are enabled, a panic is guaranteed.
///
/// # Panics
///
/// The returned iterator might panic if the to-be-returned index would
/// overflow a [`usize`].
///
/// [`usize`]: type@usize
/// [`zip`]: Iterator::zip
///
/// # Examples
///
/// ```
/// let a = ['a', 'b', 'c'];
///
/// let mut iter = a.iter().enumerate();
///
/// assert_eq!(iter.next(), Some((0, &'a')));
/// assert_eq!(iter.next(), Some((1, &'b')));
/// assert_eq!(iter.next(), Some((2, &'c')));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn enumerate(self) -> Enumerate<Self>
where
Self: Sized,
{
Enumerate::new(self)
}
/// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
/// to look at the next element of the iterator without consuming it. See
/// their documentation for more information.
///
/// Note that the underlying iterator is still advanced when [`peek`] or
/// [`peek_mut`] are called for the first time: In order to retrieve the
/// next element, [`next`] is called on the underlying iterator, hence any
/// side effects (i.e. anything other than fetching the next value) of
/// the [`next`] method will occur.
///
///
/// # 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);
/// ```
///
/// Using [`peek_mut`] to mutate the next item without advancing the
/// iterator:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // `peek_mut()` lets us see into the future
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.peek_mut(), Some(&mut &1));
/// assert_eq!(iter.next(), Some(&1));
///
/// if let Some(mut p) = iter.peek_mut() {
/// assert_eq!(*p, &2);
/// // put a value into the iterator
/// *p = &1000;
/// }
///
/// // The value reappears as the iterator continues
/// assert_eq!(iter.collect::<Vec<_>>(), vec![&1000, &3]);
/// ```
/// [`peek`]: Peekable::peek
/// [`peek_mut`]: Peekable::peek_mut