1use std::fmt;
2use std::iter::{Fuse, FusedIterator, Peekable};
34/// An iterator adaptor that wraps each element in an [`Position`].
5///
6/// Iterator element type is `(Position, I::Item)`.
7///
8/// See [`.with_position()`](crate::Itertools::with_position) for more information.
9#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
10pub struct WithPosition<I>
11where
12I: Iterator,
13{
14 handled_first: bool,
15 peekable: Peekable<Fuse<I>>,
16}
1718impl<I> fmt::Debug for WithPosition<I>
19where
20I: Iterator,
21 Peekable<Fuse<I>>: fmt::Debug,
22{
23debug_fmt_fields!(WithPosition, handled_first, peekable);
24}
2526impl<I> Clone for WithPosition<I>
27where
28I: Clone + Iterator,
29 I::Item: Clone,
30{
31clone_fields!(handled_first, peekable);
32}
3334/// Create a new `WithPosition` iterator.
35pub fn with_position<I>(iter: I) -> WithPosition<I>
36where
37I: Iterator,
38{
39 WithPosition {
40 handled_first: false,
41 peekable: iter.fuse().peekable(),
42 }
43}
4445/// The first component of the value yielded by `WithPosition`.
46/// Indicates the position of this element in the iterator results.
47///
48/// See [`.with_position()`](crate::Itertools::with_position) for more information.
49#[derive(Copy, Clone, Debug, PartialEq, Eq)]
50pub enum Position {
51/// This is the first element.
52First,
53/// This is neither the first nor the last element.
54Middle,
55/// This is the last element.
56Last,
57/// This is the only element.
58Only,
59}
6061impl<I: Iterator> Iterator for WithPosition<I> {
62type Item = (Position, I::Item);
6364fn next(&mut self) -> Option<Self::Item> {
65match self.peekable.next() {
66Some(item) => {
67if !self.handled_first {
68// Haven't seen the first item yet, and there is one to give.
69self.handled_first = true;
70// Peek to see if this is also the last item,
71 // in which case tag it as `Only`.
72match self.peekable.peek() {
73Some(_) => Some((Position::First, item)),
74None => Some((Position::Only, item)),
75 }
76 } else {
77// Have seen the first item, and there's something left.
78 // Peek to see if this is the last item.
79match self.peekable.peek() {
80Some(_) => Some((Position::Middle, item)),
81None => Some((Position::Last, item)),
82 }
83 }
84 }
85// Iterator is finished.
86None => None,
87 }
88 }
8990fn size_hint(&self) -> (usize, Option<usize>) {
91self.peekable.size_hint()
92 }
9394fn fold<B, F>(mut self, mut init: B, mut f: F) -> B
95where
96F: FnMut(B, Self::Item) -> B,
97 {
98if let Some(mut head) = self.peekable.next() {
99if !self.handled_first {
100// The current head is `First` or `Only`,
101 // it depends if there is another item or not.
102match self.peekable.next() {
103Some(second) => {
104let first = std::mem::replace(&mut head, second);
105 init = f(init, (Position::First, first));
106 }
107None => return f(init, (Position::Only, head)),
108 }
109 }
110// Have seen the first item, and there's something left.
111init = self.peekable.fold(init, |acc, mut item| {
112 std::mem::swap(&mut head, &mut item);
113 f(acc, (Position::Middle, item))
114 });
115// The "head" is now the last item.
116init = f(init, (Position::Last, head));
117 }
118 init
119 }
120}
121122impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator {}
123124impl<I: Iterator> FusedIterator for WithPosition<I> {}