1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
use super::{DoubleEndedStreamingIterator, StreamingIterator};
use super::{DoubleEndedStreamingIteratorMut, StreamingIteratorMut};
use core::marker::PhantomData;
use core::usize;

/// Turns a normal, non-streaming iterator into a streaming iterator.
///
/// ```
/// # use streaming_iterator::{StreamingIterator, convert};
/// let scores = vec![100, 50, 80];
/// let mut streaming_iter = convert(scores);
/// while let Some(score) = streaming_iter.next() {
///     println!("The score is: {}", score);
/// }
/// ```
#[inline]
pub fn convert<I>(it: I) -> Convert<I::IntoIter>
where
    I: IntoIterator,
{
    Convert {
        it: it.into_iter(),
        item: None,
    }
}

/// Turns an iterator of references into a streaming iterator.
///
/// ```
/// # use streaming_iterator::{StreamingIterator, convert_ref};
/// let scores = vec![100, 50, 80];
/// let mut streaming_iter = convert_ref(&scores);
/// while let Some(score) = streaming_iter.next() {
///     println!("The score is: {}", score);
/// }
/// ```
#[inline]
pub fn convert_ref<'a, I, T: ?Sized>(iterator: I) -> ConvertRef<'a, I::IntoIter, T>
where
    I: IntoIterator<Item = &'a T>,
{
    ConvertRef {
        it: iterator.into_iter(),
        item: None,
    }
}

/// Turns an iterator of mutable references into a streaming iterator.
///
/// ```
/// # use streaming_iterator::{StreamingIteratorMut, convert_mut};
/// let mut scores = vec![Some(100), None, Some(80)];
/// {
///     let mut streaming_iter = convert_mut(&mut scores);
///     while let Some(opt_score) = streaming_iter.next_mut() {
///         if let Some(score) = opt_score.take() {
///             println!("The score is: {}", score);
///         }
///         // else already reported
///     }
/// }
/// assert_eq!(scores, [None, None, None]);
/// ```
#[inline]
pub fn convert_mut<'a, I, T: ?Sized>(iterator: I) -> ConvertMut<'a, I::IntoIter, T>
where
    I: IntoIterator<Item = &'a mut T>,
{
    ConvertMut {
        it: iterator.into_iter(),
        item: None,
    }
}

/// Creates an empty iterator.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut streaming_iter = streaming_iterator::empty::<i32>();
/// assert_eq!(streaming_iter.next(), None);
/// ```
#[inline]
pub fn empty<T>() -> Empty<T> {
    Empty {
        phantom: PhantomData,
    }
}

/// Creates an iterator that returns items from a function call.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut count = 0;
/// let mut streaming_iter = streaming_iterator::from_fn(|| {
///     count += 1;
///     if count < 4 { Some(count) } else { None }
/// });
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&2));
/// assert_eq!(streaming_iter.next(), Some(&3));
/// assert_eq!(streaming_iter.next(), None);
/// ```
#[inline]
pub fn from_fn<T, F: FnMut() -> Option<T>>(gen: F) -> FromFn<T, F> {
    FromFn { gen, item: None }
}

/// Creates an iterator that returns exactly one item.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut streaming_iter = streaming_iterator::once(1);
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), None);
/// ```
#[inline]
pub fn once<T>(item: T) -> Once<T> {
    Once {
        first: true,
        item: Some(item),
    }
}

/// Creates an iterator that returns exactly one item from a function call.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// #[derive(Debug, PartialEq)]
/// struct Expensive(i32);
/// let mut streaming_iter = streaming_iterator::once_with(|| Expensive(1));
/// assert_eq!(streaming_iter.next(), Some(&Expensive(1)));
/// assert_eq!(streaming_iter.next(), None);
/// ```
#[inline]
pub fn once_with<T, F: FnOnce() -> T>(gen: F) -> OnceWith<T, F> {
    OnceWith {
        gen: Some(gen),
        item: None,
    }
}

