Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cordyceps): add ExactSizeIterator, IterMut #208

Merged
merged 3 commits into from
Jun 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 136 additions & 9 deletions cordyceps/src/list.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! An intrusive doubly-linked list.
//!
//! See the [`List`] type for details.

use super::Linked;
use crate::util::FmtOption;
use core::{
Expand Down Expand Up @@ -224,14 +225,32 @@ pub struct Links<T: ?Sized> {
///
/// This is similar to a mutable iterator (and implements the [`Iterator`]
/// trait), but it also permits modification to the list itself.
pub struct Cursor<'a, T: Linked<Links<T>> + ?Sized> {
list: &'a mut List<T>,
pub struct Cursor<'list, T: Linked<Links<T>> + ?Sized> {
list: &'list mut List<T>,
curr: Link<T>,
len: usize,
}

/// Iterates over the items in a [`List`] by reference.
pub struct Iter<'a, T: Linked<Links<T>> + ?Sized> {
_list: &'a List<T>,
pub struct Iter<'list, T: Linked<Links<T>> + ?Sized> {
_list: &'list List<T>,

/// The current node when iterating head -> tail.
curr: Link<T>,

/// The current node when iterating tail -> head.
///
/// This is used by the [`DoubleEndedIterator`] impl.
curr_back: Link<T>,

/// The number of remaining entries in the iterator.
len: usize,
}

/// Iterates over the items in a [`List`] by mutable reference.
pub struct IterMut<'list, T: Linked<Links<T>> + ?Sized> {
_list: &'list mut List<T>,

/// The current node when iterating head -> tail.
curr: Link<T>,

Expand Down Expand Up @@ -493,9 +512,11 @@ impl<T: Linked<Links<T>> + ?Sized> List<T> {
/// inserting or removing elements at the cursor's current position.
#[must_use]
pub fn cursor(&mut self) -> Cursor<'_, T> {
let len = self.len();
Cursor {
curr: self.head,
list: self,
len,
}
}

Expand All @@ -509,6 +530,20 @@ impl<T: Linked<Links<T>> + ?Sized> List<T> {
len: self.len(),
}
}

/// Returns an iterator over the items in this list, by mutable reference.
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
let curr = self.head;
let curr_back = self.tail;
let len = self.len();
IterMut {
_list: self,
curr,
curr_back,
len,
}
}
}

unsafe impl<T: Linked<Links<T>> + ?Sized> Send for List<T> where T: Send {}
Expand All @@ -523,6 +558,26 @@ impl<T: Linked<Links<T>> + ?Sized> fmt::Debug for List<T> {
}
}

