Skip to content

Commit 423d520

Browse files
add StreamingIteratorMut::flatten and Flatten
1 parent 723ed72 commit 423d520

File tree

1 file changed

+69
-1
lines changed

1 file changed

+69
-1
lines changed

src/lib.rs

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
#[cfg(feature = "std")]
4646
extern crate core;
4747

48-
use core::cmp;
48+
use core::{cmp, marker::PhantomData};
4949

5050
mod sources;
5151
pub use sources::{convert, Convert};
@@ -597,6 +597,19 @@ pub trait StreamingIteratorMut: StreamingIterator {
597597
{
598598
MapDerefMut { it: self, f }
599599
}
600+
601+
/// Creates an iterator which flattens nested streaming iterators.
602+
#[inline]
603+
fn flatten(self) -> Flatten<Self, Self::Item>
604+
where
605+
Self: Sized,
606+
Self::Item: StreamingIterator + Sized,
607+
{
608+
Flatten {
609+
iter: self,
610+
_inner: PhantomData,
611+
}
612+
}
600613
}
601614

602615
impl<'a, I: ?Sized> StreamingIteratorMut for &'a mut I
@@ -1264,6 +1277,61 @@ where
12641277
}
12651278
}
12661279

1280+
/// A streaming iterator that flattens nested streaming iterators.
1281+
#[derive(Debug)]
1282+
pub struct Flatten<I, J> {
1283+
iter: I,
1284+
_inner: PhantomData<J>,
1285+
}
1286+
1287+
impl<I, J> StreamingIterator for Flatten<I, J>
1288+
where
1289+
I: StreamingIteratorMut<Item = J>,
1290+
J: StreamingIterator,
1291+
{
1292+
type Item = J::Item;
1293+
1294+
#[inline]
1295+
fn advance(&mut self) {
1296+
loop {
1297+
if let Some(ref mut iter) = self.iter.get_mut() {
1298+
iter.advance();
1299+
if !iter.is_done() {
1300+
break;
1301+
}
1302+
}
1303+
self.iter.advance();
1304+
if self.iter.is_done() {
1305+
break;
1306+
}
1307+
}
1308+
}
1309+
1310+
#[inline]
1311+
fn is_done(&self) -> bool {
1312+
match self.iter.get() {
1313+
Some(iter) => iter.is_done(),
1314+
None => true,
1315+
}
1316+
}
1317+
1318+
#[inline]
1319+
fn get(&self) -> Option<&Self::Item> {
1320+
self.iter.get().and_then(|iter| iter.get())
1321+
}
1322+
}
1323+
1324+
impl<I, J> StreamingIteratorMut for Flatten<I, J>
1325+
where
1326+
I: StreamingIteratorMut<Item = J>,
1327+
J: StreamingIteratorMut,
1328+
{
1329+
#[inline]
1330+
fn get_mut(&mut self) -> Option<&mut Self::Item> {
1331+
self.iter.get_mut().and_then(J::get_mut)
1332+
}
1333+
}
1334+
12671335
/// A regular, non-streaming iterator which both filters and maps elements of a streaming iterator with a closure.
12681336
#[derive(Debug)]
12691337
pub struct FilterMapDeref<I, F> {

0 commit comments

Comments
 (0)