/// Creates an iterator that returns an item endlessly.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut streaming_iter = streaming_iterator::repeat(1);
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&1));
/// // ...
/// ```
#[inline]
pub fn repeat<T>(item: T) -> Repeat<T> {
    Repeat { item }
}

/// Creates an iterator that endlessly returns items from a function call.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut count = 0;
/// let mut streaming_iter = streaming_iterator::repeat_with(|| {
///     count += 1;
///     count
/// });
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&2));
/// assert_eq!(streaming_iter.next(), Some(&3));
/// assert_eq!(streaming_iter.next(), Some(&4));
/// assert_eq!(streaming_iter.next(), Some(&5));
/// // ...
/// ```
#[inline]
pub fn repeat_with<T, F: FnMut() -> T>(gen: F) -> RepeatWith<T, F> {
    RepeatWith { gen, item: None }
}

/// Creates an iterator where each successive item is computed from the preceding one.
///
/// ```
/// # use streaming_iterator::StreamingIterator;
/// let mut streaming_iter = streaming_iterator::successors(
///     Some(1),
///     |count| if count < 3 { Some(count + 1) } else { None },
/// );
/// assert_eq!(streaming_iter.next(), Some(&1));
/// assert_eq!(streaming_iter.next(), Some(&2));
/// assert_eq!(streaming_iter.next(), Some(&3));
/// assert_eq!(streaming_iter.next(), None);
/// ```
#[inline]
pub fn successors<T, F: FnMut(T) -> Option<T>>(first: Option<T>, succ: F) -> Successors<T, F> {
    Successors {
        first: true,
        item: first,
        succ,
    }
}

/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
#[derive(Clone, Debug)]
pub struct Convert<I>
where
    I: Iterator,
{
    it: I,
    item: Option<I::Item>,
}

impl<I> StreamingIterator for Convert<I>
where
    I: Iterator,
{
    type Item = I::Item;

    #[inline]
    fn advance(&mut self) {
        self.item = self.it.next();
    }

    #[inline]
    fn get(&self) -> Option<&I::Item> {
        self.item.as_ref()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }

    #[inline]
    fn count(self) -> usize {
        self.it.count()
    }

    #[inline]
    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.fold(init, move |acc, item| f(acc, &item))
    }
}

impl<I> DoubleEndedStreamingIterator for Convert<I>
where
    I: DoubleEndedIterator,
{
    #[inline]
    fn advance_back(&mut self) {
        self.item = self.it.next_back();
    }

    #[inline]
    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.rfold(init, move |acc, item| f(acc, &item))
    }
}

impl<I> StreamingIteratorMut for Convert<I>
where
    I: Iterator,
{
    #[inline]
    fn get_mut(&mut self) -> Option<&mut I::Item> {
        self.item.as_mut()
    }

    #[inline]
    fn fold_mut<B, F>(self, init: B, mut f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, &mut Self::Item) -> B,
    {
        self.it.fold(init, move |acc, mut item| f(acc, &mut item))
    }
}

impl<I> DoubleEndedStreamingIteratorMut for Convert<I>
where
    I: DoubleEndedIterator,
{
    #[inline]
    fn rfold_mut<B, F>(self, init: B, mut f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, &mut Self::Item) -> B,
    {
        self.it.rfold(init, move |acc, mut item| f(acc, &mut item))
    }
}

/// A streaming iterator which yields elements from an iterator of references.
#[derive(Clone, Debug)]
pub struct ConvertRef<'a, I, T: ?Sized>
where
    I: Iterator<Item = &'a T>,
{
    it: I,
    item: Option<&'a T>,
}

impl<'a, I, T: ?Sized> StreamingIterator for ConvertRef<'a, I, T>
where
    I: Iterator<Item = &'a T>,
{
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        self.item = self.it.next();
    }

    #[inline]
    fn get(&self) -> Option<&T> {
        self.item
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }

    #[inline]
    fn count(self) -> usize {
        self.it.count()
    }

    #[inline]
    fn fold<Acc, Fold>(self, init: Acc, f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.fold(init, f)
    }
}

