forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iter.rs
2340 lines (2118 loc) · 67.4 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 iterators
# The `Iterator` trait
This module defines Rust's core iteration trait. The `Iterator` trait has one
unimplemented method, `next`. All other methods are derived through default
methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
The goal of this module is to unify iteration across all containers in Rust.
An iterator can be considered as a state machine which is used to track which
element will be yielded next.
There are various extensions also defined in this module to assist with various
types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
the `FromIterator` trait for creating a container from an iterator, and much
more.
## Rust's `for` loop
The special syntax used by rust's `for` loop is based around the `Iterator`
trait defined in this module. For loops can be viewed as a syntactical expansion
into a `loop`, for example, the `for` loop in this example is essentially
translated to the `loop` below.
```rust
let values = vec![1i, 2, 3];
// "Syntactical sugar" taking advantage of an iterator
for &x in values.iter() {
println!("{}", x);
}
// Rough translation of the iteration without a `for` iterator.
let mut it = values.iter();
loop {
match it.next() {
Some(&x) => {
println!("{}", x);
}
None => { break }
}
}
```
This `for` loop syntax can be applied to any iterator over any type.
## Iteration protocol and more
More detailed information about iterators can be found in the [container
guide](http://doc.rust-lang.org/guide-container.html) with
the rest of the rust manuals.
*/
use clone::Clone;
use cmp;
use cmp::{PartialEq, PartialOrd, Ord};
use mem;
use num::{Zero, One, CheckedAdd, CheckedSub, Saturating, ToPrimitive, Int};
use ops::{Add, Mul, Sub};
use option::{Option, Some, None};
use uint;
/// Conversion from an `Iterator`
pub trait FromIterator<A> {
/// Build a container with elements from an external iterator.
fn from_iter<T: Iterator<A>>(iterator: T) -> Self;
}
/// A type growable from an `Iterator` implementation
pub trait Extendable<A>: FromIterator<A> {
/// Extend a container with the elements yielded by an iterator
fn extend<T: Iterator<A>>(&mut self, iterator: T);
}
/// An interface for dealing with "external iterators". These types of iterators
/// can be resumed at any time as all state is stored internally as opposed to
/// being located on the call stack.
///
/// The Iterator protocol states that an iterator yields a (potentially-empty,
/// potentially-infinite) sequence of values, and returns `None` to signal that
/// it's finished. The Iterator protocol does not define behavior after `None`
/// is returned. A concrete Iterator implementation may choose to behave however
/// it wishes, either by returning `None` infinitely, or by doing something
/// else.
pub trait Iterator<A> {
/// Advance the iterator and return the next value. Return `None` when the end is reached.
fn next(&mut self) -> Option<A>;
/// Return a lower bound and upper bound on the remaining length of the iterator.
///
/// The common use case for the estimate is pre-allocating space to store the results.
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
/// Chain this iterator with another, returning a new iterator which will
/// finish iterating over the current iterator, and then it will iterate
/// over the other specified iterator.
///
/// # Example
///
/// ```rust
/// let a = [0i];
/// let b = [1i];
/// let mut it = a.iter().chain(b.iter());
/// assert_eq!(it.next().unwrap(), &0);
/// assert_eq!(it.next().unwrap(), &1);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
Chain{a: self, b: other, flag: false}
}
/// Creates an iterator which iterates over both this and the specified
/// iterators simultaneously, yielding the two elements as pairs. When
/// either iterator returns None, all further invocations of next() will
/// return None.
///
/// # Example
///
/// ```rust
/// let a = [0i];
/// let b = [1i];
/// let mut it = a.iter().zip(b.iter());
/// let (x0, x1) = (0i, 1i);
/// assert_eq!(it.next().unwrap(), (&x0, &x1));
/// assert!(it.next().is_none());
/// ```
#[inline]
fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
Zip{a: self, b: other}
}
/// Creates a new iterator which will apply the specified function to each
/// element returned by the first, yielding the mapped element instead.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2];
/// let mut it = a.iter().map(|&x| 2 * x);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> {
Map{iter: self, f: f}
}
/// Creates an iterator which applies the predicate to each element returned
/// by this iterator. Only elements which have the predicate evaluate to
/// `true` will be yielded.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2];
/// let mut it = a.iter().filter(|&x| *x > 1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> {
Filter{iter: self, predicate: predicate}
}
/// Creates an iterator which both filters and maps elements.
/// If the specified function returns None, the element is skipped.
/// Otherwise the option is unwrapped and the new value is yielded.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2];
/// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
/// assert_eq!(it.next().unwrap(), 4);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> {
FilterMap { iter: self, f: f }
}
/// Creates an iterator which yields a pair of the value returned by this
/// iterator plus the current index of iteration.
///
/// # Example
///
/// ```rust
/// let a = [100i, 200];
/// let mut it = a.iter().enumerate();
/// let (x100, x200) = (100i, 200i);
/// assert_eq!(it.next().unwrap(), (0, &x100));
/// assert_eq!(it.next().unwrap(), (1, &x200));
/// assert!(it.next().is_none());
/// ```
#[inline]
fn enumerate(self) -> Enumerate<Self> {
Enumerate{iter: self, count: 0}
}
/// Creates an iterator that has a `.peek()` method
/// that returns an optional reference to the next element.
///
/// # Example
///
/// ```rust
/// let xs = [100i, 200, 300];
/// let mut it = xs.iter().map(|x| *x).peekable();
/// assert_eq!(*it.peek().unwrap(), 100);
/// assert_eq!(it.next().unwrap(), 100);
/// assert_eq!(it.next().unwrap(), 200);
/// assert_eq!(*it.peek().unwrap(), 300);
/// assert_eq!(*it.peek().unwrap(), 300);
/// assert_eq!(it.next().unwrap(), 300);
/// assert!(it.peek().is_none());
/// assert!(it.next().is_none());
/// ```
#[inline]
fn peekable(self) -> Peekable<A, Self> {
Peekable{iter: self, peeked: None}
}
/// Creates an iterator which invokes the predicate on elements until it
/// returns false. Once the predicate returns false, all further elements are
/// yielded.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().skip_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &3);
/// assert_eq!(it.next().unwrap(), &2);
/// assert_eq!(it.next().unwrap(), &1);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> {
SkipWhile{iter: self, flag: false, predicate: predicate}
}
/// Creates an iterator which yields elements so long as the predicate
/// returns true. After the predicate returns false for the first time, no
/// further elements will be yielded.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 2, 1];
/// let mut it = a.iter().take_while(|&a| *a < 3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> {
TakeWhile{iter: self, flag: false, predicate: predicate}
}
/// Creates an iterator which skips the first `n` elements of this iterator,
/// and then it yields all further items.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().skip(3);
/// assert_eq!(it.next().unwrap(), &4);
/// assert_eq!(it.next().unwrap(), &5);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn skip(self, n: uint) -> Skip<Self> {
Skip{iter: self, n: n}
}
/// Creates an iterator which yields the first `n` elements of this
/// iterator, and then it will always return None.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().take(3);
/// assert_eq!(it.next().unwrap(), &1);
/// assert_eq!(it.next().unwrap(), &2);
/// assert_eq!(it.next().unwrap(), &3);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn take(self, n: uint) -> Take<Self> {
Take{iter: self, n: n}
}
/// Creates a new iterator which behaves in a similar fashion to fold.
/// There is a state which is passed between each iteration and can be
/// mutated as necessary. The yielded values from the closure are yielded
/// from the Scan instance when not None.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().scan(1, |fac, &x| {
/// *fac = *fac * x;
/// Some(*fac)
/// });
/// assert_eq!(it.next().unwrap(), 1);
/// assert_eq!(it.next().unwrap(), 2);
/// assert_eq!(it.next().unwrap(), 6);
/// assert_eq!(it.next().unwrap(), 24);
/// assert_eq!(it.next().unwrap(), 120);
/// assert!(it.next().is_none());
/// ```
#[inline]
fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>)
-> Scan<'r, A, B, Self, St> {
Scan{iter: self, f: f, state: initial_state}
}
/// Creates an iterator that maps each element to an iterator,
/// and yields the elements of the produced iterators
///
/// # Example
///
/// ```rust
/// use std::iter::count;
///
/// let xs = [2u, 3];
/// let ys = [0u, 1, 0, 1, 2];
/// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
/// // Check that `it` has the same elements as `ys`
/// let mut i = 0;
/// for x in it {
/// assert_eq!(x, ys[i]);
/// i += 1;
/// }
/// ```
#[inline]
fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U)
-> FlatMap<'r, A, Self, U> {
FlatMap{iter: self, f: f, frontiter: None, backiter: None }
}
/// Creates an iterator that yields `None` forever after the underlying
/// iterator yields `None`. Random-access iterator behavior is not
/// affected, only single and double-ended iterator behavior.
///
/// # Example
///
/// ```rust
/// fn process<U: Iterator<int>>(it: U) -> int {
/// let mut it = it.fuse();
/// let mut sum = 0;
/// for x in it {
/// if x > 5 {
/// continue;
/// }
/// sum += x;
/// }
/// // did we exhaust the iterator?
/// if it.next().is_none() {
/// sum += 1000;
/// }
/// sum
/// }
/// let x = vec![1i,2,3,7,8,9];
/// assert_eq!(process(x.move_iter()), 1006);
/// ```
#[inline]
fn fuse(self) -> Fuse<Self> {
Fuse{iter: self, done: false}
}
/// Creates an iterator that calls a function with a reference to each
/// element before yielding it. This is often useful for debugging an
/// iterator pipeline.
///
/// # Example
///
/// ```rust
/// use std::iter::AdditiveIterator;
///
/// let xs = [1u, 4, 2, 3, 8, 9, 6];
/// let sum = xs.iter()
/// .map(|&x| x)
/// .inspect(|&x| println!("filtering {}", x))
/// .filter(|&x| x % 2 == 0)
/// .inspect(|&x| println!("{} made it through", x))
/// .sum();
/// println!("{}", sum);
/// ```
#[inline]
fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> {
Inspect{iter: self, f: f}
}
/// Creates a wrapper around a mutable reference to the iterator.
///
/// This is useful to allow applying iterator adaptors while still
/// retaining ownership of the original iterator value.
///
/// # Example
///
/// ```rust
/// let mut xs = range(0u, 10);
/// // sum the first five values
/// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
/// assert!(partial_sum == 10);
/// // xs.next() is now `5`
/// assert!(xs.next() == Some(5));
/// ```
fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
ByRef{iter: self}
}
/// Apply a function to each element, or stop iterating if the
/// function returns `false`.
///
/// # Example
///
/// ```rust,ignore
/// range(0u, 5).advance(|x| {print!("{} ", x); true});
/// ```
#[deprecated = "use the `all` method instead"]
#[inline]
fn advance(&mut self, f: |A| -> bool) -> bool {
loop {
match self.next() {
Some(x) => {
if !f(x) { return false; }
}
None => { return true; }
}
}
}
/// Loops through the entire iterator, collecting all of the elements into
/// a container implementing `FromIterator`.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let b: Vec<int> = a.iter().map(|&x| x).collect();
/// assert!(a.as_slice() == b.as_slice());
/// ```
#[inline]
fn collect<B: FromIterator<A>>(&mut self) -> B {
FromIterator::from_iter(self.by_ref())
}
/// Loops through `n` iterations, returning the `n`th element of the
/// iterator.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.nth(2).unwrap() == &3);
/// assert!(it.nth(2) == None);
/// ```
#[inline]
fn nth(&mut self, mut n: uint) -> Option<A> {
loop {
match self.next() {
Some(x) => if n == 0 { return Some(x) },
None => return None
}
n -= 1;
}
}
/// Loops through the entire iterator, returning the last element of the
/// iterator.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().last().unwrap() == &5);
/// ```
#[inline]
fn last(&mut self) -> Option<A> {
let mut last = None;
for x in *self { last = Some(x); }
last
}
/// Performs a fold operation over the entire iterator, returning the
/// eventual state at the end of the iteration.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
/// ```
#[inline]
fn fold<B>(&mut self, init: B, f: |B, A| -> B) -> B {
let mut accum = init;
loop {
match self.next() {
Some(x) => { accum = f(accum, x); }
None => { break; }
}
}
accum
}
/// Counts the number of elements in this iterator.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.count() == 5);
/// assert!(it.count() == 0);
/// ```
#[inline]
fn count(&mut self) -> uint {
self.fold(0, |cnt, _x| cnt + 1)
}
/// Tests whether the predicate holds true for all elements in the iterator.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().all(|x| *x > 0));
/// assert!(!a.iter().all(|x| *x > 2));
/// ```
#[inline]
fn all(&mut self, f: |A| -> bool) -> bool {
for x in *self { if !f(x) { return false; } }
true
}
/// Tests whether any element of an iterator satisfies the specified
/// predicate.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter();
/// assert!(it.any(|x| *x == 3));
/// assert!(!it.any(|x| *x == 3));
/// ```
#[inline]
fn any(&mut self, f: |A| -> bool) -> bool {
for x in *self { if f(x) { return true; } }
false
}
/// Return the first element satisfying the specified predicate
#[inline]
fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
for x in *self {
if predicate(&x) { return Some(x) }
}
None
}
/// Return the index of the first element satisfying the specified predicate
#[inline]
fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
let mut i = 0;
for x in *self {
if predicate(x) {
return Some(i);
}
i += 1;
}
None
}
/// Return the element that gives the maximum value from the
/// specified function.
///
/// # Example
///
/// ```rust
/// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
/// ```
#[inline]
fn max_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> {
self.fold(None, |max: Option<(A, B)>, x| {
let x_val = f(&x);
match max {
None => Some((x, x_val)),
Some((y, y_val)) => if x_val > y_val {
Some((x, x_val))
} else {
Some((y, y_val))
}
}
}).map(|(x, _)| x)
}
/// Return the element that gives the minimum value from the
/// specified function.
///
/// # Example
///
/// ```rust
/// let xs = [-3i, 0, 1, 5, -10];
/// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
/// ```
#[inline]
fn min_by<B: Ord>(&mut self, f: |&A| -> B) -> Option<A> {
self.fold(None, |min: Option<(A, B)>, x| {
let x_val = f(&x);
match min {
None => Some((x, x_val)),
Some((y, y_val)) => if x_val < y_val {
Some((x, x_val))
} else {
Some((y, y_val))
}
}
}).map(|(x, _)| x)
}
}
/// A range iterator able to yield elements from both ends
pub trait DoubleEndedIterator<A>: Iterator<A> {
/// Yield an element from the end of the range, returning `None` if the range is empty.
fn next_back(&mut self) -> Option<A>;
/// Change the direction of the iterator
///
/// The flipped iterator swaps the ends on an iterator that can already
/// be iterated from the front and from the back.
///
///
/// If the iterator also implements RandomAccessIterator, the flipped
/// iterator is also random access, with the indices starting at the back
/// of the original iterator.
///
/// Note: Random access with flipped indices still only applies to the first
/// `uint::MAX` elements of the original iterator.
#[inline]
fn rev(self) -> Rev<Self> {
Rev{iter: self}
}
}
/// A double-ended iterator yielding mutable references
pub trait MutableDoubleEndedIterator {
// FIXME: #5898: should be called `reverse`
/// Use an iterator to reverse a container in-place
fn reverse_(&mut self);
}
impl<'a, A, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
// FIXME: #5898: should be called `reverse`
/// Use an iterator to reverse a container in-place
fn reverse_(&mut self) {
loop {
match (self.next(), self.next_back()) {
(Some(x), Some(y)) => mem::swap(x, y),
_ => break
}
}
}
}
/// An object implementing random access indexing by `uint`
///
/// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
pub trait RandomAccessIterator<A>: Iterator<A> {
/// Return the number of indexable elements. At most `std::uint::MAX`
/// elements are indexable, even if the iterator represents a longer range.
fn indexable(&self) -> uint;
/// Return an element at an index
fn idx(&mut self, index: uint) -> Option<A>;
}
/// An iterator that knows its exact length
///
/// This trait is a helper for iterators like the vector iterator, so that
/// it can support double-ended enumeration.
///
/// `Iterator::size_hint` *must* return the exact size of the iterator.
/// Note that the size must fit in `uint`.
pub trait ExactSize<A> : DoubleEndedIterator<A> {
/// Return the index of the last element satisfying the specified predicate
///
/// If no element matches, None is returned.
#[inline]
fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
let (lower, upper) = self.size_hint();
assert!(upper == Some(lower));
let mut i = lower;
loop {
match self.next_back() {
None => break,
Some(x) => {
i = match i.checked_sub(&1) {
Some(x) => x,
None => fail!("rposition: incorrect ExactSize")
};
if predicate(x) {
return Some(i)
}
}
}
}
None
}
#[inline]
/// Return the exact length of the iterator.
fn len(&self) -> uint {
let (lower, upper) = self.size_hint();
assert!(upper == Some(lower));
lower
}
}
// All adaptors that preserve the size of the wrapped iterator are fine
// Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
impl<A, T: ExactSize<A>> ExactSize<(uint, A)> for Enumerate<T> {}
impl<'a, A, T: ExactSize<A>> ExactSize<A> for Inspect<'a, A, T> {}
impl<A, T: ExactSize<A>> ExactSize<A> for Rev<T> {}
impl<'a, A, B, T: ExactSize<A>> ExactSize<B> for Map<'a, A, B, T> {}
impl<A, B, T: ExactSize<A>, U: ExactSize<B>> ExactSize<(A, B)> for Zip<T, U> {}
/// An double-ended iterator with the direction inverted
#[deriving(Clone)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct Rev<T> {
iter: T
}
impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
#[inline]
fn next(&mut self) -> Option<A> { self.iter.next_back() }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}
impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.iter.next() }
}
impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
for Rev<T> {
#[inline]
fn indexable(&self) -> uint { self.iter.indexable() }
#[inline]
fn idx(&mut self, index: uint) -> Option<A> {
let amt = self.indexable();
self.iter.idx(amt - index - 1)
}
}
/// A mutable reference to an iterator
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct ByRef<'a, T> {
iter: &'a mut T
}
impl<'a, A, T: Iterator<A>> Iterator<A> for ByRef<'a, T> {
#[inline]
fn next(&mut self) -> Option<A> { self.iter.next() }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}
impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for ByRef<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
}
/// A trait for iterators over elements which can be added together
pub trait AdditiveIterator<A> {
/// Iterates over the entire iterator, summing up all the elements
///
/// # Example
///
/// ```rust
/// use std::iter::AdditiveIterator;
///
/// let a = [1i, 2, 3, 4, 5];
/// let mut it = a.iter().map(|&x| x);
/// assert!(it.sum() == 15);
/// ```
fn sum(&mut self) -> A;
}
impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
#[inline]
fn sum(&mut self) -> A {
let zero: A = Zero::zero();
self.fold(zero, |s, x| s + x)
}
}
/// A trait for iterators over elements whose elements can be multiplied
/// together.
pub trait MultiplicativeIterator<A> {
/// Iterates over the entire iterator, multiplying all the elements
///
/// # Example
///
/// ```rust
/// use std::iter::{count, MultiplicativeIterator};
///
/// fn factorial(n: uint) -> uint {
/// count(1u, 1).take_while(|&i| i <= n).product()
/// }
/// assert!(factorial(0) == 1);
/// assert!(factorial(1) == 1);
/// assert!(factorial(5) == 120);
/// ```
fn product(&mut self) -> A;
}
impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
#[inline]
fn product(&mut self) -> A {
let one: A = One::one();
self.fold(one, |p, x| p * x)
}
}
/// A trait for iterators over elements which can be compared to one another.
/// The type of each element must ascribe to the `PartialOrd` trait.
pub trait OrdIterator<A> {
/// Consumes the entire iterator to return the maximum element.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().max().unwrap() == &5);
/// ```
fn max(&mut self) -> Option<A>;
/// Consumes the entire iterator to return the minimum element.
///
/// # Example
///
/// ```rust
/// let a = [1i, 2, 3, 4, 5];
/// assert!(a.iter().min().unwrap() == &1);
/// ```
fn min(&mut self) -> Option<A>;
/// `min_max` finds the minimum and maximum elements in the iterator.
///
/// The return type `MinMaxResult` is an enum of three variants:
///
/// - `NoElements` if the iterator is empty.
/// - `OneElement(x)` if the iterator has exactly one element.
/// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
/// values are equal if and only if there is more than one
/// element in the iterator and all elements are equal.
///
/// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
/// and so faster than calling `min` and `max separately which does `2 * n` comparisons.
///
/// # Example
///
/// ```rust
/// use std::iter::{NoElements, OneElement, MinMax};
///
/// let v: [int, ..0] = [];
/// assert_eq!(v.iter().min_max(), NoElements);
///
/// let v = [1i];
/// assert!(v.iter().min_max() == OneElement(&1));
///
/// let v = [1i, 2, 3, 4, 5];
/// assert!(v.iter().min_max() == MinMax(&1, &5));
///
/// let v = [1i, 2, 3, 4, 5, 6];
/// assert!(v.iter().min_max() == MinMax(&1, &6));
///
/// let v = [1i, 1, 1, 1];
/// assert!(v.iter().min_max() == MinMax(&1, &1));
/// ```
fn min_max(&mut self) -> MinMaxResult<A>;
}
impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T {
#[inline]
fn max(&mut self) -> Option<A> {
self.fold(None, |max, x| {
match max {
None => Some(x),
Some(y) => Some(cmp::max(x, y))
}
})
}
#[inline]
fn min(&mut self) -> Option<A> {
self.fold(None, |min, x| {
match min {
None => Some(x),
Some(y) => Some(cmp::min(x, y))
}
})
}
fn min_max(&mut self) -> MinMaxResult<A> {
let (mut min, mut max) = match self.next() {
None => return NoElements,
Some(x) => {
match self.next() {
None => return OneElement(x),
Some(y) => if x < y {(x, y)} else {(y,x)}
}
}
};
loop {
// `first` and `second` are the two next elements we want to look at.
// We first compare `first` and `second` (#1). The smaller one is then compared to
// current minimum (#2). The larger one is compared to current maximum (#3). This
// way we do 3 comparisons for 2 elements.
let first = match self.next() {
None => break,
Some(x) => x
};
let second = match self.next() {
None => {
if first < min {
min = first;
} else if first > max {
max = first;
}
break;
}
Some(x) => x
};
if first < second {
if first < min {min = first;}
if max < second {max = second;}
} else {
if second < min {min = second;}
if max < first {max = first;}
}
}
MinMax(min, max)
}
}
/// `MinMaxResult` is an enum returned by `min_max`. See `OrdIterator::min_max` for more detail.
#[deriving(Clone, PartialEq, Show)]
pub enum MinMaxResult<T> {
/// Empty iterator
NoElements,
/// Iterator with one element, so the minimum and maximum are the same
OneElement(T),
/// More than one element in the iterator, the first element is not larger than the second
MinMax(T, T)
}
impl<T: Clone> MinMaxResult<T> {
/// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
/// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
/// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
/// performing this operation will make one clone of `x`.
///
/// # Example
///
/// ```rust
/// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
///
/// let r: MinMaxResult<int> = NoElements;