|
45 | 45 | #[cfg(feature = "std")]
|
46 | 46 | extern crate core;
|
47 | 47 |
|
48 |
| -use core::cmp; |
| 48 | +use core::{cmp, marker::PhantomData}; |
49 | 49 |
|
50 | 50 | mod sources;
|
51 | 51 | pub use sources::{convert, Convert};
|
@@ -597,6 +597,19 @@ pub trait StreamingIteratorMut: StreamingIterator {
|
597 | 597 | {
|
598 | 598 | MapDerefMut { it: self, f }
|
599 | 599 | }
|
| 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 | + } |
600 | 613 | }
|
601 | 614 |
|
602 | 615 | impl<'a, I: ?Sized> StreamingIteratorMut for &'a mut I
|
@@ -1264,6 +1277,61 @@ where
|
1264 | 1277 | }
|
1265 | 1278 | }
|
1266 | 1279 |
|
| 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 | + |
1267 | 1335 | /// A regular, non-streaming iterator which both filters and maps elements of a streaming iterator with a closure.
|
1268 | 1336 | #[derive(Debug)]
|
1269 | 1337 | pub struct FilterMapDeref<I, F> {
|
|
0 commit comments