-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
lib.rs
2330 lines (2083 loc) · 58.9 KB
/
lib.rs
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! "Fallible" iterators.
//!
//! The iterator APIs in the Rust standard library do not support iteration
//! that can fail in a first class manner. These iterators are typically modeled
//! as iterating over `Result<T, E>` values; for example, the `Lines` iterator
//! returns `io::Result<String>`s. When simply iterating over these types, the
//! value being iterated over must be unwrapped in some way before it can be
//! used:
//!
//! ```ignore
//! for line in reader.lines() {
//! let line = line?;
//! // work with line
//! }
//! ```
//!
//! In addition, many of the additional methods on the `Iterator` trait will
//! not behave properly in the presence of errors when working with these kinds
//! of iterators. For example, if one wanted to count the number of lines of
//! text in a `Read`er, this might be a way to go about it:
//!
//! ```ignore
//! let count = reader.lines().count();
//! ```
//!
//! This will return the proper value when the reader operates successfully, but
//! if it encounters an IO error, the result will either be slightly higher than
//! expected if the error is transient, or it may run forever if the error is
//! returned repeatedly!
//!
//! In contrast, a fallible iterator is built around the concept that a call to
//! `next` can fail. The trait has an additional `Error` associated type in
//! addition to the `Item` type, and `next` returns `Result<Option<Self::Item>,
//! Self::Error>` rather than `Option<Self::Item>`. Methods like `count` return
//! `Result`s as well.
//!
//! This does mean that fallible iterators are incompatible with Rust's `for`
//! loop syntax, but `while let` loops offer a similar level of ergonomics:
//!
//! ```ignore
//! while let Some(item) = iter.next()? {
//! // work with item
//! }
//! ```
//!
//! ## Fallible closure arguments
//!
//! Like `Iterator`, many `FallibleIterator` methods take closures as arguments.
//! These use the same signatures as their `Iterator` counterparts, except that
//! `FallibleIterator` expects the closures to be fallible: they return
//! `Result<T, Self::Error>` instead of simply `T`.
//!
//! For example, the standard library's `Iterator::filter` adapter method
//! filters the underlying iterator according to a predicate provided by the
//! user, whose return type is `bool`. In `FallibleIterator::filter`, however,
//! the predicate returns `Result<bool, Self::Error>`:
//!
//! ```
//! # use std::error::Error;
//! # use std::str::FromStr;
//! # use fallible_iterator::{convert, FallibleIterator};
//! let numbers = convert("100\n200\nfern\n400".lines().map(Ok::<&str, Box<Error>>));
//! let big_numbers = numbers.filter(|n| Ok(u64::from_str(n)? > 100));
//! assert!(big_numbers.count().is_err());
//! ```
#![doc(html_root_url = "https://docs.rs/fallible-iterator/0.1")]
#![warn(missing_docs)]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![no_std]
use core::cmp::{self, Ordering};
use core::iter;
#[cfg(all(feature = "alloc", not(feature = "std")))]
#[cfg_attr(test, macro_use)]
extern crate alloc;
#[cfg(all(feature = "alloc", not(feature = "std")))]
mod imports {
pub use alloc::boxed::Box;
pub use alloc::collections::btree_map::BTreeMap;
pub use alloc::collections::btree_set::BTreeSet;
pub use alloc::vec::Vec;
}
#[cfg(feature = "std")]
#[cfg_attr(test, macro_use)]
extern crate std;
#[cfg(feature = "std")]
mod imports {
pub use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
pub use std::hash::{BuildHasher, Hash};
pub use std::prelude::v1::*;
}
#[cfg(any(feature = "std", feature = "alloc"))]
use crate::imports::*;
#[cfg(any(feature = "std", feature = "alloc"))]
#[cfg(test)]
mod test;
/// An `Iterator`-like trait that allows for calculation of items to fail.
pub trait FallibleIterator {
/// The type being iterated over.
type Item;
/// The error type.
type Error;
/// Advances the iterator and returns the next value.
///
/// Returns `Ok(None)` when iteration is finished.
///
/// The behavior of calling this method after a previous call has returned
/// `Ok(None)` or `Err` is implemenetation defined.
fn next(&mut self) -> Result<Option<Self::Item>, Self::Error>;
/// Returns bounds on the remaining length of the iterator.
///
/// Specifically, the first half of the returned tuple is a lower bound and
/// the second half is an upper bound.
///
/// For the upper bound, `None` indicates that the upper bound is either
/// unknown or larger than can be represented as a `usize`.
///
/// Both bounds assume that all remaining calls to `next` succeed. That is,
/// `next` could return an `Err` in fewer calls than specified by the lower
/// bound.
///
/// The default implementation returns `(0, None)`, which is correct for
/// any iterator.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
/// Consumes the iterator, returning the number of remaining items.
#[inline]
fn count(self) -> Result<usize, Self::Error>
where
Self: Sized,
{
self.fold(0, |n, _| Ok(n + 1))
}
/// Returns the last element of the iterator.
#[inline]
fn last(self) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
{
self.fold(None, |_, v| Ok(Some(v)))
}
/// Returns the `n`th element of the iterator.
#[inline]
fn nth(&mut self, mut n: usize) -> Result<Option<Self::Item>, Self::Error> {
while let Some(e) = self.next()? {
if n == 0 {
return Ok(Some(e));
}
n -= 1;
}
Ok(None)
}
/// Returns an iterator starting at the same point, but stepping by the given amount at each iteration.
///
/// # Panics
///
/// Panics if `step` is 0.
#[inline]
fn step_by(self, step: usize) -> StepBy<Self>
where
Self: Sized,
{
assert!(step != 0);
StepBy {
it: self,
step: step - 1,
first_take: true,
}
}
/// Returns an iterator which yields the elements of this iterator followed
/// by another.
#[inline]
fn chain<I>(self, it: I) -> Chain<Self, I>
where
I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>,
Self: Sized,
{
Chain {
front: self,
back: it,
state: ChainState::Both,
}
}
/// Returns an iterator that yields pairs of this iterator's and another
/// iterator's values.
#[inline]
fn zip<I>(self, o: I) -> Zip<Self, I::IntoFallibleIter>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
{
Zip(self, o.into_fallible_iter())
}
/// Returns an iterator which applies a fallible transform to the elements
/// of the underlying iterator.
#[inline]
fn map<F, B>(self, f: F) -> Map<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<B, Self::Error>,
{
Map { it: self, f: f }
}
/// Calls a fallible closure on each element of an iterator.
#[inline]
fn for_each<F>(self, mut f: F) -> Result<(), Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<(), Self::Error>,
{
self.fold((), move |(), item| f(item))
}
/// Returns an iterator which uses a predicate to determine which values
/// should be yielded. The predicate may fail; such failures are passed to
/// the caller.
#[inline]
fn filter<F>(self, f: F) -> Filter<Self, F>
where
Self: Sized,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
Filter { it: self, f: f }
}
/// Returns an iterator which both filters and maps. The closure may fail;
/// such failures are passed along to the consumer.
#[inline]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
{
FilterMap { it: self, f: f }
}
/// Returns an iterator which yields the current iteration count as well
/// as the value.
#[inline]
fn enumerate(self) -> Enumerate<Self>
where
Self: Sized,
{
Enumerate { it: self, n: 0 }
}
/// Returns an iterator that can peek at the next element without consuming
/// it.
#[inline]
fn peekable(self) -> Peekable<Self>
where
Self: Sized,
{
Peekable {
it: self,
next: None,
}
}
/// Returns an iterator that skips elements based on a predicate.
#[inline]
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
SkipWhile {
it: self,
flag: false,
predicate,
}
}
/// Returns an iterator that yields elements based on a predicate.
#[inline]
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where
Self: Sized,
P: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
TakeWhile {
it: self,
flag: false,
predicate,
}
}
/// Returns an iterator which skips the first `n` values of this iterator.
#[inline]
fn skip(self, n: usize) -> Skip<Self>
where
Self: Sized,
{
Skip { it: self, n }
}
/// Returns an iterator that yields only the first `n` values of this
/// iterator.
#[inline]
fn take(self, n: usize) -> Take<Self>
where
Self: Sized,
{
Take {
it: self,
remaining: n,
}
}
/// Returns an iterator which applies a stateful map to values of this
/// iterator.
#[inline]
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where
Self: Sized,
F: FnMut(&mut St, Self::Item) -> Result<Option<B>, Self::Error>,
{
Scan {
it: self,
f,
state: initial_state,
}
}
/// Returns an iterator which maps this iterator's elements to iterators, yielding those iterators' values.
#[inline]
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where
Self: Sized,
U: IntoFallibleIterator<Error = Self::Error>,
F: FnMut(Self::Item) -> Result<U, Self::Error>,
{
FlatMap {
it: self.map(f),
cur: None,
}
}
/// Returns an iterator which flattens an iterator of iterators, yielding those iterators' values.
#[inline]
fn flatten(self) -> Flatten<Self>
where
Self: Sized,
Self::Item: IntoFallibleIterator<Error = Self::Error>,
{
Flatten {
it: self,
cur: None,
}
}
/// Returns an iterator which yields this iterator's elements and ends after
/// the first `Ok(None)`.
///
/// The behavior of calling `next` after it has previously returned
/// `Ok(None)` is normally unspecified. The iterator returned by this method
/// guarantees that `Ok(None)` will always be returned.
#[inline]
fn fuse(self) -> Fuse<Self>
where
Self: Sized,
{
Fuse {
it: self,
done: false,
}
}
/// Returns an iterator which passes each element to a closure before returning it.
#[inline]
fn inspect<F>(self, f: F) -> Inspect<Self, F>
where
Self: Sized,
F: FnMut(&Self::Item) -> Result<(), Self::Error>,
{
Inspect { it: self, f }
}
/// Borrow an iterator rather than consuming it.
///
/// This is useful to allow the use of iterator adaptors that would
/// otherwise consume the value.
#[inline]
fn by_ref(&mut self) -> &mut Self
where
Self: Sized,
{
self
}
/// Transforms the iterator into a collection.
///
/// An `Err` will be returned if any invocation of `next` returns `Err`.
#[inline]
fn collect<T>(self) -> Result<T, Self::Error>
where
T: FromFallibleIterator<Self::Item>,
Self: Sized,
{
T::from_fallible_iterator(self)
}
/// Transforms the iterator into two collections, partitioning elements by a closure.
#[inline]
fn partition<B, F>(self, mut f: F) -> Result<(B, B), Self::Error>
where
Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
let mut a = B::default();
let mut b = B::default();
self.for_each(|i| {
if f(&i)? {
a.extend(Some(i));
} else {
b.extend(Some(i));
}
Ok(())
})?;
Ok((a, b))
}
/// Applies a function over the elements of the iterator, producing a single
/// final value.
#[inline]
fn fold<B, F>(mut self, mut init: B, mut f: F) -> Result<B, Self::Error>
where
Self: Sized,
F: FnMut(B, Self::Item) -> Result<B, Self::Error>,
{
while let Some(v) = self.next()? {
init = f(init, v)?;
}
Ok(init)
}
/// Determines if all elements of this iterator match a predicate.
#[inline]
fn all<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{
while let Some(v) = self.next()? {
if !f(v)? {
return Ok(false);
}
}
Ok(true)
}
/// Determines if any element of this iterator matches a predicate.
#[inline]
fn any<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{
while let Some(v) = self.next()? {
if f(v)? {
return Ok(true);
}
}
Ok(false)
}
/// Returns the first element of the iterator that matches a predicate.
#[inline]
fn find<F>(&mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
F: FnMut(&Self::Item) -> Result<bool, Self::Error>,
{
while let Some(v) = self.next()? {
if f(&v)? {
return Ok(Some(v));
}
}
Ok(None)
}
/// Applies a function to the elements of the iterator, returning the first non-`None` result.
#[inline]
fn find_map<B, F>(&mut self, f: F) -> Result<Option<B>, Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
{
self.filter_map(f).next()
}
/// Returns the position of the first element of this iterator that matches
/// a predicate. The predicate may fail; such failures are returned to the
/// caller.
#[inline]
fn position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<bool, Self::Error>,
{
let mut i = 0;
while let Some(v) = self.next()? {
if f(v)? {
return Ok(Some(i));
}
i += 1;
}
Ok(None)
}
/// Returns the maximal element of the iterator.
#[inline]
fn max(self) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
Self::Item: Ord,
{
self.max_by(|a, b| Ok(a.cmp(b)))
}
/// Returns the element of the iterator which gives the maximum value from
/// the function.
#[inline]
fn max_by_key<B, F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
B: Ord,
F: FnMut(&Self::Item) -> Result<B, Self::Error>,
{
let max = match self.next()? {
Some(v) => (f(&v)?, v),
None => return Ok(None),
};
self.fold(max, |(key, max), v| {
let new_key = f(&v)?;
if key > new_key {
Ok((key, max))
} else {
Ok((new_key, v))
}
})
.map(|v| Some(v.1))
}
/// Returns the element that gives the maximum value with respect to the function.
#[inline]
fn max_by<F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{
let max = match self.next()? {
Some(v) => v,
None => return Ok(None),
};
self.fold(max, |max, v| {
if f(&max, &v)? == Ordering::Greater {
Ok(max)
} else {
Ok(v)
}
})
.map(Some)
}
/// Returns the minimal element of the iterator.
#[inline]
fn min(self) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
Self::Item: Ord,
{
self.min_by(|a, b| Ok(a.cmp(b)))
}
/// Returns the element of the iterator which gives the minimum value from
/// the function.
#[inline]
fn min_by_key<B, F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
B: Ord,
F: FnMut(&Self::Item) -> Result<B, Self::Error>,
{
let min = match self.next()? {
Some(v) => (f(&v)?, v),
None => return Ok(None),
};
self.fold(min, |(key, min), v| {
let new_key = f(&v)?;
if key < new_key {
Ok((key, min))
} else {
Ok((new_key, v))
}
})
.map(|v| Some(v.1))
}
/// Returns the element that gives the minimum value with respect to the function.
#[inline]
fn min_by<F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{
let min = match self.next()? {
Some(v) => v,
None => return Ok(None),
};
self.fold(min, |min, v| {
if f(&min, &v)? == Ordering::Less {
Ok(min)
} else {
Ok(v)
}
})
.map(Some)
}
/// Returns an iterator that yields this iterator's items in the opposite
/// order.
#[inline]
fn rev(self) -> Rev<Self>
where
Self: Sized + DoubleEndedFallibleIterator,
{
Rev(self)
}
/// Converts an iterator of pairs into a pair of containers.
#[inline]
fn unzip<A, B, FromA, FromB>(self) -> Result<(FromA, FromB), Self::Error>
where
Self: Sized + FallibleIterator<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
let mut from_a = FromA::default();
let mut from_b = FromB::default();
self.for_each(|(a, b)| {
from_a.extend(Some(a));
from_b.extend(Some(b));
Ok(())
})?;
Ok((from_a, from_b))
}
/// Returns an iterator which clones all of its elements.
#[inline]
fn cloned<'a, T>(self) -> Cloned<Self>
where
Self: Sized + FallibleIterator<Item = &'a T>,
T: 'a + Clone,
{
Cloned(self)
}
/// Returns an iterator which repeas this iterator endlessly.
#[inline]
fn cycle(self) -> Cycle<Self>
where
Self: Sized + Clone,
{
Cycle {
it: self.clone(),
cur: self,
}
}
/// Lexicographically compares the elements of this iterator to that of
/// another.
#[inline]
fn cmp<I>(mut self, other: I) -> Result<Ordering, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Item = Self::Item, Error = Self::Error>,
Self::Item: Ord,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(Ordering::Equal),
(None, _) => return Ok(Ordering::Less),
(_, None) => return Ok(Ordering::Greater),
(Some(x), Some(y)) => match x.cmp(&y) {
Ordering::Equal => {}
o => return Ok(o),
},
}
}
}
/// Lexicographically compares the elements of this iterator to that of
/// another.
#[inline]
fn partial_cmp<I>(mut self, other: I) -> Result<Option<Ordering>, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialOrd<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(Some(Ordering::Equal)),
(None, _) => return Ok(Some(Ordering::Less)),
(_, None) => return Ok(Some(Ordering::Greater)),
(Some(x), Some(y)) => match x.partial_cmp(&y) {
Some(Ordering::Equal) => {}
o => return Ok(o),
},
}
}
}
/// Determines if the elements of this iterator are equal to those of
/// another.
#[inline]
fn eq<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialEq<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(true),
(None, _) | (_, None) => return Ok(false),
(Some(x), Some(y)) => {
if x != y {
return Ok(false);
}
}
}
}
}
/// Determines if the elements of this iterator are not equal to those of
/// another.
#[inline]
fn ne<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialEq<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(false),
(None, _) | (_, None) => return Ok(true),
(Some(x), Some(y)) => {
if x != y {
return Ok(true);
}
}
}
}
}
/// Determines if the elements of this iterator are lexicographically less
/// than those of another.
#[inline]
fn lt<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialOrd<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(false),
(None, _) => return Ok(true),
(_, None) => return Ok(false),
(Some(x), Some(y)) => match x.partial_cmp(&y) {
Some(Ordering::Less) => return Ok(true),
Some(Ordering::Equal) => {}
Some(Ordering::Greater) => return Ok(false),
None => return Ok(false),
},
}
}
}
/// Determines if the elements of this iterator are lexicographically less
/// than or equal to those of another.
#[inline]
fn le<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialOrd<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(true),
(None, _) => return Ok(true),
(_, None) => return Ok(false),
(Some(x), Some(y)) => match x.partial_cmp(&y) {
Some(Ordering::Less) => return Ok(true),
Some(Ordering::Equal) => {}
Some(Ordering::Greater) => return Ok(false),
None => return Ok(false),
},
}
}
}
/// Determines if the elements of this iterator are lexicographically
/// greater than those of another.
#[inline]
fn gt<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialOrd<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(false),
(None, _) => return Ok(false),
(_, None) => return Ok(true),
(Some(x), Some(y)) => match x.partial_cmp(&y) {
Some(Ordering::Less) => return Ok(false),
Some(Ordering::Equal) => {}
Some(Ordering::Greater) => return Ok(true),
None => return Ok(false),
},
}
}
}
/// Determines if the elements of this iterator are lexicographically
/// greater than or equal to those of another.
#[inline]
fn ge<I>(mut self, other: I) -> Result<bool, Self::Error>
where
Self: Sized,
I: IntoFallibleIterator<Error = Self::Error>,
Self::Item: PartialOrd<I::Item>,
{
let mut other = other.into_fallible_iter();
loop {
match (self.next()?, other.next()?) {
(None, None) => return Ok(true),
(None, _) => return Ok(false),
(_, None) => return Ok(true),
(Some(x), Some(y)) => match x.partial_cmp(&y) {
Some(Ordering::Less) => return Ok(false),
Some(Ordering::Equal) => {}
Some(Ordering::Greater) => return Ok(true),
None => return Ok(false),
},
}
}
}
/// Returns a normal (non-fallible) iterator over `Result<Item, Error>`.
#[inline]
fn iterator(self) -> Iterator<Self>
where
Self: Sized,
{
Iterator(self)
}
/// Returns an iterator which applies a transform to the errors of the
/// underlying iterator.
#[inline]
fn map_err<B, F>(self, f: F) -> MapErr<Self, F>
where
F: FnMut(Self::Error) -> B,
Self: Sized,
{
MapErr { it: self, f: f }
}
}
impl<I: FallibleIterator + ?Sized> FallibleIterator for &mut I {
type Item = I::Item;
type Error = I::Error;
#[inline]
fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
(**self).next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
#[inline]
fn nth(&mut self, n: usize) -> Result<Option<I::Item>, I::Error> {
(**self).nth(n)
}
}
impl<I: DoubleEndedFallibleIterator + ?Sized> DoubleEndedFallibleIterator for &mut I {
#[inline]
fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
(**self).next_back()
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<I: FallibleIterator + ?Sized> FallibleIterator for Box<I> {
type Item = I::Item;
type Error = I::Error;
#[inline]
fn next(&mut self) -> Result<Option<I::Item>, I::Error> {
(**self).next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
#[inline]
fn nth(&mut self, n: usize) -> Result<Option<I::Item>, I::Error> {
(**self).nth(n)
}
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<I: DoubleEndedFallibleIterator + ?Sized> DoubleEndedFallibleIterator for Box<I> {
#[inline]
fn next_back(&mut self) -> Result<Option<I::Item>, I::Error> {
(**self).next_back()
}
}
/// A fallible iterator able to yield elements from both ends.
pub trait DoubleEndedFallibleIterator: FallibleIterator {
/// Advances the end of the iterator, returning the last value.
fn next_back(&mut self) -> Result<Option<Self::Item>, Self::Error>;
}
/// Conversion from a fallible iterator.
pub trait FromFallibleIterator<T>: Sized {
/// Creates a value from a fallible iterator.
fn from_fallible_iterator<I>(it: I) -> Result<Self, I::Error>
where
I: IntoFallibleIterator<Item = T>;
}
#[cfg(any(feature = "std", feature = "alloc"))]
impl<T> FromFallibleIterator<T> for Vec<T> {
#[inline]
fn from_fallible_iterator<I>(it: I) -> Result<Vec<T>, I::Error>
where
I: IntoFallibleIterator<Item = T>,