impl<'list, T: Linked<Links<T>> + ?Sized> IntoIterator for &'list List<T> {
type Item = &'list T;
type IntoIter = Iter<'list, T>;

#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}

impl<'list, T: Linked<Links<T>> + ?Sized> IntoIterator for &'list mut List<T> {
type Item = &'list mut T;
type IntoIter = IterMut<'list, T>;

#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}

impl<T: Linked<Links<T>> + ?Sized> Drop for List<T> {
fn drop(&mut self) {
while let Some(node) = self.pop_front() {
Expand Down Expand Up @@ -678,6 +733,11 @@ impl<'a, T: Linked<Links<T>> + ?Sized> Iterator for Cursor<'a, T> {
ptr.as_mut()
})
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
}
}

impl<'a, T: Linked<Links<T>> + ?Sized> Cursor<'a, T> {
Expand Down Expand Up @@ -709,12 +769,11 @@ impl<'a, T: Linked<Links<T>> + ?Sized> Cursor<'a, T> {
}
}

// TODO(eliza): next_back

// === impl Iter ====

impl<'a, T: Linked<Links<T>> + ?Sized> Iterator for Iter<'a, T> {
type Item = &'a T;
impl<'list, T: Linked<Links<T>> + ?Sized> Iterator for Iter<'list, T> {
type Item = &'list T;

fn next(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
Expand All @@ -731,9 +790,22 @@ impl<'a, T: Linked<Links<T>> + ?Sized> Iterator for Iter<'a, T> {
Some(curr.as_ref())
}
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}

impl<'list, T: Linked<Links<T>> + ?Sized> ExactSizeIterator for Iter<'list, T> {
#[inline]
fn len(&self) -> usize {
self.len
}
}

impl<'a, T: Linked<Links<T>> + ?Sized> DoubleEndedIterator for Iter<'a, T> {
impl<'list, T: Linked<Links<T>> + ?Sized> DoubleEndedIterator for Iter<'list, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
Expand All @@ -751,3 +823,58 @@ impl<'a, T: Linked<Links<T>> + ?Sized> DoubleEndedIterator for Iter<'a, T> {
}
}
}

// === impl IterMut ====

impl<'list, T: Linked<Links<T>> + ?Sized> Iterator for IterMut<'list, T> {
type Item = &'list mut T;

fn next(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
}

let mut curr = self.curr.take()?;
self.len -= 1;
unsafe {
// safety: it is safe for us to borrow `curr`, because the iterator
// borrows the `List`, ensuring that the list will not be dropped
// while the iterator exists. the returned item will not outlive the
// iterator.
self.curr = T::links(curr).as_ref().next();
Some(curr.as_mut())
}
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}

impl<'list, T: Linked<Links<T>> + ?Sized> ExactSizeIterator for IterMut<'list, T> {
#[inline]
fn len(&self) -> usize {
self.len
}
}

impl<'list, T: Linked<Links<T>> + ?Sized> DoubleEndedIterator for IterMut<'list, T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
}

let mut curr = self.curr_back.take()?;
self.len -= 1;
unsafe {
// safety: it is safe for us to borrow `curr`, because the iterator
// borrows the `List`, ensuring that the list will not be dropped
// while the iterator exists. the returned item will not outlive the
// iterator.
self.curr_back = T::links(curr).as_ref().prev();
Some(curr.as_mut())
}
}
}
56 changes: 56 additions & 0 deletions cordyceps/src/list/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,62 @@ mod owned_entry {
i += 1;
}
}

// These tests don't work with the borrowed entry type, because we mutate
// entries through the iterator

#[test]
fn double_ended_iter_mut() {
let a = owned_entry(1);
let b = owned_entry(2);
let c = owned_entry(3);
fn incr_entry(entry: &mut OwnedEntry) -> i32 {
entry.val += 1;
entry.val
}

let mut list = List::new();

list.push_back(a);
list.push_back(b);
list.push_back(c);

let head_to_tail = list.iter_mut().map(incr_entry).collect::<Vec<_>>();
assert_eq!(&head_to_tail, &[2, 3, 4]);

let tail_to_head = list.iter_mut().rev().map(incr_entry).collect::<Vec<_>>();
assert_eq!(&tail_to_head, &[5, 4, 3]);
}

/// Per the double-ended iterator docs:
///
/// > It is important to note that both back and forth work on the same range,
/// > and do not cross: iteration is over when they meet in the middle.
#[test]
fn double_ended_iter_mut_empties() {
let a = owned_entry(1);
let b = owned_entry(2);
let c = owned_entry(3);
let d = owned_entry(4);

let mut list = List::<OwnedEntry>::new();

list.push_back(a);
list.push_back(b);
list.push_back(c);
list.push_back(d);

let mut iter = list.iter_mut();

assert_eq!(iter.next().map(|entry| entry.val), Some(1));
assert_eq!(iter.next().map(|entry| entry.val), Some(2));

assert_eq!(iter.next_back().map(|entry| entry.val), Some(4));
assert_eq!(iter.next_back().map(|entry| entry.val), Some(3));

assert_eq!(iter.next().map(|entry| entry.val), None);
assert_eq!(iter.next_back().map(|entry| entry.val), None);
}
}

// #[test]
Expand Down