internal_iterator/lib.rs
1#![doc = "Internal iterator equivalent of [`std::iter::Iterator`].
2
3In some cases implementing `Iterator` can be difficult - for tree shaped
4structures you would need to store iteration state at every level, which
5implies dynamic allocation and nontrivial amounts of state. On the other
6hand, internal iteration is roughly equivalent to calling a provided
7function on every element you need to yield and is much simpler to
8implement.
9
10This library aims to provide `std`-like iteration facilities, but
11based on internal iteration. The goal is to be easy to make use of and feel
12familiar to users of `Iterator`. There is one core trait, [`InternalIterator`].
13By implementing it you can use its provided methods to construct iterator
14pipelines similar to those possible by using regular iterators.
15
16# Implementing `InternalIterator`
17
18Whereas the driving method for regular iterators is [`Iterator::next`], the one
19used here is [`InternalIterator::try_for_each`].
20
21```rust
22use std::ops::ControlFlow;
23use internal_iterator::{InternalIterator, IteratorExt};
24
25struct Tree {
26 value: i32,
27 children: Vec<Tree>,
28}
29
30// We implement InternalIterator on the tree directly. You could also
31// introduce a wrapper struct and create it in `.iter()`, `.iter_mut()`, just
32// like with usual collections.
33impl InternalIterator for Tree {
34 type Item = i32;
35
36 fn try_for_each<T, F>(self, mut f: F) -> ControlFlow<T>
37 where
38 F: FnMut(i32) -> ControlFlow<T>,
39 {
40 self.iter_helper(&mut f)
41 }
42}
43
44impl Tree {
45 fn iter_helper<T>(&self, f: &mut impl FnMut(i32) -> ControlFlow<T>) -> ControlFlow<T> {
46 f(self.value)?;
47 for child in &self.children {
48 child.iter_helper(f)?;
49 }
50 ControlFlow::Continue(())
51 }
52}
53
54// now we can use InternalIterator facilities to construct iterator pipelines
55
56let tree = Tree {
57 value: 1,
58 children: vec![
59 Tree {
60 value: 2,
61 children: Vec::new(),
62 },
63 Tree {
64 value: 3,
65 children: vec![
66 Tree {
67 value: 4,
68 children: Vec::new(),
69 },
70 ]
71 },
72 ]
73};
74
75let result = tree
76 .map(|x| x * 2)
77 .filter(|&x| x > 3)
78 .flat_map(|x| [x, x * 10])
79 .collect::<Vec<_>>();
80
81assert_eq!(result, vec![4, 40, 6, 60, 8, 80]);
82```
83
84# Differences from `std::iter::Iterator`
85
86The main difference between `Iterator` and `InternalIterator` traits is that
87all methods in `InternalIterator` consume the iterators. While for regular
88iterators you can for example call `nth` and then keep using the iterator with
89remaining elements being untouched, you cannot do so with `InternalIterator`.
90This is a deliberate choice, as the goal of this library allow having a simpler
91iterator implementation without losing too much power. Regular iterators must
92keep state to be able to implement `next`, but state is not a hard requirement
93for internal iteration and requiring it would defeat the purpose of the library.
94
95Because internal iterators drive themselves instead of being driven by an
96outside called, some methods from `Iterator` are not possible to implement. The
97most prominent example is [`Iterator::zip`].
98
99# `nostd` compatibility
100
101This crate has two optional features:
102
103* `alloc` - includes `FromInternalIterator` and `IntoInternalIterator` impls
104for `String`, `Vec`, `BTreeMap`, and `BTreeSet`. Brings in a dependency on
105`alloc`.
106* `std` - includes `FromInternalIterator` and `IntoInternalIterator` impls for
107`HashSet` and `HashMap`. Brings in a dependency on `std`.
108
109Both of these features are enabled by default, but you can disable them if you
110are compiling without `std` or even without `alloc`."]
111
112#![cfg_attr(not(feature = "std"), no_std)]
113
114#![forbid(unsafe_code)]
115#![deny(missing_docs)]
116
117mod adaptors;
118mod from_fn_impl;
119
120#[cfg(feature = "alloc")]
121extern crate alloc;
122#[cfg(feature = "alloc")]
123mod alloc_impls;
124
125#[cfg(feature = "std")]
126mod std_impls;
127
128#[cfg(test)]
129mod tests;
130
131use core::cmp::Ordering;
132use core::ops::ControlFlow;
133pub use crate::adaptors::*;
134pub use crate::from_fn_impl::{FromFn, BreakValue, from_fn};
135
136/// Internal iterator over a collection.
137#[must_use = "internal iterators are lazy and do nothing unless consumed"]
138pub trait InternalIterator: Sized {
139 /// Type of items yielded by the iterator.
140 type Item;
141
142 /// Applies function each elements of the iterator. Stops early if the
143 /// function returns `ControlFlow::Break`.
144 ///
145 /// ```
146 /// # use internal_iterator::{InternalIterator, IteratorExt};
147 /// # use std::ops::ControlFlow;
148 /// let a = [1, 2, 3, 4, 5, 6];
149 /// let mut collected = Vec::new();
150 ///
151 /// let result = a.iter().into_internal().try_for_each(|&x| {
152 /// collected.push(x);
153 /// if x == 4 {
154 /// ControlFlow::Break("stopped!")
155 /// } else {
156 /// ControlFlow::Continue(())
157 /// }
158 /// });
159 ///
160 /// assert_eq!(collected, [1, 2, 3, 4]);
161 /// assert_eq!(result, ControlFlow::Break("stopped!"));
162 /// ```
163 fn try_for_each<R, F>(self, f: F) -> ControlFlow<R>
164 where
165 F: FnMut(Self::Item) -> ControlFlow<R>;
166
167 /// Applies function to the elements of iterator and returns the first
168 /// non-none result.
169 ///
170 /// ```
171 /// # use internal_iterator::{InternalIterator, IteratorExt};
172 /// let a = ["lol", "two", "NaN", "4", "5"];
173 ///
174 /// let parsed = a
175 /// .iter()
176 /// .into_internal()
177 /// .find_map(|x| x.parse().ok());
178 ///
179 /// assert_eq!(parsed, Some(4));
180 /// ```
181 fn find_map<R, F>(self, mut f: F) -> Option<R>
182 where
183 F: FnMut(Self::Item) -> Option<R>
184 {
185 let value = self.try_for_each(|item| {
186 if let Some(value) = f(item) {
187 ControlFlow::Break(value)
188 } else {
189 ControlFlow::Continue(())
190 }
191 });
192 match value {
193 ControlFlow::Continue(()) => None,
194 ControlFlow::Break(value) => Some(value),
195 }
196 }
197
198 /// Tests if every element of the iterator matches the predicate.
199 ///
200 /// ```
201 /// # use internal_iterator::{InternalIterator, IteratorExt};
202 /// let a = [1, 2, 3];
203 /// assert!(a.iter().into_internal().all(|&x| x > 0));
204 /// assert!(!a.iter().into_internal().all(|&x| x < 2));
205 /// ```
206 fn all<F>(self, mut f: F) -> bool
207 where
208 F: FnMut(Self::Item) -> bool,
209 {
210 self.find_map(|item| if f(item) { None } else { Some(()) }).is_none()
211 }
212
213 /// Tests if any element of the iterator matches the predicate.
214 ///
215 /// ```
216 /// # use internal_iterator::{InternalIterator, IteratorExt};
217 /// let a = [1, 2, 3];
218 /// assert!(a.iter().into_internal().any(|&x| x == 2));
219 /// assert!(!a.iter().into_internal().any(|&x| x > 5));
220 /// ```
221 fn any<F>(self, mut f: F) -> bool
222 where
223 F: FnMut(Self::Item) -> bool,
224 {
225 self.find_map(|item| if f(item) { Some(()) } else { None }).is_some()
226 }
227
228 /// Takes two iterators and returns an iterator that first iterates over the
229 /// elements of the first iterator, and then over the second one.
230 ///
231 /// ```
232 /// # use internal_iterator::{InternalIterator, IteratorExt};
233 /// let a1 = [1, 2, 3];
234 /// let a2 = [4, 5, 6];
235 ///
236 /// let chained = a1.iter().into_internal()
237 /// .chain(a2.iter().into_internal())
238 /// .collect::<Vec<_>>();
239 ///
240 /// assert_eq!(chained, vec![&1, &2, &3, &4, &5, &6]);
241 /// ```
242 fn chain<U>(self, other: U) -> Chain<Self, <U as IntoInternalIterator>::IntoIter>
243 where
244 U: IntoInternalIterator<Item = Self::Item>,
245 {
246 Chain { first: self, second: other.into_internal_iter() }
247 }
248
249 /// Creates an iterator yields cloned elements of the original iterator.
250 ///
251 /// ```
252 /// # use internal_iterator::{InternalIterator, IteratorExt};
253 /// let a = [1, 2, 3];
254 ///
255 /// let cloned = a.iter().into_internal().cloned().collect::<Vec<_>>();
256 ///
257 /// assert_eq!(cloned, vec![1, 2, 3]);
258 /// ```
259 fn cloned<'a, T: 'a>(self) -> Cloned<Self>
260 where
261 Self: InternalIterator<Item = &'a T>,
262 T: Clone,
263 {
264 Cloned { iter: self }
265 }
266
267 /// Transforms the iterator into a collection.
268 ///
269 /// ```
270 /// # use internal_iterator::{InternalIterator, IteratorExt};
271 /// let a = [1, 2, 3];
272 ///
273 /// let doubled = a
274 /// .iter()
275 /// .into_internal()
276 /// .map(|&x| x * 2)
277 /// .collect::<Vec<_>>();
278 ///
279 /// assert_eq!(doubled, vec![2, 4, 6]);
280 /// ```
281 fn collect<B>(self) -> B
282 where
283 B: FromInternalIterator<Self::Item>,
284 {
285 B::from_iter(self)
286 }
287
288 /// Creates an iterator yields copied elements of the original iterator.
289 ///
290 /// ```
291 /// # use internal_iterator::{InternalIterator, IteratorExt};
292 /// let a = [1, 2, 3];
293 ///
294 /// let cloned = a.iter().into_internal().copied().collect::<Vec<_>>();
295 ///
296 /// assert_eq!(cloned, vec![1, 2, 3]);
297 /// ```
298 fn copied<'a, T: 'a>(self) -> Copied<Self>
299 where
300 Self: InternalIterator<Item = &'a T>,
301 T: Copy,
302 {
303 Copied { iter: self }
304 }
305
306 /// Returns the number of elements yielded by the iterator.
307 ///
308 /// ```
309 /// # use internal_iterator::{InternalIterator, IteratorExt};
310 /// let a = [1, 2, 3];
311 ///
312 /// assert_eq!(a.iter().into_internal().count(), 3);
313 /// ```
314 fn count(self) -> usize {
315 let mut count = 0;
316 self.for_each(|_| count += 1);
317 count
318 }
319
320 // TODO: cycle
321
322 /// Creates an iterator that adds the index to every value of the original
323 /// iterator.
324 ///
325 /// ```
326 /// # use internal_iterator::{InternalIterator, IteratorExt};
327 /// let a = ['a', 'b', 'c'];
328 ///
329 /// let enumerated = a.iter().into_internal().enumerate().collect::<Vec<_>>();
330 ///
331 /// assert_eq!(enumerated, vec![(0, &'a'), (1, &'b'), (2, &'c')]);
332 /// ```
333 fn enumerate(self) -> Enumerate<Self> {
334 Enumerate { iter: self }
335 }
336
337 /// Creates an iterator which only yields elements matching the predicate.
338 ///
339 /// ```
340 /// # use internal_iterator::{InternalIterator, IteratorExt};
341 /// let a = [0i32, 1, 2];
342 ///
343 /// let positive = a.iter().into_internal().filter(|x| x.is_positive()).collect::<Vec<_>>();
344 ///
345 /// assert_eq!(positive, vec![&1, &2]);
346 /// ```
347 fn filter<P>(self, predicate: P) -> Filter<Self, P>
348 where
349 P: FnMut(&Self::Item) -> bool,
350 {
351 Filter { iter: self, predicate }
352 }
353
354 /// A combination of [`InternalIterator::filter`] and
355 /// [`InternalIterator::map`].
356 /// ```
357 /// # use internal_iterator::{InternalIterator, IteratorExt};
358 /// let a = ["1", "two", "NaN", "four", "5"];
359 ///
360 /// let parsed: Vec<_> = a
361 /// .iter()
362 /// .into_internal()
363 /// .filter_map(|x| x.parse::<i32>().ok())
364 /// .collect();
365 ///
366 /// assert_eq!(parsed, vec![1, 5]);
367 /// ```
368 fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
369 where
370 F: FnMut(Self::Item) -> Option<T>,
371 {
372 FilterMap { iter: self, f }
373 }
374
375 /// Returns the first element of the iterator that matches the predicate.
376 ///
377 /// ```
378 /// # use internal_iterator::{InternalIterator, IteratorExt};
379 /// let a = [1, 2, 3];
380 ///
381 /// assert_eq!(a.iter().into_internal().find(|&&x| x == 2), Some(&2));
382 ///
383 /// assert_eq!(a.iter().into_internal().find(|&&x| x == 5), None);
384 /// ```
385 fn find<F>(self, mut f: F) -> Option<Self::Item>
386 where
387 F: FnMut(&Self::Item) -> bool,
388 {
389 self.find_map(|item| {
390 if f(&item) {
391 Some(item)
392 } else {
393 None
394 }
395 })
396 }
397
398 /// Creates and iterator which maps over the elements and flattens the
399 /// resulting structure.
400 ///
401 /// The provided closure is expected to return a type implementing
402 /// [`IntoInternalIterator`]. The usual types that work with
403 /// [`std::iter::Iterator::flat_map`] don't work here, so you will need to
404 /// use [`IteratorExt::into_internal`] to use regular iterators with this
405 /// function.
406 ///
407 /// ```
408 /// # use internal_iterator::{InternalIterator, IteratorExt};
409 /// let a = [1, 2, 3];
410 ///
411 /// let mapped = a.iter()
412 /// .into_internal()
413 /// .flat_map(|&x| [x * 10 + 2, x * 10 + 3])
414 /// .collect::<Vec<_>>();
415 ///
416 /// assert_eq!(mapped, vec![12, 13, 22, 23, 32, 33]);
417 /// ```
418 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, F>
419 where
420 F: FnMut(Self::Item) -> U,
421 U: IntoInternalIterator,
422 {
423 FlatMap { iter: self, f }
424 }
425
426 // TODO: flatten
427
428 /// Folds every element into an accumulator by applying an operation, returning the final result.
429 ///
430 /// ```
431 /// # use internal_iterator::{InternalIterator, IntoInternalIterator};
432 /// let a = [1, 2, 3];
433 /// let sum = a.into_internal_iter().fold(0, |acc, x| acc + x);
434 /// assert_eq!(sum, 6);
435 /// ```
436 fn fold<B, F>(self, init: B, mut f: F) -> B
437 where
438 F: FnMut(B, Self::Item) -> B,
439 {
440 let mut acc = Some(init);
441 self.for_each(|item|
442 acc = acc.take().map(|acc| f(acc, item))
443 );
444 acc.unwrap()
445 }
446
447 /// Run the closure on each element.
448 fn for_each<F>(self, mut f: F)
449 where
450 F: FnMut(Self::Item)
451 {
452 self.try_for_each::<(), _>(|item| {
453 f(item);
454 ControlFlow::Continue(())
455 });
456 }
457
458 /// Run the closure on each element, while passing that element on.
459 ///
460 /// This can be used to inspect the values passed through the iterator
461 /// while not modifying the rest of the iterator pipeline.
462 ///
463 /// ```
464 /// # use internal_iterator::{InternalIterator, IteratorExt};
465 /// let a = [1, 4, 6, 3, 2];
466 ///
467 /// let v = a.iter()
468 /// .into_internal()
469 /// .filter(|&x| x % 2 == 0)
470 /// .inspect(|x| println!("item: {}", x))
471 /// .map(|x| x / 2)
472 /// .collect::<Vec<_>>();
473 ///
474 /// assert_eq!(v, vec![2, 3, 1]);
475 /// // also prints to stdout:
476 /// // item: 4
477 /// // item: 6
478 /// // item: 2
479 /// ```
480 fn inspect<F>(self, f: F) -> Inspect<Self, F>
481 where
482 F: FnMut(&Self::Item)
483 {
484 Inspect { iter: self, f }
485 }
486
487 /// Returns the last element.
488 ///
489 /// ```
490 /// # use internal_iterator::{InternalIterator, IteratorExt};
491 /// let a = [1, 2, 3];
492 /// assert_eq!(a.iter().into_internal().last(), Some(&3));
493 ///
494 /// let a = [1, 2, 3, 4, 5];
495 /// assert_eq!(a.iter().into_internal().last(), Some(&5));
496 /// ```
497 fn last(self) -> Option<Self::Item> {
498 let mut last = None;
499 self.for_each(|item| last = Some(item));
500 last
501 }
502
503 /// Transform each element in the iterator.
504 ///
505 /// ```
506 /// # use internal_iterator::{InternalIterator, IteratorExt};
507 /// let a = [1, 2, 3];
508 ///
509 /// let doubled = a
510 /// .iter()
511 /// .into_internal()
512 /// .map(|&x| x * 2)
513 /// .collect::<Vec<_>>();
514 ///
515 /// assert_eq!(doubled, vec![2, 4, 6]);
516 /// ```
517 fn map<F, T>(self, f: F) -> Map<Self, F>
518 where
519 F: FnMut(Self::Item) -> T,
520 {
521 Map { iter: self, f }
522 }
523
524 /// Returns the maximum element of an iterator.
525 ///
526 /// ```
527 /// # use internal_iterator::{InternalIterator, IteratorExt};
528 /// let a = [1, 2, 3];
529 /// let b: Vec<u32> = Vec::new();
530 ///
531 /// assert_eq!(a.iter().into_internal().max(), Some(&3));
532 /// assert_eq!(b.iter().into_internal().max(), None);
533 /// ```
534 fn max(self) -> Option<Self::Item>
535 where
536 Self::Item: Ord,
537 {
538 self.max_by(Ord::cmp)
539 }
540
541 /// Returns the maximum element of an iterator using a custom comparer
542 /// function.
543 fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
544 where
545 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
546 {
547 let mut max = None;
548 self.for_each(|item| {
549 match max.take() {
550 None => max = Some(item),
551 Some(i) => {
552 max = Some(max_by(item, i, &mut compare));
553 }
554 }
555 });
556 max
557 }
558
559 /// Returns the element that gives the maximum value from the specified function.
560 fn max_by_key<B: Ord>(self, mut key: impl FnMut(&Self::Item) -> B) -> Option<Self::Item> {
561 self.map(|x| (key(&x), x))
562 .max_by(|(kx, _), (ky, _)| kx.cmp(ky))
563 .map(|(_, x)| x)
564 }
565
566 /// Returns the minimum element of an iterator.
567 ///
568 /// ```
569 /// # use internal_iterator::{InternalIterator, IteratorExt};
570 /// let a = [1, 2, 3];
571 /// let b: Vec<u32> = Vec::new();
572 ///
573 /// assert_eq!(a.iter().into_internal().min(), Some(&1));
574 /// assert_eq!(b.iter().into_internal().min(), None);
575 /// ```
576 fn min(self) -> Option<Self::Item>
577 where
578 Self::Item: Ord,
579 {
580 self.min_by(Ord::cmp)
581 }
582
583 /// Returns the minimum element of an iterator using a custom comparer
584 /// function.
585 fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
586 where
587 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
588 {
589 let mut min = None;
590 self.for_each(|item| {
591 match min.take() {
592 None => min = Some(item),
593 Some(i) => {
594 min = Some(min_by(item, i, &mut compare));
595 }
596 }
597 });
598 min
599 }
600
601 /// Returns the element that gives the minimum value from the specified function.
602 fn min_by_key<B: Ord>(self, mut key: impl FnMut(&Self::Item) -> B) -> Option<Self::Item> {
603 self.map(|x| (key(&x), x))
604 .min_by(|(kx, _), (ky, _)| kx.cmp(ky))
605 .map(|(_, x)| x)
606 }
607
608 /// Returns the first element of the iterator.
609 ///
610 /// Note that unlike [`Iterator::next`], this method consumes the iterator.
611 /// It is really only useful for getting the first element in the iterator,
612 /// and is called `next` just for api similarity with regular iterators.
613 ///
614 /// ```
615 /// # use internal_iterator::{InternalIterator, IteratorExt};
616 /// let a = [1, 2, 3];
617 /// assert_eq!(a.iter().into_internal().next(), Some(&1));
618 /// ```
619 fn next(self) -> Option<Self::Item> {
620 self.find_map(Some)
621 }
622
623 /// Returns the `n`th element of the iterator.
624 ///
625 /// ```
626 /// # use internal_iterator::{InternalIterator, IteratorExt};
627 /// let a = [1, 2, 3];
628 /// assert_eq!(a.iter().into_internal().nth(1), Some(&2));
629 /// ```
630 fn nth(self, mut n: usize) -> Option<Self::Item> {
631 self.find_map(|item| {
632 if n == 0 {
633 Some(item)
634 } else {
635 n -= 1;
636 None
637 }
638 })
639 }
640
641 /// Returns the index of the first element matching the predicate.
642 ///
643 /// ```
644 /// # use internal_iterator::{InternalIterator, IteratorExt};
645 /// let a = [1, 2, 3];
646 ///
647 /// assert_eq!(a.iter().into_internal().position(|&x| x == 2), Some(1));
648 ///
649 /// assert_eq!(a.iter().into_internal().position(|&x| x == 5), None);
650 /// ```
651 fn position<F>(self, mut f: F) -> Option<usize>
652 where
653 F: FnMut(Self::Item) -> bool,
654 {
655 self.enumerate().find_map(|(idx, item)| {
656 if f(item) {
657 Some(idx)
658 } else {
659 None
660 }
661 })
662 }
663
664 // TODO: product
665
666 // TODO: scan
667
668 /// Skip first `n` elements of the iterator.
669 ///
670 /// ```
671 /// # use internal_iterator::{InternalIterator, IteratorExt};
672 /// let a = [1, 2, 3, 4];
673 ///
674 /// let v = a.iter().into_internal().skip(2).collect::<Vec<_>>();
675 ///
676 /// assert_eq!(v, vec![&3, &4]);
677 /// ```
678 fn skip(self, n: usize) -> Skip<Self> {
679 Skip { iter: self, n }
680 }
681
682 // TODO: skip_while
683
684 // TODO: step_by
685
686 // TODO: sum
687
688 /// Take first `n` elements of the iterator, disregarding the rest.
689 ///
690 /// ```
691 /// # use internal_iterator::{InternalIterator, IteratorExt};
692 /// let a = [1, 2, 3, 4];
693 ///
694 /// let v = a.iter().into_internal().take(2).collect::<Vec<_>>();
695 ///
696 /// assert_eq!(v, vec![&1, &2]);
697 /// ```
698 fn take(self, n: usize) -> Take<Self> {
699 Take { iter: self, n }
700 }
701
702 // TODO: take_while
703
704 // TODO: try_find
705
706 // TODO: try_fold
707
708 // TODO: unzip
709}
710
711/// Conversion to an [`InternalIterator`].
712///
713/// This is internal-iterator equivalent of [`std::iter::IntoIterator`].
714pub trait IntoInternalIterator {
715 /// The type of the elements being iterated over.
716 type Item;
717 /// Concrete iterator type returned by the conversion.
718 type IntoIter: InternalIterator<Item = Self::Item>;
719
720 /// Convert this type to an internal iterator.
721 fn into_internal_iter(self) -> Self::IntoIter;
722}
723
724impl<I> IntoInternalIterator for I
725where
726 I: InternalIterator,
727{
728 type Item = I::Item;
729
730 type IntoIter = I;
731
732 fn into_internal_iter(self) -> Self::IntoIter {
733 self
734 }
735}
736
737macro_rules! into_internal_impls {
738 ($([$($generics:tt)*] $ty:ty,)*) => {
739 $(
740 impl<$($generics)*> IntoInternalIterator for $ty {
741 type Item = <$ty as IntoIterator>::Item;
742 type IntoIter = crate::Internal<<$ty as IntoIterator>::IntoIter>;
743 fn into_internal_iter(self) -> Self::IntoIter {
744 self.into_iter().into_internal()
745 }
746 }
747 )*
748 }
749}
750
751pub(crate) use into_internal_impls;
752
753into_internal_impls! {
754 ['a, T] &'a [T],
755 ['a, T] &'a mut [T],
756 ['a, T, const N: usize] &'a [T; N],
757 ['a, T, const N: usize] &'a mut [T; N],
758 [T, const N: usize] [T; N],
759 ['a, T] &'a Option<T>,
760 ['a, T] &'a mut Option<T>,
761 [T] Option<T>,
762 ['a, T, E] &'a Result<T, E>,
763 ['a, T, E] &'a mut Result<T, E>,
764 [T, E] Result<T, E>,
765}
766
767/// Extension trait to add conversion to [`InternalIterator`] for regular
768/// iterators.
769pub trait IteratorExt: IntoIterator {
770 /// Convert an [`std::iter::Iterator`] to an [`InternalIterator`].
771 ///
772 /// Composing internal iterators together requires all used iterators to be
773 /// internal iterators. Given that regular iterators are far more prevalent,
774 /// this function can be used to allow them to be used together with
775 /// internal iterators.
776 ///
777 /// ```
778 /// # use internal_iterator::InternalIterator;use internal_iterator::IteratorExt;
779 ///
780 /// fn flatten_ranges(
781 /// ranges: impl InternalIterator<Item = (i32, i32)>,
782 /// ) -> impl InternalIterator<Item = i32> {
783 /// ranges.flat_map(|(from, to)| (from..to).into_internal())
784 /// }
785 fn into_internal(self) -> Internal<Self::IntoIter>
786 where
787 Self: Sized,
788 {
789 Internal { iterator: self.into_iter() }
790 }
791}
792
793impl<I: IntoIterator> IteratorExt for I {}
794
795/// Conversion from an [`InternalIterator`].
796///
797/// This is internal-iterator equivalent of [`std::iter::FromIterator`].
798pub trait FromInternalIterator<A> {
799 /// Convert from an iterator.
800 fn from_iter<T>(iter: T) -> Self
801 where
802 T: IntoInternalIterator<Item = A>;
803}
804
805impl<C, R, E> FromInternalIterator<Result<R, E>> for Result<C, E>
806where
807 C: FromInternalIterator<R>,
808{
809 fn from_iter<T>(iter: T) -> Self
810 where
811 T: IntoInternalIterator<Item = Result<R, E>>
812 {
813 let mut error = None;
814 let c = C::from_iter(iter
815 .into_internal_iter()
816 // FIXME: this could stop on first Err
817 .filter_map(|r| match r {
818 Ok(v) => Some(v),
819 Err(e) => {
820 error = Some(e);
821 None
822 }
823 }));
824 match error {
825 Some(err) => Err(err),
826 None => Ok(c),
827 }
828 }
829}
830
831fn max_by<A, C: FnMut(&A, &A) -> Ordering>(x: A, y: A, mut compare: C) -> A {
832 match compare(&x, &y) {
833 Ordering::Less => y,
834 Ordering::Equal |
835 Ordering::Greater => x,
836 }
837}
838
839fn min_by<A, C: FnMut(&A, &A) -> Ordering>(x: A, y: A, mut compare: C) -> A {
840 match compare(&x, &y) {
841 Ordering::Less |
842 Ordering::Equal => x,
843 Ordering::Greater => y,
844 }
845}