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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! Fallible, streaming iteration.
//!
//! `FallibleStreamingIterator` differs from the standard library's `Iterator` trait in two ways:
//! iteration can fail, resulting in an error, and only one element of the iteration is available at
//! any time.
//!
//! While these iterators cannot be used with Rust `for` loops, `while let` loops offer a similar
//! level of ergonomics:
//!
//! ```ignore
//! while let Some(value) = it.next()? {
//!     // use value
//! }
//! ```
#![doc(html_root_url="https://docs.rs/fallible-streaming-iterator/0.1.5")]
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "std")]
extern crate core;

use core::marker::PhantomData;

/// A fallible, streaming iterator.
pub trait FallibleStreamingIterator {
    /// The type being iterated over.
    type Item: ?Sized;

    /// The error type of iteration.
    type Error;

    /// Advances the iterator to the next position.
    ///
    /// Iterators start just before the first item, so this method should be called before `get`
    /// when iterating.
    ///
    /// The behavior of calling this method after `get` has returned `None`, or after this method
    /// has returned an error is unspecified.
    fn advance(&mut self) -> Result<(), Self::Error>;

    /// Returns the current element.
    ///
    /// The behavior of calling this method before any calls to `advance` is unspecified.
    fn get(&self) -> Option<&Self::Item>;

    /// Advances the iterator, returning the next element.
    ///
    /// The default implementation simply calls `advance` followed by `get`.
    #[inline]
    fn next(&mut self) -> Result<Option<&Self::Item>, Self::Error> {
        self.advance()?;
        Ok((*self).get())
    }

    /// Returns bounds on the number of remaining elements in the iterator.
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }

    /// Determines if all elements of the iterator satisfy a predicate.
    #[inline]
    fn all<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        while let Some(e) = self.next()? {
            if !f(e) {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Determines if any elements of the iterator satisfy a predicate.
    #[inline]
    fn any<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        self.all(|e| !f(e)).map(|r| !r)
    }

    /// Borrows an iterator, rather than consuming it.
    ///
    /// This is useful to allow the application of iterator adaptors while still retaining ownership
    /// of the original adaptor.
    #[inline]
    fn by_ref(&mut self) -> &mut Self
        where Self: Sized
    {
        self
    }

    /// Returns the number of remaining elements in the iterator.
    #[inline]
    fn count(mut self) -> Result<usize, Self::Error>
        where Self: Sized
    {
        let mut count = 0;
        while let Some(_) = self.next()? {
            count += 1;
        }
        Ok(count)
    }

    /// Returns an iterator which filters elements by a predicate.
    #[inline]
    fn filter<F>(self, f: F) -> Filter<Self, F>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        Filter {
            it: self,
            f: f,
        }
    }

    /// Returns the first element of the iterator which satisfies a predicate.
    #[inline]
    fn find<F>(&mut self, mut f: F) -> Result<Option<&Self::Item>, Self::Error>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        loop {
            self.advance()?;
            match self.get() {
                Some(v) => {
                    if f(v) {
                        break;
                    }
                }
                None => break,
            }
        }
        Ok((*self).get())
    }

    /// Returns an iterator which is well-behaved at the beginning and end of iteration.
    #[inline]
    fn fuse(self) -> Fuse<Self>
        where Self: Sized
    {
        Fuse {
            it: self,
            state: FuseState::Start,
        }
    }

    /// Returns an iterator which applies a transform to elements.
    #[inline]
    fn map<F, B>(self, f: F) -> Map<Self, F, B>
        where Self: Sized,
              F: FnMut(&Self::Item) -> B
    {
        Map {
            it: self,
            f: f,
            value: None,
        }
    }

    /// Returns an iterator which applies a transform to elements.
    ///
    /// Unlike `map`, the the closure provided to this method returns a reference into the original
    /// value.
    #[inline]
    fn map_ref<F, B: ?Sized>(self, f: F) -> MapRef<Self, F>
        where Self: Sized,
              F: Fn(&Self::Item) -> &B
    {
        MapRef {
            it: self,
            f: f,
        }
    }

    /// Returns an iterator that applies a transform to errors.
    #[inline]
    fn map_err<F, B>(self, f: F) -> MapErr<Self, F>
        where Self: Sized,
              F: Fn(Self::Error) -> B
    {
        MapErr {
            it: self,
            f: f,
        }
    }

    /// Returns the `nth` element of the iterator.
    #[inline]
    fn nth(&mut self, n: usize) -> Result<Option<&Self::Item>, Self::Error> {
        for _ in 0..n {
            self.advance()?;
            if let None = self.get() {
                return Ok(None);
            }
        }
        self.next()
    }

    /// Returns the position of the first element matching a predicate.
    #[inline]
    fn position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        let mut pos = 0;
        while let Some(v) = self.next()? {
            if f(v) {
                return Ok(Some(pos));
            }
            pos += 1;
        }
        Ok(None)
    }

    /// Returns an iterator which skips the first `n` elements.
    #[inline]
    fn skip(self, n: usize) -> Skip<Self>
        where Self: Sized
    {
        Skip {
            it: self,
            n: n,
        }
    }

    /// Returns an iterator which skips the first sequence of elements matching a predicate.
    #[inline]
    fn skip_while<F>(self, f: F) -> SkipWhile<Self, F>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        SkipWhile {
            it: self,
            f: f,
            done: false,
        }
    }

    /// Returns an iterator which only returns the first `n` elements.
    #[inline]
    fn take(self, n: usize) -> Take<Self>
        where Self: Sized
    {
        Take {
            it: self,
            n: n,
            done: false,
        }
    }

    /// Returns an iterator which only returns the first sequence of elements matching a predicate.
    #[inline]
    fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
        where Self: Sized,
              F: FnMut(&Self::Item) -> bool
    {
        TakeWhile {
            it: self,
            f: f,
            done: false,
        }
    }
}