impl<'a, I, T: ?Sized> DoubleEndedStreamingIterator for ConvertRef<'a, I, T>
where
    I: DoubleEndedIterator<Item = &'a T>,
{
    #[inline]
    fn advance_back(&mut self) {
        self.item = self.it.next_back();
    }

    #[inline]
    fn rfold<Acc, Fold>(self, init: Acc, f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.rfold(init, f)
    }
}

/// A streaming iterator which yields elements from an iterator of mutable references.
#[derive(Debug)]
pub struct ConvertMut<'a, I, T: ?Sized>
where
    I: Iterator<Item = &'a mut T>,
{
    it: I,
    item: Option<&'a mut T>,
}

impl<'a, I, T: ?Sized> StreamingIterator for ConvertMut<'a, I, T>
where
    I: Iterator<Item = &'a mut T>,
{
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        self.item = self.it.next();
    }

    #[inline]
    fn get(&self) -> Option<&T> {
        match self.item {
            Some(&mut ref item) => Some(item),
            None => None,
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }

    #[inline]
    fn count(self) -> usize {
        self.it.count()
    }

    #[inline]
    fn fold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.fold(init, move |acc, item| f(acc, item))
    }
}

impl<'a, I, T: ?Sized> DoubleEndedStreamingIterator for ConvertMut<'a, I, T>
where
    I: DoubleEndedIterator<Item = &'a mut T>,
{
    #[inline]
    fn advance_back(&mut self) {
        self.item = self.it.next_back();
    }

    #[inline]
    fn rfold<Acc, Fold>(self, init: Acc, mut f: Fold) -> Acc
    where
        Self: Sized,
        Fold: FnMut(Acc, &Self::Item) -> Acc,
    {
        self.it.rfold(init, move |acc, item| f(acc, item))
    }
}

impl<'a, I, T: ?Sized> StreamingIteratorMut for ConvertMut<'a, I, T>
where
    I: Iterator<Item = &'a mut T>,
{
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        match self.item {
            Some(&mut ref mut item) => Some(item),
            None => None,
        }
    }

    #[inline]
    fn fold_mut<B, F>(self, init: B, f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, &mut Self::Item) -> B,
    {
        self.it.fold(init, f)
    }
}

impl<'a, I, T: ?Sized> DoubleEndedStreamingIteratorMut for ConvertMut<'a, I, T>
where
    I: DoubleEndedIterator<Item = &'a mut T>,
{
    #[inline]
    fn rfold_mut<B, F>(self, init: B, f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, &mut Self::Item) -> B,
    {
        self.it.rfold(init, f)
    }
}

/// A simple iterator that returns nothing.
#[derive(Clone, Debug)]
pub struct Empty<T> {
    phantom: PhantomData<T>,
}

impl<T> StreamingIterator for Empty<T> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {}

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(0))
    }
}

impl<T> DoubleEndedStreamingIterator for Empty<T> {
    #[inline]
    fn advance_back(&mut self) {}
}

impl<T> StreamingIteratorMut for Empty<T> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        None
    }
}

impl<T> DoubleEndedStreamingIteratorMut for Empty<T> {}

/// A simple iterator that returns items from a function call.
#[derive(Clone, Debug)]
pub struct FromFn<T, F> {
    gen: F,
    item: Option<T>,
}

impl<T, F: FnMut() -> Option<T>> StreamingIterator for FromFn<T, F> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        self.item = (self.gen)();
    }

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        self.item.as_ref()
    }
}

impl<T, F: FnMut() -> Option<T>> StreamingIteratorMut for FromFn<T, F> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.item.as_mut()
    }
}

/// A simple iterator that returns exactly one item.
#[derive(Clone, Debug)]
pub struct Once<T> {
    first: bool,
    item: Option<T>,
}

