1 //! Fallible, streaming iteration.
2 //!
3 //! `FallibleStreamingIterator` differs from the standard library's `Iterator` trait in two ways:
4 //! iteration can fail, resulting in an error, and only one element of the iteration is available at
5 //! any time.
6 //!
7 //! While these iterators cannot be used with Rust `for` loops, `while let` loops offer a similar
8 //! level of ergonomics:
9 //!
10 //! ```ignore
11 //! while let Some(value) = it.next()? {
12 //! // use value
13 //! }
14 //! ```
15 #![doc(html_root_url = "https://docs.rs/fallible-streaming-iterator/0.1")]
16 #![warn(missing_docs)]
17 #![cfg_attr(not(feature = "std"), no_std)]
18
19 #[cfg(feature = "std")]
20 extern crate core;
21
22 use core::cmp;
23 use core::marker::PhantomData;
24
25 /// A fallible, streaming iterator.
26 pub trait FallibleStreamingIterator {
27 /// The type being iterated over.
28 type Item: ?Sized;
29
30 /// The error type of iteration.
31 type Error;
32
33 /// Advances the iterator to the next position.
34 ///
35 /// Iterators start just before the first item, so this method should be called before `get`
36 /// when iterating.
37 ///
38 /// The behavior of calling this method after `get` has returned `None`, or after this method
39 /// has returned an error is unspecified.
advance(&mut self) -> Result<(), Self::Error>40 fn advance(&mut self) -> Result<(), Self::Error>;
41
42 /// Returns the current element.
43 ///
44 /// The behavior of calling this method before any calls to `advance` is unspecified.
get(&self) -> Option<&Self::Item>45 fn get(&self) -> Option<&Self::Item>;
46
47 /// Advances the iterator, returning the next element.
48 ///
49 /// The default implementation simply calls `advance` followed by `get`.
50 #[inline]
next(&mut self) -> Result<Option<&Self::Item>, Self::Error>51 fn next(&mut self) -> Result<Option<&Self::Item>, Self::Error> {
52 self.advance()?;
53 Ok((*self).get())
54 }
55
56 /// Returns bounds on the number of remaining elements in the iterator.
57 #[inline]
size_hint(&self) -> (usize, Option<usize>)58 fn size_hint(&self) -> (usize, Option<usize>) {
59 (0, None)
60 }
61
62 /// Determines if all elements of the iterator satisfy a predicate.
63 #[inline]
all<F>(&mut self, mut f: F) -> Result<bool, Self::Error> where Self: Sized, F: FnMut(&Self::Item) -> bool,64 fn all<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
65 where
66 Self: Sized,
67 F: FnMut(&Self::Item) -> bool,
68 {
69 while let Some(e) = self.next()? {
70 if !f(e) {
71 return Ok(false);
72 }
73 }
74 Ok(true)
75 }
76
77 /// Determines if any elements of the iterator satisfy a predicate.
78 #[inline]
any<F>(&mut self, mut f: F) -> Result<bool, Self::Error> where Self: Sized, F: FnMut(&Self::Item) -> bool,79 fn any<F>(&mut self, mut f: F) -> Result<bool, Self::Error>
80 where
81 Self: Sized,
82 F: FnMut(&Self::Item) -> bool,
83 {
84 self.all(|e| !f(e)).map(|r| !r)
85 }
86
87 /// Borrows an iterator, rather than consuming it.
88 ///
89 /// This is useful to allow the application of iterator adaptors while still retaining ownership
90 /// of the original adaptor.
91 #[inline]
by_ref(&mut self) -> &mut Self where Self: Sized,92 fn by_ref(&mut self) -> &mut Self
93 where
94 Self: Sized,
95 {
96 self
97 }
98
99 /// Returns the number of remaining elements in the iterator.
100 #[inline]
count(mut self) -> Result<usize, Self::Error> where Self: Sized,101 fn count(mut self) -> Result<usize, Self::Error>
102 where
103 Self: Sized,
104 {
105 let mut count = 0;
106 while let Some(_) = self.next()? {
107 count += 1;
108 }
109 Ok(count)
110 }
111
112 /// Returns an iterator which filters elements by a predicate.
113 #[inline]
filter<F>(self, f: F) -> Filter<Self, F> where Self: Sized, F: FnMut(&Self::Item) -> bool,114 fn filter<F>(self, f: F) -> Filter<Self, F>
115 where
116 Self: Sized,
117 F: FnMut(&Self::Item) -> bool,
118 {
119 Filter { it: self, f: f }
120 }
121
122 /// Returns the first element of the iterator which satisfies a predicate.
123 #[inline]
find<F>(&mut self, mut f: F) -> Result<Option<&Self::Item>, Self::Error> where Self: Sized, F: FnMut(&Self::Item) -> bool,124 fn find<F>(&mut self, mut f: F) -> Result<Option<&Self::Item>, Self::Error>
125 where
126 Self: Sized,
127 F: FnMut(&Self::Item) -> bool,
128 {
129 loop {
130 self.advance()?;
131 match self.get() {
132 Some(v) => {
133 if f(v) {
134 break;
135 }
136 }
137 None => break,
138 }
139 }
140 Ok((*self).get())
141 }
142
143 /// Calls a closure on each element of an iterator.
144 #[inline]
for_each<F>(mut self, mut f: F) -> Result<(), Self::Error> where Self: Sized, F: FnMut(&Self::Item),145 fn for_each<F>(mut self, mut f: F) -> Result<(), Self::Error>
146 where
147 Self: Sized,
148 F: FnMut(&Self::Item),
149 {
150 while let Some(value) = self.next()? {
151 f(value);
152 }
153 Ok(())
154 }
155
156 /// Returns an iterator which is well-behaved at the beginning and end of iteration.
157 #[inline]
fuse(self) -> Fuse<Self> where Self: Sized,158 fn fuse(self) -> Fuse<Self>
159 where
160 Self: Sized,
161 {
162 Fuse {
163 it: self,
164 state: FuseState::Start,
165 }
166 }
167
168 /// Returns an iterator which applies a transform to elements.
169 #[inline]
map<F, B>(self, f: F) -> Map<Self, F, B> where Self: Sized, F: FnMut(&Self::Item) -> B,170 fn map<F, B>(self, f: F) -> Map<Self, F, B>
171 where
172 Self: Sized,
173 F: FnMut(&Self::Item) -> B,
174 {
175 Map {
176 it: self,
177 f: f,
178 value: None,
179 }
180 }
181
182 /// Returns an iterator which applies a transform to elements.
183 ///
184 /// Unlike `map`, the the closure provided to this method returns a reference into the original
185 /// value.
186 #[inline]
map_ref<F, B: ?Sized>(self, f: F) -> MapRef<Self, F> where Self: Sized, F: Fn(&Self::Item) -> &B,187 fn map_ref<F, B: ?Sized>(self, f: F) -> MapRef<Self, F>
188 where
189 Self: Sized,
190 F: Fn(&Self::Item) -> &B,
191 {
192 MapRef { it: self, f: f }
193 }
194
195 /// Returns an iterator that applies a transform to errors.
196 #[inline]
map_err<F, B>(self, f: F) -> MapErr<Self, F> where Self: Sized, F: Fn(Self::Error) -> B,197 fn map_err<F, B>(self, f: F) -> MapErr<Self, F>
198 where
199 Self: Sized,
200 F: Fn(Self::Error) -> B,
201 {
202 MapErr { it: self, f: f }
203 }
204
205 /// Returns the `nth` element of the iterator.
206 #[inline]
nth(&mut self, n: usize) -> Result<Option<&Self::Item>, Self::Error>207 fn nth(&mut self, n: usize) -> Result<Option<&Self::Item>, Self::Error> {
208 for _ in 0..n {
209 self.advance()?;
210 if let None = self.get() {
211 return Ok(None);
212 }
213 }
214 self.next()
215 }
216
217 /// Returns the position of the first element matching a predicate.
218 #[inline]
position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error> where Self: Sized, F: FnMut(&Self::Item) -> bool,219 fn position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error>
220 where
221 Self: Sized,
222 F: FnMut(&Self::Item) -> bool,
223 {
224 let mut pos = 0;
225 while let Some(v) = self.next()? {
226 if f(v) {
227 return Ok(Some(pos));
228 }
229 pos += 1;
230 }
231 Ok(None)
232 }
233
234 /// Returns an iterator which skips the first `n` elements.
235 #[inline]
skip(self, n: usize) -> Skip<Self> where Self: Sized,236 fn skip(self, n: usize) -> Skip<Self>
237 where
238 Self: Sized,
239 {
240 Skip { it: self, n: n }
241 }
242
243 /// Returns an iterator which skips the first sequence of elements matching a predicate.
244 #[inline]
skip_while<F>(self, f: F) -> SkipWhile<Self, F> where Self: Sized, F: FnMut(&Self::Item) -> bool,245 fn skip_while<F>(self, f: F) -> SkipWhile<Self, F>
246 where
247 Self: Sized,
248 F: FnMut(&Self::Item) -> bool,
249 {
250 SkipWhile {
251 it: self,
252 f: f,
253 done: false,
254 }
255 }
256
257 /// Returns an iterator which only returns the first `n` elements.
258 #[inline]
take(self, n: usize) -> Take<Self> where Self: Sized,259 fn take(self, n: usize) -> Take<Self>
260 where
261 Self: Sized,
262 {
263 Take {
264 it: self,
265 n: n,
266 done: false,
267 }
268 }
269
270 /// Returns an iterator which only returns the first sequence of elements matching a predicate.
271 #[inline]
take_while<F>(self, f: F) -> TakeWhile<Self, F> where Self: Sized, F: FnMut(&Self::Item) -> bool,272 fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
273 where
274 Self: Sized,
275 F: FnMut(&Self::Item) -> bool,
276 {
277 TakeWhile {
278 it: self,
279 f: f,
280 done: false,
281 }
282 }
283 }
284
285 /// A fallible, streaming iterator which can be advanced from either end.
286 pub trait DoubleEndedFallibleStreamingIterator: FallibleStreamingIterator {
287 /// Advances the state of the iterator to the next item from the end.
288 ///
289 /// Iterators start just after the last item, so this method should be called before `get`
290 /// when iterating.
291 ///
292 /// The behavior of calling this method after `get` has returned `None`, or after this method
293 /// or `advance` has returned an error is unspecified.
advance_back(&mut self) -> Result<(), Self::Error>294 fn advance_back(&mut self) -> Result<(), Self::Error>;
295
296 /// Advances the back of the iterator, returning the last element.
297 ///
298 /// The default implementation simply calls `advance_back` followed by `get`.
299 #[inline]
next_back(&mut self) -> Result<Option<&Self::Item>, Self::Error>300 fn next_back(&mut self) -> Result<Option<&Self::Item>, Self::Error> {
301 self.advance_back()?;
302 Ok((*self).get())
303 }
304 }
305
306 impl<'a, I: ?Sized> FallibleStreamingIterator for &'a mut I
307 where
308 I: FallibleStreamingIterator,
309 {
310 type Item = I::Item;
311 type Error = I::Error;
312
313 #[inline]
advance(&mut self) -> Result<(), I::Error>314 fn advance(&mut self) -> Result<(), I::Error> {
315 (**self).advance()
316 }
317
318 #[inline]
get(&self) -> Option<&I::Item>319 fn get(&self) -> Option<&I::Item> {
320 (**self).get()
321 }
322
323 #[inline]
size_hint(&self) -> (usize, Option<usize>)324 fn size_hint(&self) -> (usize, Option<usize>) {
325 (**self).size_hint()
326 }
327
328 #[inline]
next(&mut self) -> Result<Option<&I::Item>, I::Error>329 fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
330 (**self).next()
331 }
332 }
333
334 #[cfg(feature = "std")]
335 impl<I: ?Sized> FallibleStreamingIterator for Box<I>
336 where
337 I: FallibleStreamingIterator,
338 {
339 type Item = I::Item;
340 type Error = I::Error;
341
342 #[inline]
advance(&mut self) -> Result<(), I::Error>343 fn advance(&mut self) -> Result<(), I::Error> {
344 (**self).advance()
345 }
346
347 #[inline]
get(&self) -> Option<&I::Item>348 fn get(&self) -> Option<&I::Item> {
349 (**self).get()
350 }
351
352 #[inline]
size_hint(&self) -> (usize, Option<usize>)353 fn size_hint(&self) -> (usize, Option<usize>) {
354 (**self).size_hint()
355 }
356
357 #[inline]
next(&mut self) -> Result<Option<&I::Item>, I::Error>358 fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
359 (**self).next()
360 }
361 }
362
363 /// Converts a normal `Iterator` over `Results` of references into a
364 /// `FallibleStreamingIterator`.
convert<'a, I, T, E>(it: I) -> Convert<'a, I, T> where I: Iterator<Item = Result<&'a T, E>>,365 pub fn convert<'a, I, T, E>(it: I) -> Convert<'a, I, T>
366 where
367 I: Iterator<Item = Result<&'a T, E>>,
368 {
369 Convert { it: it, item: None }
370 }
371
372 /// An iterator which wraps a normal `Iterator`.
373 pub struct Convert<'a, I, T: 'a> {
374 it: I,
375 item: Option<&'a T>,
376 }
377
378 impl<'a, I, T, E> FallibleStreamingIterator for Convert<'a, I, T>
379 where
380 I: Iterator<Item = Result<&'a T, E>>,
381 {
382 type Item = T;
383 type Error = E;
384
385 #[inline]
advance(&mut self) -> Result<(), E>386 fn advance(&mut self) -> Result<(), E> {
387 self.item = match self.it.next() {
388 Some(Ok(v)) => Some(v),
389 Some(Err(e)) => return Err(e),
390 None => None,
391 };
392 Ok(())
393 }
394
395 #[inline]
get(&self) -> Option<&T>396 fn get(&self) -> Option<&T> {
397 self.item
398 }
399
400 #[inline]
size_hint(&self) -> (usize, Option<usize>)401 fn size_hint(&self) -> (usize, Option<usize>) {
402 self.it.size_hint()
403 }
404 }
405
406 impl<'a, I, T, E> DoubleEndedFallibleStreamingIterator for Convert<'a, I, T>
407 where
408 I: DoubleEndedIterator<Item = Result<&'a T, E>>,
409 {
410 #[inline]
advance_back(&mut self) -> Result<(), E>411 fn advance_back(&mut self) -> Result<(), E> {
412 self.item = match self.it.next_back() {
413 Some(Ok(v)) => Some(v),
414 Some(Err(e)) => return Err(e),
415 None => None,
416 };
417 Ok(())
418 }
419 }
420
421 /// Returns an iterator over no items.
empty<T, E>() -> Empty<T, E>422 pub fn empty<T, E>() -> Empty<T, E> {
423 Empty(PhantomData)
424 }
425
426 /// An iterator over no items.
427 pub struct Empty<T, E>(PhantomData<(T, E)>);
428
429 impl<T, E> FallibleStreamingIterator for Empty<T, E> {
430 type Item = T;
431 type Error = E;
432
433 #[inline]
advance(&mut self) -> Result<(), E>434 fn advance(&mut self) -> Result<(), E> {
435 Ok(())
436 }
437
438 #[inline]
get(&self) -> Option<&T>439 fn get(&self) -> Option<&T> {
440 None
441 }
442
443 #[inline]
size_hint(&self) -> (usize, Option<usize>)444 fn size_hint(&self) -> (usize, Option<usize>) {
445 (0, Some(0))
446 }
447 }
448
449 impl<T, E> DoubleEndedFallibleStreamingIterator for Empty<T, E> {
450 #[inline]
advance_back(&mut self) -> Result<(), E>451 fn advance_back(&mut self) -> Result<(), E> {
452 Ok(())
453 }
454 }
455
456 /// An iterator which filters elements with a predicate.
457 pub struct Filter<I, F> {
458 it: I,
459 f: F,
460 }
461
462 impl<I, F> FallibleStreamingIterator for Filter<I, F>
463 where
464 I: FallibleStreamingIterator,
465 F: FnMut(&I::Item) -> bool,
466 {
467 type Item = I::Item;
468 type Error = I::Error;
469
470 #[inline]
advance(&mut self) -> Result<(), I::Error>471 fn advance(&mut self) -> Result<(), I::Error> {
472 while let Some(i) = self.it.next()? {
473 if (self.f)(i) {
474 break;
475 }
476 }
477 Ok(())
478 }
479
480 #[inline]
get(&self) -> Option<&I::Item>481 fn get(&self) -> Option<&I::Item> {
482 self.it.get()
483 }
484
485 #[inline]
size_hint(&self) -> (usize, Option<usize>)486 fn size_hint(&self) -> (usize, Option<usize>) {
487 (0, self.it.size_hint().1)
488 }
489 }
490
491 #[derive(Copy, Clone)]
492 enum FuseState {
493 Start,
494 Middle,
495 End,
496 }
497
498 /// An iterator which is well-behaved at the beginning and end of iteration.
499 pub struct Fuse<I> {
500 it: I,
501 state: FuseState,
502 }
503
504 impl<I> FallibleStreamingIterator for Fuse<I>
505 where
506 I: FallibleStreamingIterator,
507 {
508 type Item = I::Item;
509 type Error = I::Error;
510
511 #[inline]
advance(&mut self) -> Result<(), I::Error>512 fn advance(&mut self) -> Result<(), I::Error> {
513 match self.state {
514 FuseState::Start => {
515 match self.it.next() {
516 Ok(Some(_)) => self.state = FuseState::Middle,
517 Ok(None) => self.state = FuseState::End,
518 Err(e) => {
519 self.state = FuseState::End;
520 return Err(e);
521 }
522 };
523 }
524 FuseState::Middle => match self.it.next() {
525 Ok(Some(_)) => {}
526 Ok(None) => self.state = FuseState::End,
527 Err(e) => {
528 self.state = FuseState::End;
529 return Err(e);
530 }
531 },
532 FuseState::End => {}
533 }
534 Ok(())
535 }
536
537 #[inline]
get(&self) -> Option<&I::Item>538 fn get(&self) -> Option<&I::Item> {
539 match self.state {
540 FuseState::Middle => self.it.get(),
541 FuseState::Start | FuseState::End => None,
542 }
543 }
544
545 #[inline]
size_hint(&self) -> (usize, Option<usize>)546 fn size_hint(&self) -> (usize, Option<usize>) {
547 self.it.size_hint()
548 }
549
550 #[inline]
next(&mut self) -> Result<Option<&I::Item>, I::Error>551 fn next(&mut self) -> Result<Option<&I::Item>, I::Error> {
552 match self.state {
553 FuseState::Start => match self.it.next() {
554 Ok(Some(v)) => {
555 self.state = FuseState::Middle;
556 Ok(Some(v))
557 }
558 Ok(None) => {
559 self.state = FuseState::End;
560 Ok(None)
561 }
562 Err(e) => {
563 self.state = FuseState::End;
564 Err(e)
565 }
566 },
567 FuseState::Middle => match self.it.next() {
568 Ok(Some(v)) => Ok(Some(v)),
569 Ok(None) => {
570 self.state = FuseState::End;
571 Ok(None)
572 }
573 Err(e) => {
574 self.state = FuseState::End;
575 Err(e)
576 }
577 },
578 FuseState::End => Ok(None),
579 }
580 }
581 }
582
583 /// An iterator which applies a transform to elements.
584 pub struct Map<I, F, B> {
585 it: I,
586 f: F,
587 value: Option<B>,
588 }
589
590 impl<I, F, B> FallibleStreamingIterator for Map<I, F, B>
591 where
592 I: FallibleStreamingIterator,
593 F: FnMut(&I::Item) -> B,
594 {
595 type Item = B;
596 type Error = I::Error;
597
598 #[inline]
advance(&mut self) -> Result<(), I::Error>599 fn advance(&mut self) -> Result<(), I::Error> {
600 self.value = self.it.next()?.map(&mut self.f);
601 Ok(())
602 }
603
604 #[inline]
get(&self) -> Option<&B>605 fn get(&self) -> Option<&B> {
606 self.value.as_ref()
607 }
608
609 #[inline]
size_hint(&self) -> (usize, Option<usize>)610 fn size_hint(&self) -> (usize, Option<usize>) {
611 self.it.size_hint()
612 }
613 }
614
615 impl<I, F, B> DoubleEndedFallibleStreamingIterator for Map<I, F, B>
616 where
617 I: DoubleEndedFallibleStreamingIterator,
618 F: FnMut(&I::Item) -> B,
619 {
620 #[inline]
advance_back(&mut self) -> Result<(), I::Error>621 fn advance_back(&mut self) -> Result<(), I::Error> {
622 self.value = self.it.next_back()?.map(&mut self.f);
623 Ok(())
624 }
625 }
626
627 /// An iterator which applies a transform to elements.
628 pub struct MapRef<I, F> {
629 it: I,
630 f: F,
631 }
632
633 impl<I, F, B: ?Sized> FallibleStreamingIterator for MapRef<I, F>
634 where
635 I: FallibleStreamingIterator,
636 F: Fn(&I::Item) -> &B,
637 {
638 type Item = B;
639 type Error = I::Error;
640
641 #[inline]
advance(&mut self) -> Result<(), I::Error>642 fn advance(&mut self) -> Result<(), I::Error> {
643 self.it.advance()
644 }
645
646 #[inline]
get(&self) -> Option<&B>647 fn get(&self) -> Option<&B> {
648 self.it.get().map(&self.f)
649 }
650
651 #[inline]
size_hint(&self) -> (usize, Option<usize>)652 fn size_hint(&self) -> (usize, Option<usize>) {
653 self.it.size_hint()
654 }
655 }
656
657 impl<I, F, B: ?Sized> DoubleEndedFallibleStreamingIterator for MapRef<I, F>
658 where
659 I: DoubleEndedFallibleStreamingIterator,
660 F: Fn(&I::Item) -> &B,
661 {
662 #[inline]
advance_back(&mut self) -> Result<(), I::Error>663 fn advance_back(&mut self) -> Result<(), I::Error> {
664 self.it.advance_back()
665 }
666 }
667
668 /// An iterator which applies a transform to errors.
669 pub struct MapErr<I, F> {
670 it: I,
671 f: F,
672 }
673
674 impl<I, F, B> FallibleStreamingIterator for MapErr<I, F>
675 where
676 I: FallibleStreamingIterator,
677 F: Fn(I::Error) -> B,
678 {
679 type Item = I::Item;
680 type Error = B;
681
682 #[inline]
advance(&mut self) -> Result<(), B>683 fn advance(&mut self) -> Result<(), B> {
684 self.it.advance().map_err(&mut self.f)
685 }
686
687 #[inline]
get(&self) -> Option<&I::Item>688 fn get(&self) -> Option<&I::Item> {
689 self.it.get()
690 }
691
692 #[inline]
next(&mut self) -> Result<Option<&I::Item>, B>693 fn next(&mut self) -> Result<Option<&I::Item>, B> {
694 self.it.next().map_err(&mut self.f)
695 }
696
697 #[inline]
size_hint(&self) -> (usize, Option<usize>)698 fn size_hint(&self) -> (usize, Option<usize>) {
699 self.it.size_hint()
700 }
701 }
702
703 impl<I, F, B> DoubleEndedFallibleStreamingIterator for MapErr<I, F>
704 where
705 I: DoubleEndedFallibleStreamingIterator,
706 F: Fn(I::Error) -> B,
707 {
708 #[inline]
advance_back(&mut self) -> Result<(), B>709 fn advance_back(&mut self) -> Result<(), B> {
710 self.it.advance_back().map_err(&mut self.f)
711 }
712
713 #[inline]
next_back(&mut self) -> Result<Option<&I::Item>, B>714 fn next_back(&mut self) -> Result<Option<&I::Item>, B> {
715 self.it.next_back().map_err(&mut self.f)
716 }
717 }
718
719 /// An iterator which skips a number of initial elements.
720 pub struct Skip<I> {
721 it: I,
722 n: usize,
723 }
724
725 impl<I> FallibleStreamingIterator for Skip<I>
726 where
727 I: FallibleStreamingIterator,
728 {
729 type Item = I::Item;
730 type Error = I::Error;
731
732 #[inline]
advance(&mut self) -> Result<(), I::Error>733 fn advance(&mut self) -> Result<(), I::Error> {
734 for _ in 0..self.n {
735 if let None = self.it.next()? {
736 return Ok(());
737 }
738 }
739 self.n = 0;
740 self.advance()
741 }
742
743 #[inline]
get(&self) -> Option<&I::Item>744 fn get(&self) -> Option<&I::Item> {
745 self.it.get()
746 }
747
748 #[inline]
size_hint(&self) -> (usize, Option<usize>)749 fn size_hint(&self) -> (usize, Option<usize>) {
750 let hint = self.it.size_hint();
751 (
752 hint.0.saturating_sub(self.n),
753 hint.1.map(|h| h.saturating_sub(self.n)),
754 )
755 }
756 }
757
758 /// An iterator which skips initial elements matching a predicate.
759 pub struct SkipWhile<I, F> {
760 it: I,
761 f: F,
762 done: bool,
763 }
764
765 impl<I, F> FallibleStreamingIterator for SkipWhile<I, F>
766 where
767 I: FallibleStreamingIterator,
768 F: FnMut(&I::Item) -> bool,
769 {
770 type Item = I::Item;
771 type Error = I::Error;
772
773 #[inline]
advance(&mut self) -> Result<(), I::Error>774 fn advance(&mut self) -> Result<(), I::Error> {
775 if !self.done {
776 self.done = true;
777 let f = &mut self.f;
778 self.it.find(|i| !f(i)).map(|_| ())
779 } else {
780 self.it.advance()
781 }
782 }
783
784 #[inline]
get(&self) -> Option<&I::Item>785 fn get(&self) -> Option<&I::Item> {
786 self.it.get()
787 }
788
789 #[inline]
size_hint(&self) -> (usize, Option<usize>)790 fn size_hint(&self) -> (usize, Option<usize>) {
791 let hint = self.it.size_hint();
792 if self.done {
793 hint
794 } else {
795 (0, hint.1)
796 }
797 }
798 }
799
800 /// An iterator which only returns a number of initial elements.
801 pub struct Take<I> {
802 it: I,
803 n: usize,
804 done: bool,
805 }
806
807 impl<I> FallibleStreamingIterator for Take<I>
808 where
809 I: FallibleStreamingIterator,
810 {
811 type Item = I::Item;
812 type Error = I::Error;
813
814 #[inline]
advance(&mut self) -> Result<(), I::Error>815 fn advance(&mut self) -> Result<(), I::Error> {
816 if self.n != 0 {
817 self.it.advance()?;
818 self.n -= 1;
819 } else {
820 self.done = true;
821 }
822 Ok(())
823 }
824
825 #[inline]
get(&self) -> Option<&I::Item>826 fn get(&self) -> Option<&I::Item> {
827 if self.done {
828 None
829 } else {
830 self.it.get()
831 }
832 }
833
834 #[inline]
size_hint(&self) -> (usize, Option<usize>)835 fn size_hint(&self) -> (usize, Option<usize>) {
836 let (lower, upper) = self.it.size_hint();
837
838 let lower = cmp::min(lower, self.n);
839
840 let upper = match upper {
841 Some(x) if x < self.n => Some(x),
842 _ => Some(self.n)
843 };
844
845 (lower, upper)
846 }
847 }
848
849 /// An iterator which only returns initial elements matching a predicate.
850 pub struct TakeWhile<I, F> {
851 it: I,
852 f: F,
853 done: bool,
854 }
855
856 impl<I, F> FallibleStreamingIterator for TakeWhile<I, F>
857 where
858 I: FallibleStreamingIterator,
859 F: FnMut(&I::Item) -> bool,
860 {
861 type Item = I::Item;
862 type Error = I::Error;
863
864 #[inline]
advance(&mut self) -> Result<(), I::Error>865 fn advance(&mut self) -> Result<(), I::Error> {
866 if let Some(v) = self.it.next()? {
867 if !(self.f)(v) {
868 self.done = true;
869 }
870 }
871 Ok(())
872 }
873
874 #[inline]
get(&self) -> Option<&I::Item>875 fn get(&self) -> Option<&I::Item> {
876 if self.done {
877 None
878 } else {
879 self.it.get()
880 }
881 }
882
883 #[inline]
size_hint(&self) -> (usize, Option<usize>)884 fn size_hint(&self) -> (usize, Option<usize>) {
885 if self.done {
886 (0, Some(0))
887 } else {
888 (0, self.it.size_hint().1)
889 }
890 }
891 }
892
893 #[cfg(test)]
894 mod test {
895 use super::*;
896
_is_object_safe(_: &FallibleStreamingIterator<Item = (), Error = ()>)897 fn _is_object_safe(_: &FallibleStreamingIterator<Item = (), Error = ()>) {}
_is_object_safe_double(_: &DoubleEndedFallibleStreamingIterator<Item = (), Error = ()>)898 fn _is_object_safe_double(_: &DoubleEndedFallibleStreamingIterator<Item = (), Error = ()>) {}
899 }
900