impl<'a, I: ?Sized> FallibleStreamingIterator for &'a mut I
    where I: FallibleStreamingIterator
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        (**self).advance()
    }

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

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

    #[inline]
    fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
        (**self).next()
    }
}

#[cfg(feature = "std")]
impl<I: ?Sized> FallibleStreamingIterator for Box<I>
    where I: FallibleStreamingIterator
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        (**self).advance()
    }

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

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

    #[inline]
    fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
        (**self).next()
    }
}

/// Converts a normal `Iterator` over `Results` of references into a
/// `FallibleStreamingIterator`.
pub fn convert<'a, I, T, E>(it: I) -> Convert<'a, I, T>
    where I: Iterator<Item = Result<&'a T, E>>
{
    Convert {
        it: it,
        item: None,
    }
}

/// An iterator which wraps a normal `Iterator`.
pub struct Convert<'a, I, T: 'a> {
    it: I,
    item: Option<&'a T>,
}

impl<'a, I, T, E> FallibleStreamingIterator for Convert<'a, I, T>
    where I: Iterator<Item = Result<&'a T, E>>
{
    type Item = T;
    type Error = E;

    #[inline]
    fn advance(&mut self) -> Result<(), E> {
        self.item = match self.it.next() {
            Some(Ok(v)) => Some(v),
            Some(Err(e)) => return Err(e),
            None => None,
        };
        Ok(())
    }

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

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

/// Returns an iterator over no items.
pub fn empty<T, E>() -> Empty<T, E> {
    Empty(PhantomData)
}

/// An iterator over no items.
pub struct Empty<T, E>(PhantomData<(T, E)>);

impl<T, E> FallibleStreamingIterator for Empty<T, E> {
    type Item = T;
    type Error = E;

    #[inline]
    fn advance(&mut self) -> Result<(), E> {
        Ok(())
    }

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

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

/// An iterator which filters elements with a predicate.
pub struct Filter<I, F> {
    it: I,
    f: F,
}

impl<I, F> FallibleStreamingIterator for Filter<I, F>
    where I: FallibleStreamingIterator,
          F: FnMut(&I::Item) -> bool
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        while let Some(i) = self.it.next()? {
            if (self.f)(i) {
                break;
            }
        }
        Ok(())
    }

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

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

#[derive(Copy, Clone)]
enum FuseState {
    Start,
    Middle,
    End,
}

/// An iterator which is well-behaved at the beginning and end of iteration.
pub struct Fuse<I> {
    it: I,
    state: FuseState,
}

impl<I> FallibleStreamingIterator for Fuse<I>
    where I: FallibleStreamingIterator
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        match self.state {
            FuseState::Start => {
                match self.it.next() {
                    Ok(Some(_)) => self.state = FuseState::Middle,
                    Ok(None) => self.state = FuseState::End,
                    Err(e) => {
                        self.state = FuseState::End;
                        return Err(e)
                    }
                };
            }
            FuseState::Middle => {
                match self.it.next() {
                    Ok(Some(_)) => {}
                    Ok(None) => self.state = FuseState::End,
                    Err(e) => {
                        self.state = FuseState::End;
                        return Err(e)
                    }
                }
            }
            FuseState::End => {},
        }
        Ok(())
    }

    #[inline]
    fn get(&self) -> Option<&I::Item> {
        match self.state {
            FuseState::Middle => self.it.get(),
            FuseState::Start | FuseState::End => None,
        }
    }

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

    #[inline]
    fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
        match self.state {
            FuseState::Start => {
                match self.it.next() {
                    Ok(Some(v)) => {
                        self.state = FuseState::Middle;
                        Ok(Some(v))
                    }
                    Ok(None) => {
                        self.state = FuseState::End;
                        Ok(None)
                    }
                    Err(e) => {
                        self.state = FuseState::End;
                        Err(e)
                    }
                }
            }
            FuseState::Middle => {
                match self.it.next() {
                    Ok(Some(v)) => Ok(Some(v)),
                    Ok(None) => {
                        self.state = FuseState::End;
                        Ok(None)
                    }
                    Err(e) => {
                        self.state = FuseState::End;
                        Err(e)
                    }
                }
            }
            FuseState::End => Ok(None)
        }
    }
}

