streaming_iterator/
lib.rs

1//! Streaming iterators.
2//!
3//! The iterator APIs in the Rust standard library do not allow elements to be yielded which borrow
4//! from the iterator itself. That means, for example, that the `std::io::Lines` iterator must
5//! allocate a new `String` for each line rather than reusing an internal buffer. The
6//! `StreamingIterator` trait instead provides access to elements being iterated over only by
7//! reference rather than by value.
8//!
9//! `StreamingIterator`s cannot be used in Rust `for` loops, but `while let` loops offer a similar
10//! level of ergonomics:
11//!
12//! ```ignore
13//! while let Some(item) = iter.next() {
14//!     // work with item
15//! }
16//! ```
17//!
18//! However, **make sure to only use the above form with a mutable reference to an existing iterator**,
19//! not with an expression that creates an iterator.
20//! For example, the following code will loop forever over the first element of the array:
21//!
22//! ```no_run
23//! use streaming_iterator::{convert, StreamingIterator};
24//! let array = [0, 1, 2, 3];
25//!
26//! while let Some(item) = convert(array.iter()).next() {
27//!   // This is an infinite loop!
28//! }
29//! ```
30//!
31//! While the standard `Iterator` trait's functionality is based off of the `next` method,
32//! `StreamingIterator`'s functionality is based off of a pair of methods: `advance` and `get`. This
33//! essentially splits the logic of `next` in half (in fact, `StreamingIterator`'s `next` method
34//! does nothing but call `advance` followed by `get`).
35//!
36//! This is required because of Rust's lexical handling of borrows (more specifically a lack of
37//! single entry, multiple exit borrows). If `StreamingIterator` was defined like `Iterator` with
38//! just a required `next` method, operations like `filter` would be impossible to define.
39#![doc(html_root_url = "https://docs.rs/streaming-iterator/0.1")]
40#![warn(missing_docs)]
41#![no_std]
42
43#[cfg(feature = "alloc")]
44extern crate alloc;
45
46use core::cmp;
47
48#[cfg(feature = "alloc")]
49use alloc::{borrow::ToOwned, boxed::Box};
50
51mod slice;
52pub use crate::slice::{windows_mut, WindowsMut};
53
54mod sources;
55pub use crate::sources::{convert, Convert};
56pub use crate::sources::{convert_mut, ConvertMut};
57pub use crate::sources::{convert_ref, ConvertRef};
58pub use crate::sources::{empty, Empty};
59pub use crate::sources::{from_fn, FromFn};
60pub use crate::sources::{once, Once};
61pub use crate::sources::{once_with, OnceWith};
62pub use crate::sources::{repeat, Repeat};
63pub use crate::sources::{repeat_with, RepeatWith};
64pub use crate::sources::{successors, Successors};
65
66/// An interface for dealing with streaming iterators.
67pub trait StreamingIterator {
68    /// The type of the elements being iterated over.
69    type Item: ?Sized;
70
71    /// Advances the iterator to the next element.
72    ///
73    /// Iterators start just before the first element, so this should be called before `get`.
74    ///
75    /// The behavior of calling this method after the end of the iterator has been reached is
76    /// unspecified.
77    fn advance(&mut self);
78
79    /// Returns a reference to the current element of the iterator.
80    ///
81    /// The behavior of calling this method before `advance` has been called is unspecified.
82    fn get(&self) -> Option<&Self::Item>;
83
84    /// Advances the iterator and returns the next value.
85    ///
86    /// The behavior of calling this method after the end of the iterator has been reached is
87    /// unspecified.
88    ///
89    /// The default implementation simply calls `advance` followed by `get`.
90    #[inline]
91    fn next(&mut self) -> Option<&Self::Item> {
92        self.advance();
93        (*self).get()
94    }
95
96    /// Returns the bounds on the remaining length of the iterator.
97    #[inline]
98    fn size_hint(&self) -> (usize, Option<usize>) {
99        (0, None)
100    }
101
102    /// Checks if `get()` will return `None`.
103    fn is_done(&self) -> bool {
104        self.get().is_none()
105    }
106
107    /// Determines if all elements of the iterator satisfy a predicate.
108    #[inline]
109    fn all<F>(&mut self, mut f: F) -> bool
110    where
111        Self: Sized,
112        F: FnMut(&Self::Item) -> bool,
113    {
114        while let Some(i) = self.next() {
115            if !f(i) {
116                return false;
117            }
118        }
119
120        true
121    }
122
123    /// Determines if any elements of the iterator satisfy a predicate.
124    #[inline]
125    fn any<F>(&mut self, mut f: F) -> bool
126    where
127        Self: Sized,
128        F: FnMut(&Self::Item) -> bool,
129    {
130        !self.all(|i| !f(i))
131    }
132
133    /// Borrows an iterator, rather than consuming it.
134    ///
135    /// This is useful to allow the application of iterator adaptors while still retaining ownership
136    /// of the original adaptor.
137    #[inline]
138    fn by_ref(&mut self) -> &mut Self
139    where
140        Self: Sized,
141    {
142        self
143    }
144
145    /// Consumes two iterators and returns a new iterator that iterates over both in sequence.
146    #[inline]
147    fn chain<I>(self, other: I) -> Chain<Self, I>
148    where
149        Self: Sized,
150        I: StreamingIterator<Item = Self::Item> + Sized,
151    {
152        Chain {
153            a: self,
154            b: other,
155            state: ChainState::BothForward,
156        }
157    }
158
159    /// Produces a normal, non-streaming, iterator by cloning the elements of this iterator.
160    #[inline]
161    fn cloned(self) -> Cloned<Self>
162    where
163        Self: Sized,
164        Self::Item: Clone,
165    {
166        Cloned(self)
167    }
168
169    /// Produces a normal, non-streaming, iterator by copying the elements of this iterator.
170    #[inline]
171    fn copied(self) -> Copied<Self>
172    where
173        Self: Sized,
174        Self::Item: Copy,
175    {
176        Copied(self)
177    }
178
179    /// Consumes the iterator, counting the number of remaining elements and returning it.
180    #[inline]
181    fn count(self) -> usize
182    where
183        Self: Sized,
184    {
185        self.fold(0, |count, _| count + 1)
186    }
187
188    /// Creates an iterator which uses a closure to determine if an element should be yielded.
189    #[inline]
190    fn filter<F>(self, f: F) -> Filter<Self, F>
191    where
192        Self: Sized,
193        F: FnMut(&Self::Item) -> bool,
194    {
195        Filter { it: self, f }
196    }
197
198    /// Creates an iterator which both filters and maps by applying a closure to elements.
199    #[inline]
200    fn filter_map<B, F>(self, f: F) -> FilterMap<Self, B, F>
201    where
202        Self: Sized,
203        F: FnMut(&Self::Item) -> Option<B>,
204    {
205        FilterMap {
206            it: self,
207            f,
208            item: None,
209        }
210    }
211
212    /// Creates an iterator which flattens iterators obtained by applying a closure to elements.
213    /// Note that the returned iterators must be streaming iterators.
214    #[inline]
215    fn flat_map<J, F>(self, f: F) -> FlatMap<Self, J, F>
216    where
217        Self: Sized,
218        J: StreamingIterator,
219        F: FnMut(&Self::Item) -> J,
220    {
221        FlatMap {
222            it: self,
223            f,
224            sub_iter: None,
225        }
226    }
227
228    /// Creates a regular, non-streaming iterator which both filters and maps by applying a closure to elements.
229    #[inline]
230    fn filter_map_deref<B, F>(self, f: F) -> FilterMapDeref<Self, F>
231    where
232        Self: Sized,
233        F: FnMut(&Self::Item) -> Option<B>,
234    {
235        FilterMapDeref { it: self, f }
236    }
237
238    /// Returns the first element of the iterator that satisfies the predicate.
239    #[inline]
240    fn find<F>(&mut self, mut f: F) -> Option<&Self::Item>
241    where
242        Self: Sized,
243        F: FnMut(&Self::Item) -> bool,
244    {
245        loop {
246            self.advance();
247            match self.get() {
248                Some(i) => {
249                    if f(i) {
250                        break;
251                    }
252                }
253                None => break,
254            }
255        }
256
257        (*self).get()
258    }
259
260    /// Creates an iterator which is "well behaved" at the beginning and end of iteration.
261    ///
262    /// The behavior of calling `get` before iteration has been started, and of continuing to call
263    /// `advance` after `get` has returned `None` is normally unspecified, but this guarantees that
264    /// `get` will return `None` in both cases.
265    #[inline]
266    fn fuse(self) -> Fuse<Self>
267    where
268        Self: Sized,
269    {
270        Fuse {
271            it: self,
272            state: FuseState::Start,
273        }
274    }
275
276    /// Call a closure on each element, passing the element on.
277    /// The closure is called upon calls to `advance` or `advance_back`, and exactly once per element
278    /// regardless of how many times (if any) `get` is called.
279    #[inline]
280    fn inspect<F>(self, f: F) -> Inspect<Self, F>
281    where
282        F: FnMut(&Self::Item),
283        Self: Sized,
284    {
285        Inspect { it: self, f }
286    }
287
288    /// Creates an iterator which transforms elements of this iterator by passing them to a closure.
289    #[inline]
290    fn map<B, F>(self, f: F) -> Map<Self, B, F>
291    where
292        Self: Sized,
293        F: FnMut(&Self::Item) -> B,
294    {
295        Map {
296            it: self,
297            f,
298            item: None,
299        }
300    }
301
302    /// Creates a regular, non-streaming iterator which transforms elements of this iterator by passing them to a closure.
303    #[inline]
304    fn map_deref<B, F>(self, f: F) -> MapDeref<Self, F>
305    where
306        Self: Sized,
307        F: FnMut(&Self::Item) -> B,
308    {
309        MapDeref { it: self, f }
310    }
311
312    /// Creates an iterator which transforms elements of this iterator by passing them to a closure.
313    ///
314    /// Unlike `map`, this method takes a closure that returns a reference into the original value.
315    ///
316    /// The mapping function is only guaranteed to be called at some point before an element
317    /// is actually consumed. This allows an expensive mapping function to be ignored
318    /// during skipping (e.g. `nth`).
319    #[inline]
320    fn map_ref<B: ?Sized, F>(self, f: F) -> MapRef<Self, F>
321    where
322        Self: Sized,
323        F: Fn(&Self::Item) -> &B,
324    {
325        MapRef { it: self, f }
326    }
327
328    /// Consumes the first `n` elements of the iterator, returning the next one.
329    #[inline]
330    fn nth(&mut self, n: usize) -> Option<&Self::Item> {
331        for _ in 0..n {
332            self.advance();
333            if self.is_done() {
334                return None;
335            }
336        }
337        self.next()
338    }
339
340    /// Creates a normal, non-streaming, iterator with elements produced by calling `to_owned` on
341    /// the elements of this iterator.
342    ///
343    /// Requires the `alloc` feature.
344    #[cfg(feature = "alloc")]
345    #[inline]
346    fn owned(self) -> Owned<Self>
347    where
348        Self: Sized,
349        Self::Item: ToOwned,
350    {
351        Owned(self)
352    }
353
354    /// Returns the index of the first element of the iterator matching a predicate.
355    #[inline]
356    fn position<F>(&mut self, mut f: F) -> Option<usize>
357    where
358        Self: Sized,
359        F: FnMut(&Self::Item) -> bool,
360    {
361        let mut n = 0;
362
363        while let Some(i) = self.next() {
364            if f(i) {
365                return Some(n);
366            }
367            n += 1;
368        }
369
370        None
371    }
372
373    /// Creates an iterator which skips the first `n` elements.
374    #[inline]
375    fn skip(self, n: usize) -> Skip<Self>
376    where
377        Self: Sized,
378    {
379        Skip { it: self, n }
380    }
381
382    /// Creates an iterator that skips initial elements matching a predicate.
383    #[inline]
384    fn skip_while<F>(self, f: F) -> SkipWhile<Self, F>
385    where
386        Self: Sized,
387        F: FnMut(&Self::Item) -> bool,
388    {
389        SkipWhile {
390            it: self,
391            f,
392            done: false,
393        }
394    }
395
396    /// Creates an iterator which only returns the first `n` elements.
397    #[inline]
398    fn take(self, n: usize) -> Take<Self>
399    where
400        Self: Sized,
401    {
402        Take {
403            it: self,
404            n,
405            done: false,
406        }
407    }
408
409    /// Creates an iterator which only returns initial elements matching a predicate.
410    #[inline]
411    fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
412    where
413        Self: Sized,
414        F: FnMut(&Self::Item) -> bool,
415    {
416        TakeWhile {
417            it: self,
418            f,
419            done: false,
420        }
421    }
422
423    /// Creates an iterator which returns elemens in the opposite order.
424    #[inline]
425    fn rev(self) -> Rev<Self>
426    where
427        Self: Sized + DoubleEndedStreamingIterator,
428    {
429        Rev(self)
430    }
431
432    /// Reduces the iterator's elements to a single, final value.
433    #[inline]
434    fn fold<B, F>(mut self, init: B, mut f: F) -> B
435    where
436        Self: Sized,
437        F: FnMut(B, &Self::Item) -> B,
438    {
439        let mut acc = init;
440        while let Some(item) = self.next() {
441            acc = f(acc, item);
442        }
443        acc
444    }
445
446    /// Calls a closure on each element of an iterator.
447    #[inline]
448    fn for_each<F>(self, mut f: F)
449    where
450        Self: Sized,
451        F: FnMut(&Self::Item),
452    {
453        self.fold((), move |(), item| f(item));
454    }
455}
456
457impl<'a, I: ?Sized> StreamingIterator for &'a mut I
458where
459    I: StreamingIterator,
460{
461    type Item = I::Item;
462
463    #[inline]
464    fn advance(&mut self) {
465        (**self).advance()
466    }
467
468    #[inline]
469    fn is_done(&self) -> bool {
470        (**self).is_done()
471    }
472
473    #[inline]
474    fn get(&self) -> Option<&Self::Item> {
475        (**self).get()
476    }
477
478    #[inline]
479    fn size_hint(&self) -> (usize, Option<usize>) {
480        (**self).size_hint()
481    }
482
483    #[inline]
484    fn next(&mut self) -> Option<&Self::Item> {
485        (**self).next()
486    }
487}
488
489#[cfg(feature = "alloc")]
490impl<I: ?Sized> StreamingIterator for Box<I>
491where
492    I: StreamingIterator,
493{
494    type Item = I::Item;
495
496    #[inline]
497    fn advance(&mut self) {
498        (**self).advance()
499    }
500
501    #[inline]
502    fn is_done(&self) -> bool {
503        (**self).is_done()
504    }
505
506    #[inline]
507    fn get(&self) -> Option<&Self::Item> {
508        (**self).get()
509    }
510
511    #[inline]
512    fn size_hint(&self) -> (usize, Option<usize>) {
513        (**self).size_hint()
514    }
515
516    #[inline]
517    fn next(&mut self) -> Option<&Self::Item> {
518        (**self).next()
519    }
520}
521
522/// A streaming iterator able to yield elements from both ends.
523pub trait DoubleEndedStreamingIterator: StreamingIterator {
524    /// Advances the iterator to the next element from the back of the iterator.
525    ///
526    /// Double ended iterators just after the last element, so this should be called before `get`
527    /// when iterating in reverse.
528    ///
529    /// The behavior of calling this method after the iterator has been exhausted is unspecified.
530    fn advance_back(&mut self);
531
532    /// Advances the iterator and returns the next value from the back.
533    ///
534    /// The behavior of calling this method after the iterator has been exhausted is unspecified.
535    ///
536    /// The default implementation simply calls `advance_back` followed by `get`.
537    #[inline]
538    fn next_back(&mut self) -> Option<&Self::Item> {
539        self.advance_back();
540        (*self).get()
541    }
542
543    /// Reduces the iterator's elements to a single, final value, starting from the back.
544    #[inline]
545    fn rfold<B, F>(mut self, init: B, mut f: F) -> B
546    where
547        Self: Sized,
548        F: FnMut(B, &Self::Item) -> B,
549    {
550        let mut acc = init;
551        while let Some(item) = self.next_back() {
552            acc = f(acc, item);
553        }
554        acc
555    }
556}
557
558/// An interface for dealing with mutable streaming iterators.
559pub trait StreamingIteratorMut: StreamingIterator {
560    /// Returns a mutable reference to the current element of the iterator.
561    ///
562    /// The behavior of calling this method before `advance` has been called is unspecified.
563    ///
564    /// Modifications through this reference may also have an unspecified effect on further
565    /// iterator advancement, but implementations are encouraged to document this.
566    fn get_mut(&mut self) -> Option<&mut Self::Item>;
567
568    /// Advances the iterator and returns the next mutable value.
569    ///
570    /// The behavior of calling this method after the end of the iterator has been reached is
571    /// unspecified.
572    ///
573    /// The default implementation simply calls `advance` followed by `get_mut`.
574    #[inline]
575    fn next_mut(&mut self) -> Option<&mut Self::Item> {
576        self.advance();
577        (*self).get_mut()
578    }
579
580    /// Reduces the iterator's mutable elements to a single, final value.
581    #[inline]
582    fn fold_mut<B, F>(mut self, init: B, mut f: F) -> B
583    where
584        Self: Sized,
585        F: FnMut(B, &mut Self::Item) -> B,
586    {
587        let mut acc = init;
588        while let Some(item) = self.next_mut() {
589            acc = f(acc, item);
590        }
591        acc
592    }
593
594    /// Calls a closure on each mutable element of an iterator.
595    #[inline]
596    fn for_each_mut<F>(self, mut f: F)
597    where
598        Self: Sized,
599        F: FnMut(&mut Self::Item),
600    {
601        self.fold_mut((), move |(), item| f(item));
602    }
603
604    /// Creates a regular, non-streaming iterator which transforms mutable elements
605    /// of this iterator by passing them to a closure.
606    #[inline]
607    fn map_deref_mut<B, F>(self, f: F) -> MapDerefMut<Self, F>
608    where
609        Self: Sized,
610        F: FnMut(&mut Self::Item) -> B,
611    {
612        MapDerefMut { it: self, f }
613    }
614
615    /// Creates an iterator which flattens nested streaming iterators.
616    #[inline]
617    fn flatten(self) -> Flatten<Self>
618    where
619        Self: Sized,
620        Self::Item: StreamingIterator,
621    {
622        Flatten {
623            iter: self,
624            first: true,
625        }
626    }
627}
628
629impl<'a, I: ?Sized> StreamingIteratorMut for &'a mut I
630where
631    I: StreamingIteratorMut,
632{
633    #[inline]
634    fn get_mut(&mut self) -> Option<&mut Self::Item> {
635        (**self).get_mut()
636    }
637
638    #[inline]
639    fn next_mut(&mut self) -> Option<&mut Self::Item> {
640        (**self).next_mut()
641    }
642}
643
644#[cfg(feature = "alloc")]
645impl<I: ?Sized> StreamingIteratorMut for Box<I>
646where
647    I: StreamingIteratorMut,
648{
649    #[inline]
650    fn get_mut(&mut self) -> Option<&mut Self::Item> {
651        (**self).get_mut()
652    }
653
654    #[inline]
655    fn next_mut(&mut self) -> Option<&mut Self::Item> {
656        (**self).next_mut()
657    }
658}
659
660/// A mutable streaming iterator able to yield elements from both ends.
661pub trait DoubleEndedStreamingIteratorMut:
662    DoubleEndedStreamingIterator + StreamingIteratorMut
663{
664    /// Advances the iterator and returns the next mutable value from the back.
665    ///
666    /// The behavior of calling this method after the end of the iterator has been reached is
667    /// unspecified.
668    ///
669    /// The default implementation simply calls `advance_back` followed by `get_mut`.
670    #[inline]
671    fn next_back_mut(&mut self) -> Option<&mut Self::Item> {
672        self.advance_back();
673        (*self).get_mut()
674    }
675
676    /// Reduces the iterator's mutable elements to a single, final value, starting from the back.
677    #[inline]
678    fn rfold_mut<B, F>(mut self, init: B, mut f: F) -> B
679    where
680        Self: Sized,
681        F: FnMut(B, &mut Self::Item) -> B,
682    {
683        let mut acc = init;
684        while let Some(item) = self.next_back_mut() {
685            acc = f(acc, item);
686        }
687        acc
688    }
689}
690// Note, in theory we could blanket-impl `DoubleEndedStreamingIteratorMut`, but that
691// wouldn't allow custom folding until we can do it with Rust specialization.
692
693/// A streaming iterator that concatenates two streaming iterators
694#[derive(Debug)]
695pub struct Chain<A, B> {
696    a: A,
697    b: B,
698    state: ChainState,
699}
700
701#[derive(Debug)]
702enum ChainState {
703    // Both iterators have items remaining and we are iterating forward
704    BothForward,
705    // Both iterators have items remaining and we are iterating backward
706    BothBackward,
707    // Only the front iterator has items
708    Front,
709    // Only the back iterator has items
710    Back,
711}
712
713impl<A, B> StreamingIterator for Chain<A, B>
714where
715    A: StreamingIterator,
716    B: StreamingIterator<Item = A::Item>,
717{
718    type Item = A::Item;
719
720    #[inline]
721    fn advance(&mut self) {
722        use crate::ChainState::*;
723
724        match self.state {
725            BothForward | BothBackward => {
726                self.a.advance();
727                self.state = if self.a.is_done() {
728                    self.b.advance();
729                    Back
730                } else {
731                    BothForward
732                };
733            }
734            Front => self.a.advance(),
735            Back => self.b.advance(),
736        }
737    }
738
739    #[inline]
740    fn is_done(&self) -> bool {
741        use crate::ChainState::*;
742
743        match self.state {
744            BothForward | Front => self.a.is_done(),
745            BothBackward | Back => self.b.is_done(),
746        }
747    }
748
749    #[inline]
750    fn get(&self) -> Option<&Self::Item> {
751        use crate::ChainState::*;
752
753        match self.state {
754            BothForward | Front => self.a.get(),
755            BothBackward | Back => self.b.get(),
756        }
757    }
758
759    #[inline]
760    fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
761    where
762        Self: Sized,
763        F: FnMut(Acc, &Self::Item) -> Acc,
764    {
765        let mut accum = init;
766        match self.state {
767            ChainState::Back => {}
768            _ => accum = self.a.fold(accum, &mut f),
769        }
770        match self.state {
771            ChainState::Front => {}
772            _ => accum = self.b.fold(accum, &mut f),
773        }
774        accum
775    }
776}
777
778impl<A, B> DoubleEndedStreamingIterator for Chain<A, B>
779where
780    A: DoubleEndedStreamingIterator,
781    B: DoubleEndedStreamingIterator<Item = A::Item>,
782{
783    #[inline]
784    fn advance_back(&mut self) {
785        use crate::ChainState::*;
786
787        match self.state {
788            BothForward | BothBackward => {
789                self.b.advance_back();
790                self.state = if self.b.is_done() {
791                    self.a.advance_back();
792                    Front
793                } else {
794                    BothBackward
795                };
796            }
797            Front => self.a.advance_back(),
798            Back => self.b.advance_back(),
799        }
800    }
801
802    #[inline]
803    fn rfold<Acc, F>(self, init: Acc, mut f: F) -> Acc
804    where
805        Self: Sized,
806        F: FnMut(Acc, &Self::Item) -> Acc,
807    {
808        let mut accum = init;
809        match self.state {
810            ChainState::Front => {}
811            _ => accum = self.b.rfold(accum, &mut f),
812        }
813        match self.state {
814            ChainState::Back => {}
815            _ => accum = self.a.rfold(accum, &mut f),
816        }
817        accum
818    }
819}
820
821impl<A, B> StreamingIteratorMut for Chain<A, B>
822where
823    A: StreamingIteratorMut,
824    B: StreamingIteratorMut<Item = A::Item>,
825{
826    #[inline]
827    fn get_mut(&mut self) -> Option<&mut Self::Item> {
828        use crate::ChainState::*;
829
830        match self.state {
831            BothForward | Front => self.a.get_mut(),
832            BothBackward | Back => self.b.get_mut(),
833        }
834    }
835
836    #[inline]
837    fn fold_mut<Acc, F>(self, init: Acc, mut f: F) -> Acc
838    where
839        Self: Sized,
840        F: FnMut(Acc, &mut Self::Item) -> Acc,
841    {
842        let mut accum = init;
843        match self.state {
844            ChainState::Back => {}
845            _ => accum = self.a.fold_mut(accum, &mut f),
846        }
847        match self.state {
848            ChainState::Front => {}
849            _ => accum = self.b.fold_mut(accum, &mut f),
850        }
851        accum
852    }
853}
854
855impl<A, B> DoubleEndedStreamingIteratorMut for Chain<A, B>
856where
857    A: DoubleEndedStreamingIteratorMut,
858    B: DoubleEndedStreamingIteratorMut<Item = A::Item>,
859{
860    fn rfold_mut<Acc, F>(self, init: Acc, mut f: F) -> Acc
861    where
862        Self: Sized,
863        F: FnMut(Acc, &mut Self::Item) -> Acc,
864    {
865        let mut accum = init;
866        match self.state {
867            ChainState::Front => {}
868            _ => accum = self.b.rfold_mut(accum, &mut f),
869        }
870        match self.state {
871            ChainState::Back => {}
872            _ => accum = self.a.rfold_mut(accum, &mut f),
873        }
874        accum
875    }
876}
877
878/// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned
879/// values by cloning them.
880#[derive(Clone, Debug)]
881pub struct Cloned<I>(I);
882
883impl<I> Iterator for Cloned<I>
884where
885    I: StreamingIterator,
886    I::Item: Clone,
887{
888    type Item = I::Item;
889
890    #[inline]
891    fn next(&mut self) -> Option<I::Item> {
892        self.0.next().cloned()
893    }
894
895    #[inline]
896    fn size_hint(&self) -> (usize, Option<usize>) {
897        self.0.size_hint()
898    }
899
900    #[inline]
901    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
902    where
903        Self: Sized,
904        Fold: FnMut(Acc, Self::Item) -> Acc,
905    {
906        self.0.fold(init, move |acc, item| f(acc, item.clone()))
907    }
908}
909
910impl<I> DoubleEndedIterator for Cloned<I>
911where
912    I: DoubleEndedStreamingIterator,
913    I::Item: Clone,
914{
915    #[inline]
916    fn next_back(&mut self) -> Option<I::Item> {
917        self.0.next_back().cloned()
918    }
919
920    #[inline]
921    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
922    where
923        Self: Sized,
924        Fold: FnMut(Acc, Self::Item) -> Acc,
925    {
926        self.0.rfold(init, move |acc, item| f(acc, item.clone()))
927    }
928}
929
930/// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned
931/// values by copying them.
932#[derive(Clone, Debug)]
933pub struct Copied<I>(I);
934
935impl<I> Iterator for Copied<I>
936where
937    I: StreamingIterator,
938    I::Item: Copy,
939{
940    type Item = I::Item;
941
942    #[inline]
943    fn next(&mut self) -> Option<I::Item> {
944        self.0.next().copied()
945    }
946
947    #[inline]
948    fn size_hint(&self) -> (usize, Option<usize>) {
949        self.0.size_hint()
950    }
951
952    #[inline]
953    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
954    where
955        Self: Sized,
956        Fold: FnMut(Acc, Self::Item) -> Acc,
957    {
958        self.0.fold(init, move |acc, &item| f(acc, item))
959    }
960}
961
962impl<I> DoubleEndedIterator for Copied<I>
963where
964    I: DoubleEndedStreamingIterator,
965    I::Item: Copy,
966{
967    #[inline]
968    fn next_back(&mut self) -> Option<I::Item> {
969        self.0.next_back().copied()
970    }
971
972    #[inline]
973    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
974    where
975        Self: Sized,
976        Fold: FnMut(Acc, Self::Item) -> Acc,
977    {
978        self.0.rfold(init, move |acc, &item| f(acc, item))
979    }
980}
981
982/// A streaming iterator which filters the elements of a streaming iterator with a predicate.
983#[derive(Debug)]
984pub struct Filter<I, F> {
985    it: I,
986    f: F,
987}
988
989impl<I, F> StreamingIterator for Filter<I, F>
990where
991    I: StreamingIterator,
992    F: FnMut(&I::Item) -> bool,
993{
994    type Item = I::Item;
995
996    #[inline]
997    fn advance(&mut self) {
998        while let Some(i) = self.it.next() {
999            if (self.f)(i) {
1000                break;
1001            }
1002        }
1003    }
1004
1005    #[inline]
1006    fn is_done(&self) -> bool {
1007        self.it.is_done()
1008    }
1009
1010    #[inline]
1011    fn get(&self) -> Option<&I::Item> {
1012        self.it.get()
1013    }
1014
1015    #[inline]
1016    fn size_hint(&self) -> (usize, Option<usize>) {
1017        (0, self.it.size_hint().1)
1018    }
1019
1020    #[inline]
1021    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1022    where
1023        Self: Sized,
1024        Fold: FnMut(Acc, &Self::Item) -> Acc,
1025    {
1026        let mut f = self.f;
1027        self.it.fold(
1028            init,
1029            move |acc, item| {
1030                if f(item) {
1031                    fold(acc, item)
1032                } else {
1033                    acc
1034                }
1035            },
1036        )
1037    }
1038}
1039
1040impl<I, F> DoubleEndedStreamingIterator for Filter<I, F>
1041where
1042    I: DoubleEndedStreamingIterator,
1043    F: FnMut(&I::Item) -> bool,
1044{
1045    #[inline]
1046    fn advance_back(&mut self) {
1047        while let Some(i) = self.it.next_back() {
1048            if (self.f)(i) {
1049                break;
1050            }
1051        }
1052    }
1053
1054    #[inline]
1055    fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1056    where
1057        Self: Sized,
1058        Fold: FnMut(Acc, &Self::Item) -> Acc,
1059    {
1060        let mut f = self.f;
1061        self.it.rfold(
1062            init,
1063            move |acc, item| {
1064                if f(item) {
1065                    fold(acc, item)
1066                } else {
1067                    acc
1068                }
1069            },
1070        )
1071    }
1072}
1073
1074impl<I, F> StreamingIteratorMut for Filter<I, F>
1075where
1076    I: StreamingIteratorMut,
1077    F: FnMut(&I::Item) -> bool,
1078{
1079    #[inline]
1080    fn get_mut(&mut self) -> Option<&mut I::Item> {
1081        self.it.get_mut()
1082    }
1083
1084    #[inline]
1085    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1086    where
1087        Self: Sized,
1088        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1089    {
1090        let mut f = self.f;
1091        self.it.fold_mut(
1092            init,
1093            move |acc, item| {
1094                if f(&*item) {
1095                    fold(acc, item)
1096                } else {
1097                    acc
1098                }
1099            },
1100        )
1101    }
1102}
1103
1104impl<I, F> DoubleEndedStreamingIteratorMut for Filter<I, F>
1105where
1106    I: DoubleEndedStreamingIteratorMut,
1107    F: FnMut(&I::Item) -> bool,
1108{
1109    #[inline]
1110    fn rfold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1111    where
1112        Self: Sized,
1113        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1114    {
1115        let mut f = self.f;
1116        self.it.rfold_mut(
1117            init,
1118            move |acc, item| {
1119                if f(&*item) {
1120                    fold(acc, item)
1121                } else {
1122                    acc
1123                }
1124            },
1125        )
1126    }
1127}
1128
1129/// An iterator which both filters and maps elements of a streaming iterator with a closure.
1130#[derive(Debug)]
1131pub struct FilterMap<I, B, F> {
1132    it: I,
1133    f: F,
1134    item: Option<B>,
1135}
1136
1137impl<I, B, F> StreamingIterator for FilterMap<I, B, F>
1138where
1139    I: StreamingIterator,
1140    F: FnMut(&I::Item) -> Option<B>,
1141{
1142    type Item = B;
1143
1144    #[inline]
1145    fn advance(&mut self) {
1146        loop {
1147            match self.it.next() {
1148                Some(i) => {
1149                    if let Some(i) = (self.f)(i) {
1150                        self.item = Some(i);
1151                        break;
1152                    }
1153                }
1154                None => {
1155                    self.item = None;
1156                    break;
1157                }
1158            }
1159        }
1160    }
1161
1162    #[inline]
1163    fn get(&self) -> Option<&B> {
1164        self.item.as_ref()
1165    }
1166
1167    #[inline]
1168    fn size_hint(&self) -> (usize, Option<usize>) {
1169        (0, self.it.size_hint().1)
1170    }
1171
1172    #[inline]
1173    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1174    where
1175        Self: Sized,
1176        Fold: FnMut(Acc, &Self::Item) -> Acc,
1177    {
1178        let mut f = self.f;
1179        self.it.fold(init, move |acc, item| match f(item) {
1180            Some(item) => fold(acc, &item),
1181            None => acc,
1182        })
1183    }
1184}
1185
1186impl<I, B, F> DoubleEndedStreamingIterator for FilterMap<I, B, F>
1187where
1188    I: DoubleEndedStreamingIterator,
1189    F: FnMut(&I::Item) -> Option<B>,
1190{
1191    #[inline]
1192    fn advance_back(&mut self) {
1193        loop {
1194            match self.it.next_back() {
1195                Some(i) => {
1196                    if let Some(i) = (self.f)(i) {
1197                        self.item = Some(i);
1198                        break;
1199                    }
1200                }
1201                None => {
1202                    self.item = None;
1203                    break;
1204                }
1205            }
1206        }
1207    }
1208
1209    #[inline]
1210    fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1211    where
1212        Self: Sized,
1213        Fold: FnMut(Acc, &Self::Item) -> Acc,
1214    {
1215        let mut f = self.f;
1216        self.it.rfold(init, move |acc, item| match f(item) {
1217            Some(item) => fold(acc, &item),
1218            None => acc,
1219        })
1220    }
1221}
1222
1223impl<I, B, F> StreamingIteratorMut for FilterMap<I, B, F>
1224where
1225    I: StreamingIterator,
1226    F: FnMut(&I::Item) -> Option<B>,
1227{
1228    #[inline]
1229    fn get_mut(&mut self) -> Option<&mut B> {
1230        self.item.as_mut()
1231    }
1232
1233    #[inline]
1234    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1235    where
1236        Self: Sized,
1237        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1238    {
1239        let mut f = self.f;
1240        self.it.fold(init, move |acc, item| match f(item) {
1241            Some(mut item) => fold(acc, &mut item),
1242            None => acc,
1243        })
1244    }
1245}
1246
1247impl<I, B, F> DoubleEndedStreamingIteratorMut for FilterMap<I, B, F>
1248where
1249    I: DoubleEndedStreamingIterator,
1250    F: FnMut(&I::Item) -> Option<B>,
1251{
1252    #[inline]
1253    fn rfold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1254    where
1255        Self: Sized,
1256        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1257    {
1258        let mut f = self.f;
1259        self.it.rfold(init, move |acc, item| match f(item) {
1260            Some(mut item) => fold(acc, &mut item),
1261            None => acc,
1262        })
1263    }
1264}
1265
1266/// A streaming iterator that maps elements to iterators with a closure and then yields the
1267/// concatenation of the obtained iterators
1268#[derive(Debug)]
1269pub struct FlatMap<I, J, F> {
1270    it: I,
1271    f: F,
1272    sub_iter: Option<J>,
1273}
1274
1275impl<I, J, F> StreamingIterator for FlatMap<I, J, F>
1276where
1277    I: StreamingIterator,
1278    F: FnMut(&I::Item) -> J,
1279    J: StreamingIterator,
1280{
1281    type Item = J::Item;
1282
1283    #[inline]
1284    fn advance(&mut self) {
1285        loop {
1286            if let Some(ref mut iter) = self.sub_iter {
1287                iter.advance();
1288                if !iter.is_done() {
1289                    break;
1290                }
1291            }
1292            if let Some(item) = self.it.next() {
1293                self.sub_iter = Some((self.f)(item));
1294            } else {
1295                break;
1296            }
1297        }
1298    }
1299
1300    #[inline]
1301    fn is_done(&self) -> bool {
1302        match self.sub_iter {
1303            Some(ref iter) => iter.is_done(),
1304            None => true,
1305        }
1306    }
1307
1308    #[inline]
1309    fn get(&self) -> Option<&Self::Item> {
1310        self.sub_iter.as_ref().and_then(J::get)
1311    }
1312
1313    #[inline]
1314    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1315    where
1316        Self: Sized,
1317        Fold: FnMut(Acc, &Self::Item) -> Acc,
1318    {
1319        let mut acc = init;
1320        if let Some(iter) = self.sub_iter {
1321            acc = iter.fold(acc, &mut fold);
1322        }
1323        let mut f = self.f;
1324        self.it.fold(acc, |acc, item| f(item).fold(acc, &mut fold))
1325    }
1326}
1327
1328impl<I, J, F> StreamingIteratorMut for FlatMap<I, J, F>
1329where
1330    I: StreamingIterator,
1331    F: FnMut(&I::Item) -> J,
1332    J: StreamingIteratorMut,
1333{
1334    #[inline]
1335    fn get_mut(&mut self) -> Option<&mut Self::Item> {
1336        self.sub_iter.as_mut().and_then(J::get_mut)
1337    }
1338
1339    #[inline]
1340    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1341    where
1342        Self: Sized,
1343        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1344    {
1345        let mut acc = init;
1346        if let Some(iter) = self.sub_iter {
1347            acc = iter.fold_mut(acc, &mut fold);
1348        }
1349        let mut f = self.f;
1350        self.it
1351            .fold(acc, |acc, item| f(item).fold_mut(acc, &mut fold))
1352    }
1353}
1354
1355/// A streaming iterator that flattens nested streaming iterators.
1356#[derive(Debug)]
1357pub struct Flatten<I> {
1358    iter: I,
1359    first: bool,
1360}
1361
1362impl<I> StreamingIterator for Flatten<I>
1363where
1364    I: StreamingIteratorMut,
1365    I::Item: StreamingIterator,
1366{
1367    type Item = <I::Item as StreamingIterator>::Item;
1368
1369    #[inline]
1370    fn advance(&mut self) {
1371        if self.first {
1372            self.first = false;
1373            self.iter.advance();
1374        }
1375        while let Some(iter) = self.iter.get_mut() {
1376            iter.advance();
1377            if !iter.is_done() {
1378                break;
1379            }
1380            self.iter.advance(); // since we got Some, self.iter is not done and can be advanced
1381        }
1382    }
1383
1384    #[inline]
1385    fn is_done(&self) -> bool {
1386        match self.iter.get() {
1387            Some(iter) => iter.is_done(),
1388            None => true,
1389        }
1390    }
1391
1392    #[inline]
1393    fn get(&self) -> Option<&Self::Item> {
1394        self.iter.get().and_then(I::Item::get)
1395    }
1396
1397    #[inline]
1398    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1399    where
1400        Self: Sized,
1401        Fold: FnMut(Acc, &Self::Item) -> Acc,
1402    {
1403        self.iter
1404            .fold_mut(init, |acc, item| item.fold(acc, &mut fold))
1405    }
1406}
1407
1408impl<I> StreamingIteratorMut for Flatten<I>
1409where
1410    I: StreamingIteratorMut,
1411    I::Item: StreamingIteratorMut,
1412{
1413    #[inline]
1414    fn get_mut(&mut self) -> Option<&mut Self::Item> {
1415        self.iter.get_mut().and_then(I::Item::get_mut)
1416    }
1417
1418    #[inline]
1419    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1420    where
1421        Self: Sized,
1422        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1423    {
1424        self.iter
1425            .fold_mut(init, |acc, item| item.fold_mut(acc, &mut fold))
1426    }
1427}
1428
1429/// A regular, non-streaming iterator which both filters and maps elements of a streaming iterator with a closure.
1430#[derive(Debug)]
1431pub struct FilterMapDeref<I, F> {
1432    it: I,
1433    f: F,
1434}
1435
1436impl<I, B, F> Iterator for FilterMapDeref<I, F>
1437where
1438    I: StreamingIterator,
1439    F: FnMut(&I::Item) -> Option<B>,
1440{
1441    type Item = B;
1442
1443    #[inline]
1444    fn next(&mut self) -> Option<Self::Item> {
1445        while let Some(item) = self.it.next() {
1446            if let Some(mapped) = (self.f)(item) {
1447                return Some(mapped);
1448            }
1449        }
1450
1451        None
1452    }
1453
1454    #[inline]
1455    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1456    where
1457        Self: Sized,
1458        Fold: FnMut(Acc, Self::Item) -> Acc,
1459    {
1460        let mut map = self.f;
1461        self.it.fold(init, move |acc, item| match map(item) {
1462            Some(mapped) => f(acc, mapped),
1463            None => acc,
1464        })
1465    }
1466}
1467
1468impl<I, B, F> DoubleEndedIterator for FilterMapDeref<I, F>
1469where
1470    I: DoubleEndedStreamingIterator,
1471    F: FnMut(&I::Item) -> Option<B>,
1472{
1473    #[inline]
1474    fn next_back(&mut self) -> Option<B> {
1475        while let Some(item) = self.it.next_back() {
1476            if let Some(mapped) = (self.f)(item) {
1477                return Some(mapped);
1478            }
1479        }
1480
1481        None
1482    }
1483
1484    #[inline]
1485    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1486    where
1487        Self: Sized,
1488        Fold: FnMut(Acc, Self::Item) -> Acc,
1489    {
1490        let mut map = self.f;
1491        self.it.rfold(init, move |acc, item| match map(item) {
1492            Some(mapped) => f(acc, mapped),
1493            None => acc,
1494        })
1495    }
1496}
1497
1498#[derive(Copy, Clone, Debug)]
1499enum FuseState {
1500    Start,
1501    Middle,
1502    End,
1503}
1504
1505/// A streaming iterator which is well-defined before and after iteration.
1506#[derive(Clone, Debug)]
1507pub struct Fuse<I> {
1508    it: I,
1509    state: FuseState,
1510}
1511
1512impl<I> StreamingIterator for Fuse<I>
1513where
1514    I: StreamingIterator,
1515{
1516    type Item = I::Item;
1517
1518    #[inline]
1519    fn advance(&mut self) {
1520        match self.state {
1521            FuseState::Start => {
1522                self.it.advance();
1523                self.state = if self.it.is_done() {
1524                    FuseState::End
1525                } else {
1526                    FuseState::Middle
1527                };
1528            }
1529            FuseState::Middle => {
1530                self.it.advance();
1531                if self.it.is_done() {
1532                    self.state = FuseState::End;
1533                }
1534            }
1535            FuseState::End => {}
1536        }
1537    }
1538
1539    #[inline]
1540    fn is_done(&self) -> bool {
1541        match self.state {
1542            FuseState::Start | FuseState::End => true,
1543            FuseState::Middle => false,
1544        }
1545    }
1546
1547    #[inline]
1548    fn get(&self) -> Option<&I::Item> {
1549        match self.state {
1550            FuseState::Start | FuseState::End => None,
1551            FuseState::Middle => self.it.get(),
1552        }
1553    }
1554
1555    #[inline]
1556    fn size_hint(&self) -> (usize, Option<usize>) {
1557        self.it.size_hint()
1558    }
1559
1560    #[inline]
1561    fn next(&mut self) -> Option<&I::Item> {
1562        match self.state {
1563            FuseState::Start => match self.it.next() {
1564                Some(i) => {
1565                    self.state = FuseState::Middle;
1566                    Some(i)
1567                }
1568                None => {
1569                    self.state = FuseState::End;
1570                    None
1571                }
1572            },
1573            FuseState::Middle => match self.it.next() {
1574                Some(i) => Some(i),
1575                None => {
1576                    self.state = FuseState::End;
1577                    None
1578                }
1579            },
1580            FuseState::End => None,
1581        }
1582    }
1583
1584    #[inline]
1585    fn count(self) -> usize {
1586        match self.state {
1587            FuseState::Start | FuseState::Middle => self.it.count(),
1588            FuseState::End => 0,
1589        }
1590    }
1591
1592    #[inline]
1593    fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1594    where
1595        Self: Sized,
1596        Fold: FnMut(Acc, &Self::Item) -> Acc,
1597    {
1598        match self.state {
1599            FuseState::Start | FuseState::Middle => self.it.fold(init, fold),
1600            FuseState::End => init,
1601        }
1602    }
1603}
1604
1605impl<I> StreamingIteratorMut for Fuse<I>
1606where
1607    I: StreamingIteratorMut,
1608{
1609    #[inline]
1610    fn get_mut(&mut self) -> Option<&mut I::Item> {
1611        match self.state {
1612            FuseState::Start | FuseState::End => None,
1613            FuseState::Middle => self.it.get_mut(),
1614        }
1615    }
1616
1617    #[inline]
1618    fn fold_mut<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
1619    where
1620        Self: Sized,
1621        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1622    {
1623        match self.state {
1624            FuseState::Start | FuseState::Middle => self.it.fold_mut(init, fold),
1625            FuseState::End => init,
1626        }
1627    }
1628}
1629
1630/// A streaming iterator that calls a function with element before yielding it.
1631#[derive(Debug)]
1632pub struct Inspect<I, F> {
1633    it: I,
1634    f: F,
1635}
1636
1637impl<I, F> StreamingIterator for Inspect<I, F>
1638where
1639    I: StreamingIterator,
1640    F: FnMut(&I::Item),
1641{
1642    type Item = I::Item;
1643
1644    fn advance(&mut self) {
1645        if let Some(item) = self.it.next() {
1646            (self.f)(item);
1647        }
1648    }
1649
1650    #[inline]
1651    fn is_done(&self) -> bool {
1652        self.it.is_done()
1653    }
1654
1655    fn get(&self) -> Option<&Self::Item> {
1656        self.it.get()
1657    }
1658
1659    fn size_hint(&self) -> (usize, Option<usize>) {
1660        self.it.size_hint()
1661    }
1662
1663    #[inline]
1664    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1665    where
1666        Self: Sized,
1667        Fold: FnMut(Acc, &Self::Item) -> Acc,
1668    {
1669        let mut f = self.f;
1670        self.it.fold(init, |acc, item| {
1671            f(item);
1672            fold(acc, item)
1673        })
1674    }
1675}
1676
1677impl<I, F> DoubleEndedStreamingIterator for Inspect<I, F>
1678where
1679    I: DoubleEndedStreamingIterator,
1680    F: FnMut(&I::Item),
1681{
1682    fn advance_back(&mut self) {
1683        if let Some(item) = self.it.next_back() {
1684            (self.f)(item);
1685        }
1686    }
1687
1688    #[inline]
1689    fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1690    where
1691        Self: Sized,
1692        Fold: FnMut(Acc, &Self::Item) -> Acc,
1693    {
1694        let mut f = self.f;
1695        self.it.rfold(init, |acc, item| {
1696            f(item);
1697            fold(acc, item)
1698        })
1699    }
1700}
1701
1702impl<I, F> StreamingIteratorMut for Inspect<I, F>
1703where
1704    I: StreamingIteratorMut,
1705    F: FnMut(&I::Item),
1706{
1707    fn get_mut(&mut self) -> Option<&mut Self::Item> {
1708        self.it.get_mut()
1709    }
1710
1711    #[inline]
1712    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1713    where
1714        Self: Sized,
1715        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1716    {
1717        let mut f = self.f;
1718        self.it.fold_mut(init, |acc, item| {
1719            f(&*item);
1720            fold(acc, item)
1721        })
1722    }
1723}
1724
1725impl<I, F> DoubleEndedStreamingIteratorMut for Inspect<I, F>
1726where
1727    I: DoubleEndedStreamingIteratorMut,
1728    F: FnMut(&I::Item),
1729{
1730    #[inline]
1731    fn rfold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1732    where
1733        Self: Sized,
1734        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1735    {
1736        let mut f = self.f;
1737        self.it.rfold_mut(init, |acc, item| {
1738            f(&*item);
1739            fold(acc, item)
1740        })
1741    }
1742}
1743
1744/// A streaming iterator which transforms the elements of a streaming iterator.
1745#[derive(Debug)]
1746pub struct Map<I, B, F> {
1747    it: I,
1748    f: F,
1749    item: Option<B>,
1750}
1751
1752impl<I, B, F> StreamingIterator for Map<I, B, F>
1753where
1754    I: StreamingIterator,
1755    F: FnMut(&I::Item) -> B,
1756{
1757    type Item = B;
1758
1759    #[inline]
1760    fn advance(&mut self) {
1761        self.item = self.it.next().map(&mut self.f);
1762    }
1763
1764    #[inline]
1765    fn get(&self) -> Option<&B> {
1766        self.item.as_ref()
1767    }
1768
1769    #[inline]
1770    fn size_hint(&self) -> (usize, Option<usize>) {
1771        self.it.size_hint()
1772    }
1773
1774    #[inline]
1775    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1776    where
1777        Self: Sized,
1778        Fold: FnMut(Acc, &Self::Item) -> Acc,
1779    {
1780        let mut f = self.f;
1781        self.it.fold(init, move |acc, item| fold(acc, &f(item)))
1782    }
1783}
1784
1785impl<I, B, F> DoubleEndedStreamingIterator for Map<I, B, F>
1786where
1787    I: DoubleEndedStreamingIterator,
1788    F: FnMut(&I::Item) -> B,
1789{
1790    #[inline]
1791    fn advance_back(&mut self) {
1792        self.item = self.it.next_back().map(&mut self.f);
1793    }
1794
1795    #[inline]
1796    fn rfold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1797    where
1798        Self: Sized,
1799        Fold: FnMut(Acc, &Self::Item) -> Acc,
1800    {
1801        let mut f = self.f;
1802        self.it.rfold(init, move |acc, item| fold(acc, &f(item)))
1803    }
1804}
1805
1806impl<I, B, F> StreamingIteratorMut for Map<I, B, F>
1807where
1808    I: StreamingIterator,
1809    F: FnMut(&I::Item) -> B,
1810{
1811    #[inline]
1812    fn get_mut(&mut self) -> Option<&mut B> {
1813        self.item.as_mut()
1814    }
1815
1816    #[inline]
1817    fn fold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1818    where
1819        Self: Sized,
1820        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1821    {
1822        let mut f = self.f;
1823        self.it.fold(init, move |acc, item| fold(acc, &mut f(item)))
1824    }
1825}
1826
1827impl<I, B, F> DoubleEndedStreamingIteratorMut for Map<I, B, F>
1828where
1829    I: DoubleEndedStreamingIterator,
1830    F: FnMut(&I::Item) -> B,
1831{
1832    #[inline]
1833    fn rfold_mut<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1834    where
1835        Self: Sized,
1836        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
1837    {
1838        let mut f = self.f;
1839        self.it
1840            .rfold(init, move |acc, item| fold(acc, &mut f(item)))
1841    }
1842}
1843
1844/// A regular, non-streaming iterator which transforms the elements of a streaming iterator.
1845#[derive(Debug)]
1846pub struct MapDeref<I, F> {
1847    it: I,
1848    f: F,
1849}
1850
1851impl<I, B, F> Iterator for MapDeref<I, F>
1852where
1853    I: StreamingIterator,
1854    F: FnMut(&I::Item) -> B,
1855{
1856    type Item = B;
1857
1858    #[inline]
1859    fn next(&mut self) -> Option<Self::Item> {
1860        self.it.next().map(&mut self.f)
1861    }
1862
1863    #[inline]
1864    fn size_hint(&self) -> (usize, Option<usize>) {
1865        self.it.size_hint()
1866    }
1867
1868    #[inline]
1869    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1870    where
1871        Self: Sized,
1872        Fold: FnMut(Acc, Self::Item) -> Acc,
1873    {
1874        let mut map = self.f;
1875        self.it.fold(init, move |acc, item| f(acc, map(item)))
1876    }
1877}
1878
1879impl<I, B, F> DoubleEndedIterator for MapDeref<I, F>
1880where
1881    I: DoubleEndedStreamingIterator,
1882    F: FnMut(&I::Item) -> B,
1883{
1884    #[inline]
1885    fn next_back(&mut self) -> Option<Self::Item> {
1886        self.it.next_back().map(&mut self.f)
1887    }
1888
1889    #[inline]
1890    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1891    where
1892        Self: Sized,
1893        Fold: FnMut(Acc, Self::Item) -> Acc,
1894    {
1895        let mut map = self.f;
1896        self.it.rfold(init, move |acc, item| f(acc, map(item)))
1897    }
1898}
1899
1900/// A regular, non-streaming iterator which transforms the elements of a mutable streaming iterator.
1901#[derive(Debug)]
1902pub struct MapDerefMut<I, F> {
1903    it: I,
1904    f: F,
1905}
1906
1907impl<I, B, F> Iterator for MapDerefMut<I, F>
1908where
1909    I: StreamingIteratorMut,
1910    F: FnMut(&mut I::Item) -> B,
1911{
1912    type Item = B;
1913
1914    #[inline]
1915    fn next(&mut self) -> Option<Self::Item> {
1916        self.it.next_mut().map(&mut self.f)
1917    }
1918
1919    #[inline]
1920    fn size_hint(&self) -> (usize, Option<usize>) {
1921        self.it.size_hint()
1922    }
1923
1924    #[inline]
1925    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1926    where
1927        Self: Sized,
1928        Fold: FnMut(Acc, Self::Item) -> Acc,
1929    {
1930        let mut map = self.f;
1931        self.it.fold_mut(init, move |acc, item| f(acc, map(item)))
1932    }
1933}
1934
1935impl<I, B, F> DoubleEndedIterator for MapDerefMut<I, F>
1936where
1937    I: DoubleEndedStreamingIteratorMut,
1938    F: FnMut(&mut I::Item) -> B,
1939{
1940    #[inline]
1941    fn next_back(&mut self) -> Option<Self::Item> {
1942        self.it.next_back_mut().map(&mut self.f)
1943    }
1944
1945    #[inline]
1946    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
1947    where
1948        Self: Sized,
1949        Fold: FnMut(Acc, Self::Item) -> Acc,
1950    {
1951        let mut map = self.f;
1952        self.it.rfold_mut(init, move |acc, item| f(acc, map(item)))
1953    }
1954}
1955
1956/// A streaming iterator which transforms the elements of a streaming iterator.
1957#[derive(Debug)]
1958pub struct MapRef<I, F> {
1959    it: I,
1960    f: F,
1961}
1962
1963impl<I, B: ?Sized, F> StreamingIterator for MapRef<I, F>
1964where
1965    I: StreamingIterator,
1966    F: Fn(&I::Item) -> &B,
1967{
1968    type Item = B;
1969
1970    #[inline]
1971    fn advance(&mut self) {
1972        self.it.advance();
1973    }
1974
1975    #[inline]
1976    fn is_done(&self) -> bool {
1977        self.it.is_done()
1978    }
1979
1980    #[inline]
1981    fn get(&self) -> Option<&B> {
1982        self.it.get().map(&self.f)
1983    }
1984
1985    #[inline]
1986    fn size_hint(&self) -> (usize, Option<usize>) {
1987        self.it.size_hint()
1988    }
1989
1990    #[inline]
1991    fn next(&mut self) -> Option<&B> {
1992        self.it.next().map(&self.f)
1993    }
1994
1995    #[inline]
1996    fn fold<Acc, Fold>(self, init: Acc, mut fold: Fold) -> Acc
1997    where
1998        Self: Sized,
1999        Fold: FnMut(Acc, &Self::Item) -> Acc,
2000    {
2001        let f = self.f;
2002        self.it.fold(init, move |acc, item| fold(acc, f(item)))
2003    }
2004}
2005
2006/// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned
2007/// versions.
2008///
2009/// Requires the `alloc` feature.
2010#[cfg(feature = "alloc")]
2011#[derive(Clone, Debug)]
2012pub struct Owned<I>(I);
2013
2014#[cfg(feature = "alloc")]
2015impl<I> Iterator for Owned<I>
2016where
2017    I: StreamingIterator,
2018    I::Item: ToOwned,
2019{
2020    type Item = <I::Item as ToOwned>::Owned;
2021
2022    #[inline]
2023    fn next(&mut self) -> Option<<I::Item as ToOwned>::Owned> {
2024        self.0.next().map(ToOwned::to_owned)
2025    }
2026
2027    #[inline]
2028    fn size_hint(&self) -> (usize, Option<usize>) {
2029        self.0.size_hint()
2030    }
2031
2032    #[inline]
2033    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
2034    where
2035        Self: Sized,
2036        Fold: FnMut(Acc, Self::Item) -> Acc,
2037    {
2038        self.0.fold(init, move |acc, item| f(acc, item.to_owned()))
2039    }
2040}
2041
2042#[cfg(feature = "alloc")]
2043impl<I> DoubleEndedIterator for Owned<I>
2044where
2045    I: DoubleEndedStreamingIterator,
2046    I::Item: Sized + ToOwned,
2047{
2048    #[inline]
2049    fn next_back(&mut self) -> Option<<I::Item as ToOwned>::Owned> {
2050        self.0.next_back().map(ToOwned::to_owned)
2051    }
2052
2053    #[inline]
2054    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
2055    where
2056        Self: Sized,
2057        Fold: FnMut(Acc, Self::Item) -> Acc,
2058    {
2059        self.0.rfold(init, move |acc, item| f(acc, item.to_owned()))
2060    }
2061}
2062
2063/// A streaming iterator which skips a number of elements in a streaming iterator.
2064#[derive(Clone, Debug)]
2065pub struct Skip<I> {
2066    it: I,
2067    n: usize,
2068}
2069
2070impl<I> StreamingIterator for Skip<I>
2071where
2072    I: StreamingIterator,
2073{
2074    type Item = I::Item;
2075
2076    #[inline]
2077    fn advance(&mut self) {
2078        self.it.nth(self.n);
2079        self.n = 0;
2080    }
2081
2082    #[inline]
2083    fn is_done(&self) -> bool {
2084        self.it.is_done()
2085    }
2086
2087    #[inline]
2088    fn get(&self) -> Option<&I::Item> {
2089        self.it.get()
2090    }
2091
2092    #[inline]
2093    fn size_hint(&self) -> (usize, Option<usize>) {
2094        let hint = self.it.size_hint();
2095        (
2096            hint.0.saturating_sub(self.n),
2097            hint.1.map(|n| n.saturating_sub(self.n)),
2098        )
2099    }
2100
2101    #[inline]
2102    fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2103    where
2104        Self: Sized,
2105        Fold: FnMut(Acc, &Self::Item) -> Acc,
2106    {
2107        if self.n > 0 {
2108            // nth(n) skips n+1
2109            if self.it.nth(self.n - 1).is_none() {
2110                return init;
2111            }
2112        }
2113        self.it.fold(init, fold)
2114    }
2115}
2116
2117impl<I> StreamingIteratorMut for Skip<I>
2118where
2119    I: StreamingIteratorMut,
2120{
2121    fn get_mut(&mut self) -> Option<&mut Self::Item> {
2122        self.it.get_mut()
2123    }
2124
2125    #[inline]
2126    fn fold_mut<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
2127    where
2128        Self: Sized,
2129        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
2130    {
2131        if self.n > 0 {
2132            // nth(n) skips n+1
2133            if self.it.nth(self.n - 1).is_none() {
2134                return init;
2135            }
2136        }
2137        self.it.fold_mut(init, fold)
2138    }
2139}
2140
2141/// A streaming iterator which skips initial elements that match a predicate
2142#[derive(Clone, Debug)]
2143pub struct SkipWhile<I, F> {
2144    it: I,
2145    f: F,
2146    done: bool,
2147}
2148
2149impl<I, F> StreamingIterator for SkipWhile<I, F>
2150where
2151    I: StreamingIterator,
2152    F: FnMut(&I::Item) -> bool,
2153{
2154    type Item = I::Item;
2155
2156    #[inline]
2157    fn advance(&mut self) {
2158        if !self.done {
2159            let f = &mut self.f;
2160            self.it.find(|i| !f(i));
2161            self.done = true;
2162        } else {
2163            self.it.advance();
2164        }
2165    }
2166
2167    #[inline]
2168    fn is_done(&self) -> bool {
2169        self.it.is_done()
2170    }
2171
2172    #[inline]
2173    fn get(&self) -> Option<&I::Item> {
2174        self.it.get()
2175    }
2176
2177    #[inline]
2178    fn size_hint(&self) -> (usize, Option<usize>) {
2179        let hint = self.it.size_hint();
2180        (0, hint.1)
2181    }
2182
2183    #[inline]
2184    fn fold<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
2185    where
2186        Self: Sized,
2187        Fold: FnMut(Acc, &Self::Item) -> Acc,
2188    {
2189        if !self.done {
2190            match self.next() {
2191                Some(item) => init = fold(init, item),
2192                None => return init,
2193            }
2194        }
2195        self.it.fold(init, fold)
2196    }
2197}
2198
2199impl<I, F> StreamingIteratorMut for SkipWhile<I, F>
2200where
2201    I: StreamingIteratorMut,
2202    F: FnMut(&I::Item) -> bool,
2203{
2204    fn get_mut(&mut self) -> Option<&mut Self::Item> {
2205        self.it.get_mut()
2206    }
2207
2208    #[inline]
2209    fn fold_mut<Acc, Fold>(mut self, mut init: Acc, mut fold: Fold) -> Acc
2210    where
2211        Self: Sized,
2212        Fold: FnMut(Acc, &mut Self::Item) -> Acc,
2213    {
2214        if !self.done {
2215            match self.next_mut() {
2216                Some(item) => init = fold(init, item),
2217                None => return init,
2218            }
2219        }
2220        self.it.fold_mut(init, fold)
2221    }
2222}
2223
2224/// A streaming iterator which only yields a limited number of elements in a streaming iterator.
2225#[derive(Clone, Debug)]
2226pub struct Take<I> {
2227    it: I,
2228    n: usize,
2229    done: bool,
2230}
2231
2232impl<I> StreamingIterator for Take<I>
2233where
2234    I: StreamingIterator,
2235{
2236    type Item = I::Item;
2237
2238    #[inline]
2239    fn advance(&mut self) {
2240        if self.n != 0 {
2241            self.it.advance();
2242            self.n -= 1;
2243        } else {
2244            self.done = true;
2245        }
2246    }
2247
2248    #[inline]
2249    fn is_done(&self) -> bool {
2250        self.done || self.it.is_done()
2251    }
2252
2253    #[inline]
2254    fn get(&self) -> Option<&I::Item> {
2255        if self.done {
2256            None
2257        } else {
2258            self.it.get()
2259        }
2260    }
2261
2262    #[inline]
2263    fn size_hint(&self) -> (usize, Option<usize>) {
2264        let hint = self.it.size_hint();
2265        (cmp::min(hint.0, self.n), Some(self.n))
2266    }
2267}
2268
2269impl<I> StreamingIteratorMut for Take<I>
2270where
2271    I: StreamingIteratorMut,
2272{
2273    #[inline]
2274    fn get_mut(&mut self) -> Option<&mut I::Item> {
2275        if self.done {
2276            None
2277        } else {
2278            self.it.get_mut()
2279        }
2280    }
2281}
2282
2283/// A streaming iterator which only returns initial elements matching a predicate.
2284#[derive(Debug)]
2285pub struct TakeWhile<I, F> {
2286    it: I,
2287    f: F,
2288    done: bool,
2289}
2290
2291impl<I, F> StreamingIterator for TakeWhile<I, F>
2292where
2293    I: StreamingIterator,
2294    F: FnMut(&I::Item) -> bool,
2295{
2296    type Item = I::Item;
2297
2298    #[inline]
2299    fn advance(&mut self) {
2300        if !self.done {
2301            self.it.advance();
2302            if let Some(i) = self.it.get() {
2303                if !(self.f)(i) {
2304                    self.done = true;
2305                }
2306            }
2307        }
2308    }
2309
2310    #[inline]
2311    fn is_done(&self) -> bool {
2312        self.done || self.it.is_done()
2313    }
2314
2315    #[inline]
2316    fn get(&self) -> Option<&I::Item> {
2317        if self.done {
2318            None
2319        } else {
2320            self.it.get()
2321        }
2322    }
2323
2324    #[inline]
2325    fn next(&mut self) -> Option<&I::Item> {
2326        if self.done {
2327            None
2328        } else {
2329            match self.it.next() {
2330                Some(i) => {
2331                    if (self.f)(i) {
2332                        Some(i)
2333                    } else {
2334                        self.done = true;
2335                        None
2336                    }
2337                }
2338                None => None,
2339            }
2340        }
2341    }
2342
2343    #[inline]
2344    fn size_hint(&self) -> (usize, Option<usize>) {
2345        let upper = if self.done {
2346            Some(0)
2347        } else {
2348            self.it.size_hint().1
2349        };
2350        (0, upper)
2351    }
2352}
2353
2354impl<I, F> StreamingIteratorMut for TakeWhile<I, F>
2355where
2356    I: StreamingIteratorMut,
2357    F: FnMut(&I::Item) -> bool,
2358{
2359    #[inline]
2360    fn get_mut(&mut self) -> Option<&mut I::Item> {
2361        if self.done {
2362            None
2363        } else {
2364            self.it.get_mut()
2365        }
2366    }
2367}
2368
2369/// A streaming iterator which returns elements in the opposite order.
2370pub struct Rev<I>(I);
2371
2372impl<I> StreamingIterator for Rev<I>
2373where
2374    I: DoubleEndedStreamingIterator,
2375{
2376    type Item = I::Item;
2377
2378    #[inline]
2379    fn advance(&mut self) {
2380        self.0.advance_back();
2381    }
2382
2383    #[inline]
2384    fn is_done(&self) -> bool {
2385        self.0.is_done()
2386    }
2387
2388    #[inline]
2389    fn get(&self) -> Option<&I::Item> {
2390        self.0.get()
2391    }
2392
2393    #[inline]
2394    fn next(&mut self) -> Option<&I::Item> {
2395        self.0.next_back()
2396    }
2397
2398    #[inline]
2399    fn size_hint(&self) -> (usize, Option<usize>) {
2400        self.0.size_hint()
2401    }
2402
2403    #[inline]
2404    fn fold<Acc, Fold>(self, init: Acc, f: Fold) -> Acc
2405    where
2406        Self: Sized,
2407        Fold: FnMut(Acc, &Self::Item) -> Acc,
2408    {
2409        self.0.rfold(init, f)
2410    }
2411}
2412
2413impl<I> DoubleEndedStreamingIterator for Rev<I>
2414where
2415    I: DoubleEndedStreamingIterator,
2416{
2417    #[inline]
2418    fn advance_back(&mut self) {
2419        self.0.advance();
2420    }
2421
2422    #[inline]
2423    fn next_back(&mut self) -> Option<&I::Item> {
2424        self.0.next()
2425    }
2426
2427    #[inline]
2428    fn rfold<Acc, Fold>(self, init: Acc, f: Fold) -> Acc
2429    where
2430        Self: Sized,
2431        Fold: FnMut(Acc, &Self::Item) -> Acc,
2432    {
2433        self.0.fold(init, f)
2434    }
2435}
2436
2437impl<I> StreamingIteratorMut for Rev<I>
2438where
2439    I: DoubleEndedStreamingIteratorMut,
2440{
2441    #[inline]
2442    fn get_mut(&mut self) -> Option<&mut I::Item> {
2443        self.0.get_mut()
2444    }
2445
2446    #[inline]
2447    fn fold_mut<B, F>(self, init: B, f: F) -> B
2448    where
2449        Self: Sized,
2450        F: FnMut(B, &mut Self::Item) -> B,
2451    {
2452        self.0.rfold_mut(init, f)
2453    }
2454}
2455
2456impl<I> DoubleEndedStreamingIteratorMut for Rev<I>
2457where
2458    I: DoubleEndedStreamingIteratorMut,
2459{
2460    #[inline]
2461    fn rfold_mut<B, F>(self, init: B, f: F) -> B
2462    where
2463        Self: Sized,
2464        F: FnMut(B, &mut Self::Item) -> B,
2465    {
2466        self.0.fold_mut(init, f)
2467    }
2468}
2469
2470/// Conversion from [`IntoIterator`] to [`StreamingIterator`].
2471pub trait IntoStreamingIterator: IntoIterator
2472where
2473    Self: Sized,
2474{
2475    /// Turns an [`IntoIterator`] into a [`StreamingIterator`].
2476    ///
2477    /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert`].
2478    #[inline]
2479    fn into_streaming_iter(self) -> Convert<Self::IntoIter> {
2480        convert(self)
2481    }
2482
2483    /// Turns an [`IntoIterator`] of references into a [`StreamingIterator`].
2484    ///
2485    /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert_ref`].
2486    #[inline]
2487    fn into_streaming_iter_ref<'a, T: ?Sized>(self) -> ConvertRef<'a, Self::IntoIter, T>
2488    where
2489        Self: IntoIterator<Item = &'a T>,
2490    {
2491        convert_ref(self)
2492    }
2493
2494    /// Turns an [`IntoIterator`] of mutable references into a [`StreamingIteratorMut`].
2495    ///
2496    /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert_mut`].
2497    #[inline]
2498    fn into_streaming_iter_mut<'a, T: ?Sized>(self) -> ConvertMut<'a, Self::IntoIter, T>
2499    where
2500        Self: IntoIterator<Item = &'a mut T>,
2501    {
2502        convert_mut(self)
2503    }
2504}
2505
2506impl<I> IntoStreamingIterator for I where I: IntoIterator {}
2507
2508#[cfg(test)]
2509mod test {
2510    use core::fmt::Debug;
2511
2512    #[cfg(feature = "alloc")]
2513    use alloc::vec::Vec;
2514
2515    use super::*;
2516
2517    fn test<I>(mut it: I, expected: &[I::Item])
2518    where
2519        I: StreamingIterator,
2520        I::Item: Sized + PartialEq + Debug,
2521    {
2522        for item in expected {
2523            it.advance();
2524            assert_eq!(it.get(), Some(item));
2525            assert_eq!(it.get(), Some(item));
2526        }
2527        it.advance();
2528        assert_eq!(it.get(), None);
2529        assert_eq!(it.get(), None);
2530    }
2531
2532    fn test_back<I>(mut it: I, expected: &[I::Item])
2533    where
2534        I: DoubleEndedStreamingIterator,
2535        I::Item: Sized + PartialEq + Debug,
2536    {
2537        for item in expected {
2538            it.advance_back();
2539            assert_eq!(it.get(), Some(item));
2540            assert_eq!(it.get(), Some(item));
2541        }
2542        it.advance_back();
2543        assert_eq!(it.get(), None);
2544        assert_eq!(it.get(), None);
2545    }
2546
2547    fn test_deref<I>(mut it: I, expected: &[I::Item])
2548    where
2549        I: Iterator,
2550        I::Item: Sized + PartialEq + Debug,
2551    {
2552        for item in expected {
2553            assert_eq!(it.next().as_ref(), Some(item));
2554        }
2555        assert_eq!(it.next(), None)
2556    }
2557
2558    #[test]
2559    fn all() {
2560        let items = [0, 1, 2];
2561        let mut it = convert(items);
2562        assert!(it.clone().all(|&i| i < 3));
2563        assert!(!it.all(|&i| i % 2 == 0));
2564    }
2565
2566    #[test]
2567    fn any() {
2568        let items = [0, 1, 2];
2569        let mut it = convert(items);
2570        assert!(it.clone().any(|&i| i > 1));
2571        assert!(!it.any(|&i| i > 2));
2572    }
2573
2574    #[test]
2575    fn test_chain() {
2576        let items_a = [0, 1, 2, 3];
2577        let items_b = [10, 20, 30];
2578        let expected = [0, 1, 2, 3, 10, 20, 30];
2579
2580        let it = convert(items_a).chain(convert(items_b));
2581        test(it, &expected);
2582    }
2583
2584    #[test]
2585    fn test_chain_back() {
2586        let items_a = [0, 1, 2, 3];
2587        let items_b = [10, 20, 30];
2588        let expected = [30, 20, 10, 3, 2, 1, 0];
2589
2590        let it = convert(items_a).chain(convert(items_b));
2591        test_back(it, &expected);
2592    }
2593
2594    #[test]
2595    fn test_chain_mixed() {
2596        let items_a = [0, 1, 2, 3];
2597        let items_b = [10, 20, 30];
2598
2599        let mut it = convert(items_a).chain(convert(items_b));
2600
2601        assert_eq!(it.get(), None);
2602        it.advance();
2603        assert_eq!(it.get().copied(), Some(0));
2604        it.advance_back();
2605        assert_eq!(it.get().copied(), Some(30));
2606        it.advance();
2607        assert_eq!(it.get().copied(), Some(1));
2608        it.advance_back();
2609        assert_eq!(it.get().copied(), Some(20));
2610        it.advance();
2611        assert_eq!(it.get().copied(), Some(2));
2612        it.advance_back();
2613        assert_eq!(it.get().copied(), Some(10));
2614        it.advance_back();
2615        assert_eq!(it.get().copied(), Some(3));
2616    }
2617
2618    #[test]
2619    fn cloned() {
2620        let items = [0, 1];
2621        let mut it = convert(items).cloned();
2622        assert_eq!(it.next(), Some(0));
2623        assert_eq!(it.next(), Some(1));
2624        assert_eq!(it.next(), None);
2625    }
2626
2627    #[test]
2628    fn copied() {
2629        let items = [0, 1];
2630        let mut it = convert(items).copied();
2631        assert_eq!(it.next(), Some(0));
2632        assert_eq!(it.next(), Some(1));
2633        assert_eq!(it.next(), None);
2634    }
2635
2636    #[test]
2637    fn test_convert() {
2638        let items = [0, 1];
2639        let it = convert(items);
2640        test(it, &items);
2641    }
2642
2643    #[test]
2644    fn test_convert_ref() {
2645        let items = [&0, &1];
2646        let it = convert_ref(items.iter());
2647        test(it, &items);
2648    }
2649
2650    #[test]
2651    fn count() {
2652        let items = [0, 1, 2, 3];
2653        let it = convert(items);
2654        assert_eq!(it.count(), 4);
2655    }
2656
2657    #[test]
2658    fn filter() {
2659        let items = [0, 1, 2, 3];
2660        let it = convert(items).filter(|x| x % 2 == 0);
2661        test(it, &[0, 2]);
2662    }
2663
2664    #[test]
2665    fn fuse() {
2666        struct Flicker(i32);
2667
2668        impl StreamingIterator for Flicker {
2669            type Item = i32;
2670
2671            fn advance(&mut self) {
2672                self.0 += 1;
2673            }
2674
2675            fn get(&self) -> Option<&i32> {
2676                if self.0 % 4 == 3 {
2677                    None
2678                } else {
2679                    Some(&self.0)
2680                }
2681            }
2682        }
2683
2684        let mut it = Flicker(0).fuse();
2685        assert_eq!(it.get(), None);
2686        it.advance();
2687        assert_eq!(it.get(), Some(&1));
2688        assert_eq!(it.get(), Some(&1));
2689        it.advance();
2690        assert_eq!(it.get(), Some(&2));
2691        assert_eq!(it.get(), Some(&2));
2692        it.advance();
2693        assert_eq!(it.get(), None);
2694        assert_eq!(it.get(), None);
2695        it.advance();
2696        assert_eq!(it.get(), None);
2697        assert_eq!(it.get(), None);
2698    }
2699
2700    #[test]
2701    fn inspect() {
2702        let items = [0, 1, 2, 3];
2703        let mut idx = 0;
2704        let mut items_inspected = [-1, -1, -1, -1];
2705
2706        {
2707            let it = convert(items).inspect(|&i| {
2708                items_inspected[idx] = i;
2709                idx += 1;
2710            });
2711
2712            test(it, &items);
2713        }
2714
2715        assert_eq!(&items_inspected, &items);
2716    }
2717
2718    #[test]
2719    fn map() {
2720        let items = [0, 1];
2721        let it = convert(items.iter().map(|&i| i as usize)).map(|&i| i as i32);
2722        test(it, &items);
2723    }
2724
2725    #[test]
2726    fn map_deref() {
2727        let items = [0, 1];
2728        let it = convert(items.iter().map(|&i| i as usize)).map_deref(|&i| i as i32);
2729        test_deref(it, &items);
2730    }
2731
2732    #[test]
2733    fn map_deref_mut() {
2734        let mut items = [1, 2, 3];
2735        {
2736            let it = convert_mut(&mut items).map_deref_mut(|i| -core::mem::replace(i, 0));
2737            test_deref(it, &[-1, -2, -3]);
2738        }
2739        assert_eq!(items, [0, 0, 0]);
2740    }
2741
2742    #[test]
2743    fn map_ref() {
2744        #[derive(Clone)]
2745        struct Foo(i32);
2746
2747        let items = [Foo(0), Foo(1)];
2748        let it = convert(items).map_ref(|f| &f.0);
2749        test(it, &[0, 1]);
2750    }
2751
2752    #[test]
2753    fn flat_map() {
2754        let items = [[0, 1, 2], [3, 4, 5]];
2755        let it = convert(items).flat_map(|&i| convert(i));
2756
2757        test(it, &[0, 1, 2, 3, 4, 5]);
2758    }
2759
2760    #[test]
2761    fn flatten() {
2762        let mut items = [
2763            convert_ref([].as_ref()),
2764            convert_ref([1].as_ref()),
2765            convert_ref([].as_ref()),
2766            convert_ref([2, 3].as_ref()),
2767            convert_ref([].as_ref()),
2768        ];
2769        let it = convert_mut(&mut items).flatten();
2770
2771        test(it, &[1, 2, 3]);
2772    }
2773
2774    #[test]
2775    fn flatten_unsized() {
2776        type DynI32 = dyn StreamingIterator<Item = i32>;
2777        let mut items = [
2778            &mut once(1) as &mut DynI32,
2779            &mut empty(),
2780            &mut convert(2..=3),
2781        ];
2782        let iters = items.iter_mut().map(|iter| &mut **iter);
2783        let it = convert_mut(iters).flatten();
2784
2785        test(it, &[1, 2, 3]);
2786    }
2787
2788    #[test]
2789    fn nth() {
2790        let items = [0, 1];
2791        let mut it = convert(items);
2792        assert_eq!(it.clone().nth(0), Some(&0));
2793        assert_eq!(it.clone().nth(1), Some(&1));
2794        assert_eq!(it.nth(2), None);
2795    }
2796
2797    #[test]
2798    fn filter_map() {
2799        let items = [0u8, 1, 1, 2, 4];
2800        let it = convert(items).filter_map(|&i| if i % 2 == 0 { Some(i) } else { None });
2801        test(it, &[0, 2, 4])
2802    }
2803
2804    #[test]
2805    fn filter_map_deref() {
2806        let items = [0u8, 1, 1, 2, 4];
2807        let it = convert(items).filter_map_deref(|&i| if i % 2 == 0 { Some(i) } else { None });
2808        test_deref(it, &[0, 2, 4])
2809    }
2810
2811    #[test]
2812    fn find() {
2813        let items = [0, 1];
2814        let mut it = convert(items);
2815        assert_eq!(it.clone().find(|&x| x % 2 == 1), Some(&1));
2816        assert_eq!(it.find(|&x| x % 3 == 2), None);
2817    }
2818
2819    #[test]
2820    #[cfg(feature = "alloc")]
2821    fn owned() {
2822        let items = [0, 1];
2823        let it = convert(items).owned();
2824        assert_eq!(it.collect::<Vec<_>>(), items);
2825    }
2826
2827    #[test]
2828    #[cfg(feature = "alloc")]
2829    fn owned_str() {
2830        let s = "The quick brown fox jumps over the lazy dog";
2831        let words = s.split_whitespace().map(str::to_owned).collect::<Vec<_>>();
2832        let it = convert_ref(s.split_whitespace()).owned();
2833        assert_eq!(it.collect::<Vec<_>>(), words);
2834    }
2835
2836    #[test]
2837    fn position() {
2838        let items = [0, 1];
2839        let mut it = convert(items);
2840        assert_eq!(it.clone().position(|&x| x % 2 == 1), Some(1));
2841        assert_eq!(it.position(|&x| x % 3 == 2), None);
2842    }
2843
2844    #[test]
2845    fn skip() {
2846        let items = [0, 1, 2, 3];
2847        let it = convert(items);
2848        test(it.clone().skip(0), &[0, 1, 2, 3]);
2849        test(it.clone().skip(2), &[2, 3]);
2850        test(it.skip(5), &[]);
2851    }
2852
2853    #[test]
2854    fn skip_while() {
2855        let items = [0, 1, 2, 3];
2856        let it = convert(items);
2857        test(it.clone().skip_while(|&i| i < 0), &[0, 1, 2, 3]);
2858        test(it.clone().skip_while(|&i| i < 2), &[2, 3]);
2859        test(it.skip_while(|&i| i < 5), &[]);
2860    }
2861
2862    #[test]
2863    fn take() {
2864        let items = [0, 1, 2, 3];
2865        let it = convert(items);
2866        test(it.clone().take(0), &[]);
2867        test(it.clone().take(2), &[0, 1]);
2868        test(it.take(5), &[0, 1, 2, 3]);
2869    }
2870
2871    #[test]
2872    fn take_while() {
2873        let items = [0, 1, 2, 3];
2874        let it = convert(items);
2875        test(it.clone().take_while(|&i| i < 0), &[]);
2876        test(it.clone().take_while(|&i| i < 2), &[0, 1]);
2877        test(it.take_while(|&i| i < 5), &[0, 1, 2, 3]);
2878    }
2879
2880    fn _is_object_safe(_: &dyn StreamingIterator<Item = ()>) {}
2881
2882    fn _is_object_safe_mut(_: &dyn StreamingIteratorMut<Item = ()>) {}
2883
2884    #[test]
2885    fn empty_iterator() {
2886        let mut it: Empty<u8> = empty();
2887
2888        assert_eq!(it.next(), None);
2889    }
2890
2891    #[test]
2892    fn is_done_empty() {
2893        let mut empty = empty::<u8>();
2894        empty.advance();
2895        assert!(empty.is_done());
2896    }
2897
2898    #[test]
2899    fn is_done_map() {
2900        let items = [1];
2901        let mut it = convert(items).map_ref::<u16, _>(|_| panic!("only called during get()"));
2902        it.advance();
2903        assert!(!it.is_done());
2904        it.advance();
2905        assert!(it.is_done());
2906    }
2907
2908    #[test]
2909    fn rev() {
2910        let items = [0, 1, 2, 3];
2911        let it = convert(items);
2912        test(it.rev(), &[3, 2, 1, 0]);
2913    }
2914
2915    #[test]
2916    fn fold() {
2917        let items = [0, 1, 2, 3];
2918        let it = convert(items);
2919        assert_eq!(it.fold(0, |acc, i| acc * 10 + i), 123);
2920    }
2921
2922    #[test]
2923    fn for_each() {
2924        let items = [0, 1, 2, 3];
2925        let it = convert(items);
2926        let mut acc = 0;
2927        it.for_each(|i| acc = acc * 10 + i);
2928        assert_eq!(acc, 123);
2929    }
2930
2931    #[test]
2932    fn rfold() {
2933        let items = [0, 1, 2, 3];
2934        let it = convert(items);
2935        assert_eq!(it.rfold(0, |acc, i| acc * 10 + i), 3210);
2936    }
2937
2938    #[test]
2939    fn for_each_rev() {
2940        let items = [0, 1, 2, 3];
2941        let it = convert(items);
2942        let mut acc = 0;
2943        it.rev().for_each(|i| acc = acc * 10 + i);
2944        assert_eq!(acc, 3210);
2945    }
2946
2947    #[test]
2948    fn for_each_mut() {
2949        let mut items = [0, 1, 2, 3];
2950
2951        convert_mut(&mut items).for_each_mut(|i: &mut i32| *i += 10);
2952        assert_eq!(items, [10, 11, 12, 13]);
2953
2954        // Note that filter sees a direct `&T` reference,
2955        // rather than `&&mut T` like `Iterator` would.
2956        convert_mut(&mut items)
2957            .filter(|&i: &i32| i & 1 == 0)
2958            .for_each_mut(|i: &mut i32| *i /= 2);
2959        assert_eq!(items, [5, 11, 6, 13]);
2960    }
2961
2962    #[test]
2963    fn into_streaming_iter() {
2964        let items = [0, 1, 2, 3];
2965        let iter = items.into_streaming_iter();
2966        test(iter, &items);
2967        let iter = (&items).into_streaming_iter_ref();
2968        test(iter, &items);
2969        let mut mut_items = items;
2970        let iter = (&mut mut_items).into_streaming_iter_mut();
2971        test(iter, &items);
2972    }
2973}