Skip to content

Commit 19f7fdb

Browse files
committed
Add stream::skip_while implementation
1 parent 85a066b commit 19f7fdb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/stream.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,33 @@ pub fn take_while<St, F, Fut>(stream: St, f: F) -> impl Stream<Item = St::Item>
264264
})
265265
}
266266

267+
pub fn skip_while<St, F, Fut>(stream: St, f: F) -> impl Stream<Item = St::Item>
268+
where St: Stream,
269+
F: FnMut(&St::Item) -> Fut,
270+
Fut: Future<Output = bool>,
271+
{
272+
let stream = Box::pin(stream);
273+
let should_skip = true;
274+
futures::stream::unfold((stream, f, should_skip), async move | (mut stream, mut f, should_skip)| {
275+
while should_skip {
276+
if let Some(item) = await!(next(&mut stream)) {
277+
if await!(f(&item)) {
278+
continue;
279+
} else {
280+
return Some((item, (stream, f, /* should_skip */ false)))
281+
}
282+
} else {
283+
return None
284+
}
285+
}
286+
if let Some(item) = await!(next(&mut stream)) {
287+
Some((item, (stream, f, /* should_skip */ false)))
288+
} else {
289+
None
290+
}
291+
})
292+
}
293+
267294
#[cfg(test)]
268295
mod tests {
269296
use futures::executor;
@@ -430,4 +457,12 @@ mod tests {
430457

431458
assert_eq!(vec![1, 2, 3, 4, 5], executor::block_on(collect::<_, Vec<_>>(stream)));
432459
}
460+
461+
#[test]
462+
fn test_skip_while() {
463+
let stream = iter(1..=10);
464+
let stream = skip_while(stream, |x| ready(*x <= 5));
465+
466+
assert_eq!(vec![6, 7, 8, 9, 10], executor::block_on(collect::<_, Vec<_>>(stream)));
467+
}
433468
}

0 commit comments

Comments
 (0)