Skip to content

Commit 6683263

Browse files
committed
Add a chain! macro.
The chain! macro creates an iterator running multiple iterators sequentially.
1 parent 853f064 commit 6683263

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,43 @@ macro_rules! izip {
346346
};
347347
}
348348

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+
349386
/// An [`Iterator`] blanket implementation that provides extra adaptors and
350387
/// methods.
351388
///

tests/test_core.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use crate::it::multizip;
1313
use crate::it::free::put_back;
1414
use crate::it::iproduct;
1515
use crate::it::izip;
16+
use crate::it::chain;
1617

1718
#[test]
1819
fn product2() {
@@ -87,6 +88,28 @@ fn multizip3() {
8788
}
8889
}
8990

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+
90113
#[test]
91114
fn write_to() {
92115
let xs = [7, 9, 8];

0 commit comments

Comments
 (0)