impl<T> StreamingIterator for Once<T> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        if self.first {
            self.first = false;
        } else {
            self.item = None;
        }
    }

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        self.item.as_ref()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.first as usize;
        (len, Some(len))
    }
}

impl<T> DoubleEndedStreamingIterator for Once<T> {
    #[inline]
    fn advance_back(&mut self) {
        self.advance();
    }
}

impl<T> StreamingIteratorMut for Once<T> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.item.as_mut()
    }
}

impl<T> DoubleEndedStreamingIteratorMut for Once<T> {}

/// A simple iterator that returns exactly one item from a function call.
#[derive(Clone, Debug)]
pub struct OnceWith<T, F> {
    gen: Option<F>,
    item: Option<T>,
}

impl<T, F: FnOnce() -> T> StreamingIterator for OnceWith<T, F> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        self.item = self.gen.take().map(|gen| gen());
    }

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        self.item.as_ref()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.gen.is_some() as usize;
        (len, Some(len))
    }
}

impl<T, F: FnOnce() -> T> DoubleEndedStreamingIterator for OnceWith<T, F> {
    #[inline]
    fn advance_back(&mut self) {
        self.advance();
    }
}

impl<T, F: FnOnce() -> T> StreamingIteratorMut for OnceWith<T, F> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.item.as_mut()
    }
}

impl<T, F: FnOnce() -> T> DoubleEndedStreamingIteratorMut for OnceWith<T, F> {}

/// A simple iterator that repeats an item endlessly.
///
/// Note: if the item is modified through `StreamingIteratorMut`,
/// this will continue be reflected in further iterations!
#[derive(Clone, Debug)]
pub struct Repeat<T> {
    item: T,
}

impl<T> StreamingIterator for Repeat<T> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {}

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        Some(&self.item)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (usize::MAX, None)
    }
}

impl<T> DoubleEndedStreamingIterator for Repeat<T> {
    #[inline]
    fn advance_back(&mut self) {}
}

impl<T> StreamingIteratorMut for Repeat<T> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        Some(&mut self.item)
    }
}

impl<T> DoubleEndedStreamingIteratorMut for Repeat<T> {}

/// A simple iterator that endlessly returns items from a function call.
#[derive(Clone, Debug)]
pub struct RepeatWith<T, F> {
    gen: F,
    item: Option<T>,
}

impl<T, F: FnMut() -> T> StreamingIterator for RepeatWith<T, F> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        self.item = Some((self.gen)());
    }

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        self.item.as_ref()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (usize::MAX, None)
    }
}

impl<T, F: FnMut() -> T> StreamingIteratorMut for RepeatWith<T, F> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.item.as_mut()
    }
}

/// An iterator where each successive item is computed from the preceding one.
///
/// Note: if an item is modified through `StreamingIteratorMut`, those changes
/// will be visible to the successor function when the iterator is advanced.
#[derive(Clone, Debug)]
pub struct Successors<T, F> {
    first: bool,
    item: Option<T>,
    succ: F,
}

impl<T, F: FnMut(T) -> Option<T>> StreamingIterator for Successors<T, F> {
    type Item = T;

    #[inline]
    fn advance(&mut self) {
        if self.first {
            self.first = false;
        } else if let Some(item) = self.item.take() {
            self.item = (self.succ)(item);
        }
    }

    #[inline]
    fn get(&self) -> Option<&Self::Item> {
        self.item.as_ref()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match (self.first, &self.item) {
            // We have a first item and unknown successors
            (true, &Some(_)) => (1, None),
            // We only have unknown successors
            (false, &Some(_)) => (0, None),
            // We have nothing.
            (_, &None) => (0, Some(0)),
        }
    }
}

impl<T, F: FnMut(T) -> Option<T>> StreamingIteratorMut for Successors<T, F> {
    #[inline]
    fn get_mut(&mut self) -> Option<&mut Self::Item> {
        self.item.as_mut()
    }
}