File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -346,6 +346,43 @@ macro_rules! izip {
346
346
} ;
347
347
}
348
348
349
+ #[ macro_export]
350
+ /// Create an iterator running multiple iterators sequentially.
351
+ ///
352
+ /// This is a version of the standard ``.chain()`` that's supporting more than
353
+ /// two iterators. `chain!` takes `IntoIterator` arguments.
354
+ /// Alternatively, this is an alternative to the standard ``.flatten()`` for a
355
+ /// fixed number of iterators of distinct sizes.
356
+ ///
357
+ /// **Note:** The result of this macro is in the general case an iterator
358
+ /// composed of repeated `.chain()`.
359
+ /// The special case of one arguments produce $a.into_iter().
360
+ ///
361
+ ///
362
+ /// ```
363
+ /// # use itertools::chain;
364
+ /// #
365
+ /// # fn main() {
366
+ ///
367
+ /// // chain three sequences
368
+ /// let chained: Vec<i32> = chain!(0..=3, 4..6, vec![6, 7]).collect();
369
+ /// assert_eq!(chained, (0..=7).collect::<Vec<i32>>());
370
+ /// # }
371
+ /// ```
372
+ macro_rules! chain {
373
+ ( ) => {
374
+ core:: iter:: empty( )
375
+ } ;
376
+ ( $first: expr $( , $rest: expr ) * $( , ) * ) => {
377
+ core:: iter:: IntoIterator :: into_iter( $first)
378
+ $(
379
+ . chain(
380
+ core:: iter:: IntoIterator :: into_iter( $rest)
381
+ )
382
+ ) *
383
+ } ;
384
+ }
385
+
349
386
/// An [`Iterator`] blanket implementation that provides extra adaptors and
350
387
/// methods.
351
388
///
Original file line number Diff line number Diff line change @@ -13,6 +13,7 @@ use crate::it::multizip;
13
13
use crate :: it:: free:: put_back;
14
14
use crate :: it:: iproduct;
15
15
use crate :: it:: izip;
16
+ use crate :: it:: chain;
16
17
17
18
#[ test]
18
19
fn product2 ( ) {
@@ -87,6 +88,28 @@ fn multizip3() {
87
88
}
88
89
}
89
90
91
+ #[ test]
92
+ fn chain_macro ( ) {
93
+ let mut chain = chain ! ( 2 ..3 ) ;
94
+ assert ! ( chain. next( ) == Some ( 2 ) ) ;
95
+ assert ! ( chain. next( ) . is_none( ) ) ;
96
+
97
+ let mut chain = chain ! ( 0 ..2 , 2 ..3 , 3 ..5i8 ) ;
98
+ for i in 0 ..5i8 {
99
+ assert_eq ! ( Some ( i) , chain. next( ) ) ;
100
+ }
101
+ assert ! ( chain. next( ) . is_none( ) ) ;
102
+
103
+ let mut chain = chain ! ( ) ;
104
+ assert_eq ! ( chain. next( ) , Option :: <( ) >:: None ) ;
105
+ }
106
+
107
+ #[ test]
108
+ fn chain2 ( ) {
109
+ let _ = chain ! ( 1 .., 2 ..) ;
110
+ let _ = chain ! ( 1 .., 2 .., ) ;
111
+ }
112
+
90
113
#[ test]
91
114
fn write_to ( ) {
92
115
let xs = [ 7 , 9 , 8 ] ;
You can’t perform that action at this time.
0 commit comments