Skip to content

Commit

Permalink
Test with non-fused iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
timvermeulen committed Oct 5, 2020
1 parent bcacfe1 commit 1d27a50
Showing 1 changed file with 41 additions and 4 deletions.
45 changes: 41 additions & 4 deletions library/core/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,43 @@ use core::cell::Cell;
use core::convert::TryFrom;
use core::iter::*;

/// An iterator wrapper that panics whenever `next` or `next_back` is called
/// after `None` has been returned.
struct Unfuse<I> {
iter: I,
exhausted: bool,
}

fn unfuse<I: IntoIterator>(iter: I) -> Unfuse<I::IntoIter> {
Unfuse { iter: iter.into_iter(), exhausted: false }
}

impl<I> Iterator for Unfuse<I>
where
I: Iterator,
{
type Item = I::Item;

fn next(&mut self) -> Option<Self::Item> {
assert!(!self.exhausted);
let next = self.iter.next();
self.exhausted = next.is_none();
next
}
}

impl<I> DoubleEndedIterator for Unfuse<I>
where
I: DoubleEndedIterator,
{
fn next_back(&mut self) -> Option<Self::Item> {
assert!(!self.exhausted);
let next = self.iter.next_back();
self.exhausted = next.is_none();
next
}
}

#[test]
fn test_lt() {
let empty: [isize; 0] = [];
Expand Down Expand Up @@ -148,14 +185,14 @@ fn test_iterator_chain_advance_by() {
let len = xs.len() + ys.len();

for i in 0..xs.len() {
let mut iter = xs.iter().chain(ys);
let mut iter = unfuse(xs).chain(unfuse(ys));
iter.advance_by(i).unwrap();
assert_eq!(iter.next(), Some(&xs[i]));
assert_eq!(iter.advance_by(100), Err(len - i - 1));
}

for i in 0..ys.len() {
let mut iter = xs.iter().chain(ys);
let mut iter = unfuse(xs).chain(unfuse(ys));
iter.advance_by(xs.len() + i).unwrap();
assert_eq!(iter.next(), Some(&ys[i]));
assert_eq!(iter.advance_by(100), Err(ys.len() - i - 1));
Expand All @@ -181,14 +218,14 @@ fn test_iterator_chain_advance_back_by() {
let len = xs.len() + ys.len();

for i in 0..ys.len() {
let mut iter = xs.iter().chain(ys);
let mut iter = unfuse(xs).chain(unfuse(ys));
iter.advance_back_by(i).unwrap();
assert_eq!(iter.next_back(), Some(&ys[ys.len() - i - 1]));
assert_eq!(iter.advance_back_by(100), Err(len - i - 1));
}

for i in 0..xs.len() {
let mut iter = xs.iter().chain(ys);
let mut iter = unfuse(xs).chain(unfuse(ys));
iter.advance_back_by(ys.len() + i).unwrap();
assert_eq!(iter.next_back(), Some(&xs[xs.len() - i - 1]));
assert_eq!(iter.advance_back_by(100), Err(xs.len() - i - 1));
Expand Down

0 comments on commit 1d27a50

Please sign in to comment.