Skip to content

Commit 1d81b7b

Browse files
committed
iterator: add a chain adaptor
1 parent 90313b7 commit 1d81b7b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libcore/iterator.rs

+42
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ pub trait Iterator<A> {
1818
}
1919

2020
pub trait IteratorUtil<A> {
21+
fn chain(self, other: Self) -> ChainIterator<Self>;
2122
fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<Self, U>;
2223
// FIXME: #5898: should be called map
2324
fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>;
@@ -31,6 +32,11 @@ pub trait IteratorUtil<A> {
3132
}
3233

3334
impl<A, T: Iterator<A>> IteratorUtil<A> for T {
35+
#[inline(always)]
36+
fn chain(self, other: T) -> ChainIterator<T> {
37+
ChainIterator{a: self, b: other, flag: false}
38+
}
39+
3440
#[inline(always)]
3541
fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<T, U> {
3642
ZipIterator{a: self, b: other}
@@ -86,6 +92,28 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
8692
}
8793
}
8894

95+
pub struct ChainIterator<T> {
96+
priv a: T,
97+
priv b: T,
98+
priv flag: bool
99+
}
100+
101+
impl<A, T: Iterator<A>> Iterator<A> for ChainIterator<T> {
102+
#[inline]
103+
fn next(&mut self) -> Option<A> {
104+
if self.flag {
105+
self.b.next()
106+
} else {
107+
match self.a.next() {
108+
Some(x) => return Some(x),
109+
_ => ()
110+
}
111+
self.flag = true;
112+
self.b.next()
113+
}
114+
}
115+
}
116+
89117
pub struct ZipIterator<T, U> {
90118
priv a: T,
91119
priv b: U
@@ -288,6 +316,20 @@ mod tests {
288316
use super::*;
289317
use prelude::*;
290318

319+
#[test]
320+
fn test_iterator_chain() {
321+
let xs = [0u, 1, 2, 3, 4, 5];
322+
let ys = [30, 40, 50, 60];
323+
let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
324+
let mut it = xs.iter().chain(ys.iter());
325+
let mut i = 0;
326+
for it.advance |&x: &uint| {
327+
assert_eq!(x, expected[i]);
328+
i += 1;
329+
}
330+
assert_eq!(i, expected.len());
331+
}
332+
291333
#[test]
292334
fn test_iterator_enumerate() {
293335
let xs = [0u, 1, 2, 3, 4, 5];

0 commit comments

Comments
 (0)