diff --git a/src/lib.rs b/src/lib.rs index e764b27..ab1e445 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -62,6 +62,12 @@ pub type Iter<'a, T> = Chain>, Rev>>; /// A mutable iterator over `CircularQueue`. pub type IterMut<'a, T> = Chain>, Rev>>; +/// An ascending iterator over `CircularQueue`. +pub type AscIter<'a, T> = Chain, SliceIter<'a, T>>; + +/// An mutable ascending iterator over `CircularQueue`. +pub type AscIterMut<'a, T> = Chain, SliceIterMut<'a, T>>; + impl CircularQueue { /// Constructs a new, empty `CircularQueue` with the requested capacity. /// @@ -185,6 +191,7 @@ impl CircularQueue { /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), Some(&2)); /// ``` + #[inline] pub fn push(&mut self, x: T) { if self.data.len() < self.capacity() { self.data.push(x); @@ -248,6 +255,60 @@ impl CircularQueue { let (a, b) = self.data.split_at_mut(self.insertion_index); a.iter_mut().rev().chain(b.iter_mut().rev()) } + + /// Returns an ascending iterator over the queue's contents. + /// + /// The iterator goes from the least recently pushed items to the newest ones. + /// + /// # Examples + /// + /// ``` + /// use circular_queue::CircularQueue; + /// + /// let mut queue = CircularQueue::with_capacity(3); + /// queue.push(1); + /// queue.push(2); + /// queue.push(3); + /// queue.push(4); + /// + /// let mut iter = queue.asc_iter(); + /// + /// assert_eq!(iter.next(), Some(&2)); + /// assert_eq!(iter.next(), Some(&3)); + /// assert_eq!(iter.next(), Some(&4)); + /// ``` + #[inline] + pub fn asc_iter(&self) -> AscIter { + let (a, b) = self.data.split_at(self.insertion_index); + b.iter().chain(a.iter()) + } + + /// Returns a mutable ascending iterator over the queue's contents. + /// + /// The iterator goes from the least recently pushed items to the newest ones. + /// + /// # Examples + /// + /// ``` + /// use circular_queue::CircularQueue; + /// + /// let mut queue = CircularQueue::with_capacity(3); + /// queue.push(1); + /// queue.push(2); + /// queue.push(3); + /// queue.push(4); + /// + /// let mut iter = queue.asc_iter_mut(); + /// + /// assert_eq!(iter.next(), Some(&mut 2)); + /// assert_eq!(iter.next(), Some(&mut 3)); + /// assert_eq!(iter.next(), Some(&mut 4)); + /// ``` + #[inline] + pub fn asc_iter_mut(&mut self) -> AscIterMut { + let (a, b) = self.data.split_at_mut(self.insertion_index); + b.iter_mut().chain(a.iter_mut()) + } } impl PartialEq for CircularQueue {