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
//! A Rust iterator extension trait to extend iterators with a new method called
//! `with_position` which makes it easier to handle an element being the first,
//! last, middle or only element in an iteration. It is similar to a method in
//! itertools with the same name, but with a slightly different API, which IMO is
//! a bit easier to use.
//!
//! # Example
//!
//! ```
//! use with_position::{WithPosition, Position};
//!
//! let result: Vec<_> = vec![1,2,3].into_iter().with_position().collect();
//!
//! assert_eq!(result[0], (Position::First, 1));
//! assert_eq!(result[1], (Position::Middle, 2));
//! assert_eq!(result[2], (Position::Last, 3));
//!
//! assert_eq!(result[0].0.is_first(), true);
//! assert_eq!(result[1].0.is_first(), false);
//! ```

use std::iter::Peekable;
use std::cell::Cell;

/// An enum which indicates the position of an item in an iteration.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Position {
    First,
    Middle,
    Last,
    Only,
}

impl Position {
    pub fn is_first(self) -> bool {
        self == Position::First || self == Position::Only
    }

    pub fn is_last(self) -> bool {
        self == Position::Last || self == Position::Only
    }

    pub fn is_only(self) -> bool {
        self == Position::Only
    }
}

/// An iterator adapter that yields tuples where the first element is a Position
/// and the second is the item.
pub struct PositionIterator<T> where T: Iterator {
    iter: Peekable<T>,
    did_iter: Cell<bool>,
}

impl<T> Iterator for PositionIterator<T> where T: Iterator {
    type Item = (Position, T::Item);

    fn next(&mut self) -> Option<Self::Item> {
        let is_first = self.did_iter.get();
        self.did_iter.set(true);

        let next = match self.iter.next() {
            Some(item) => item,
            None => return None,
        };

        if is_first {
            match self.iter.peek() {
                Some(_) => Some((Position::Middle, next)),
                None => Some((Position::Last, next)),
            }
        } else {
            match self.iter.peek() {
                Some(_) => Some((Position::First, next)),
                None => Some((Position::Only, next)),
            }
        }
    }
}

/// Extension trait for iterators which adds the `with_position` method
pub trait WithPosition where {
    type Iterator: Iterator;

    /// Yield a tuple of `(Position, item)` where position indicates whether this
    /// is the first, middle or last item.
    fn with_position(self) -> PositionIterator<Self::Iterator>;
}

impl<T> WithPosition for T where T: Iterator {
    type Iterator = T;

    fn with_position(self) -> PositionIterator<T> {
        PositionIterator { iter: self.peekable(), did_iter: Cell::new(false) }
    }
}

#[cfg(test)]
mod tests {
    use super::{WithPosition, Position};

    #[test]
    fn it_marks_first_middle_and_last_position() {
        let result: Vec<_> = vec![1,2,3,4].into_iter().with_position().collect();

        assert_eq!(result[0], (Position::First, 1));
        assert_eq!(result[1], (Position::Middle, 2));
        assert_eq!(result[2], (Position::Middle, 3));
        assert_eq!(result[3], (Position::Last, 4));
    }

    #[test]
    fn it_marks_first_and_last_position() {
        let result: Vec<_> = vec![1,4].into_iter().with_position().collect();

        assert_eq!(result[0], (Position::First, 1));
        assert_eq!(result[1], (Position::Last, 4));
    }

    #[test]
    fn it_marks_only_position() {
        let result: Vec<_> = vec![2].into_iter().with_position().collect();

        assert_eq!(result[0], (Position::Only, 2));
    }

    #[test]
    fn it_has_boolean_methods_on_position() {
        assert_eq!(Position::First.is_first(), true);
        assert_eq!(Position::Middle.is_first(), false);
        assert_eq!(Position::Last.is_first(), false);
        assert_eq!(Position::Only.is_first(), true);

        assert_eq!(Position::First.is_last(), false);
        assert_eq!(Position::Middle.is_last(), false);
        assert_eq!(Position::Last.is_last(), true);
        assert_eq!(Position::Only.is_last(), true);

        assert_eq!(Position::First.is_only(), false);
        assert_eq!(Position::Middle.is_only(), false);
        assert_eq!(Position::Last.is_only(), false);
        assert_eq!(Position::Only.is_only(), true);
    }
}