/// An iterator which applies a transform to elements.
pub struct Map<I, F, B>
{
    it: I,
    f: F,
    value: Option<B>,
}

impl<I, F, B> FallibleStreamingIterator for Map<I, F, B>
    where I: FallibleStreamingIterator,
          F: FnMut(&I::Item) -> B
{
    type Item = B;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        self.value = self.it.next()?.map(&mut self.f);
        Ok(())
    }

    #[inline]
    fn get(&self) -> Option<&B> {
        self.value.as_ref()
    }

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

/// An iterator which applies a transform to elements.
pub struct MapRef<I, F> {
    it: I,
    f: F,
}

impl<I, F, B: ?Sized> FallibleStreamingIterator for MapRef<I, F>
    where I: FallibleStreamingIterator,
          F: Fn(&I::Item) -> &B,
{
    type Item = B;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        self.it.advance()
    }

    #[inline]
    fn get(&self) -> Option<&B> {
        self.it.get().map(&self.f)
    }

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

/// An iterator which applies a transform to errors.
pub struct MapErr<I, F> {
    it: I,
    f: F,
}

impl<I, F, B> FallibleStreamingIterator for MapErr<I, F>
    where I: FallibleStreamingIterator,
          F: Fn(I::Error) -> B
{
    type Item = I::Item;
    type Error = B;

    #[inline]
    fn advance(&mut self) -> Result<(), B> {
        self.it.advance().map_err(&mut self.f)
    }

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

    #[inline]
    fn next(&mut self) -> Result<Option<&I::Item>, B> {
        self.it.next().map_err(&mut self.f)
    }

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

/// An iterator which skips a number of initial elements.
pub struct Skip<I> {
    it: I,
    n: usize,
}

impl<I> FallibleStreamingIterator for Skip<I>
    where I: FallibleStreamingIterator
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        for _ in 0..self.n {
            if let None = self.it.next()? {
                return Ok(());
            }
        }
        self.n = 0;
        self.advance()
    }

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

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let hint = self.it.size_hint();
        (hint.0.saturating_sub(self.n), hint.1.map(|h| h.saturating_sub(self.n)))
    }
}

/// An iterator which skips initial elements matching a predicate.
pub struct SkipWhile<I, F> {
    it: I,
    f: F,
    done: bool,
}

impl<I, F> FallibleStreamingIterator for SkipWhile<I, F>
    where I: FallibleStreamingIterator,
          F: FnMut(&I::Item) -> bool
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        if !self.done {
            self.done = true;
            let f = &mut self.f;
            self.it.find(|i| !f(i)).map(|_| ())
        } else {
            self.it.advance()
        }
    }

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

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let hint = self.it.size_hint();
        if self.done {
            hint
        } else {
            (0, hint.1)
        }
    }
}

/// An iterator which only returns a number of initial elements.
pub struct Take<I> {
    it: I,
    n: usize,
    done: bool,
}

impl<I> FallibleStreamingIterator for Take<I>
    where I: FallibleStreamingIterator
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        if self.n != 0 {
            self.it.advance()?;
            self.n -= 1;
        } else {
            self.done = true;
        }
        Ok(())
    }

    #[inline]
    fn get(&self) -> Option<&I::Item> {
        if self.done { None } else { self.it.get() }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.done {
            (0, Some(0))
        } else {
            let hint = self.it.size_hint();
            (hint.0.saturating_sub(self.n), hint.1.map(|h| h.saturating_sub(self.n)))
        }
    }
}

/// An iterator which only returns initial elements matching a predicate.
pub struct TakeWhile<I, F> {
    it: I,
    f: F,
    done: bool,
}

impl<I, F> FallibleStreamingIterator for TakeWhile<I, F>
    where I: FallibleStreamingIterator,
          F: FnMut(&I::Item) -> bool
{
    type Item = I::Item;
    type Error = I::Error;

    #[inline]
    fn advance(&mut self) -> Result<(), I::Error> {
        if let Some(v) = self.it.next()? {
            if !(self.f)(v) {
                self.done = true;
            }
        }
        Ok(())
    }

    #[inline]
    fn get(&self) -> Option<&I::Item> {
        if self.done { None } else { self.it.get() }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.done {
            (0, Some(0))
        } else {
            (0, self.it.size_hint().1)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn _is_object_safe(_: &FallibleStreamingIterator<Item = (), Error = ()>) {}
}