3

I built an iterator that generates an infinite list of primes. The types look like this:

pub struct Primes { … }

impl Iterator for Primes {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> { … }
}

Now I want to test if my iterator returns the correct values by comparing the first 100 values against the correct ones:

#[test]
fn first_thousand() {
    assert_eq!(
        Primes::new().take(100),
        first_100_primes
    );
}

const first_100_primes: [u32; 100] = [2, 3, …, 541];

I do not know how to compare these values. I tried creating a slice (first_100_primes[..]), collecting the iterator values, but I don't seem to be able to compare them.

Sebastian
  • 313
  • 1
  • 15
  • Unfortunately, the IntoIterator trait is only defined for `[T; N]` if `N <= 32`. So I believe it is not the same as comparing iterators. – Sebastian May 13 '16 at 16:08
  • See also [Is there a built-in way to compare two Iterators?](http://stackoverflow.com/q/30540822/155423) – Shepmaster May 13 '16 at 16:23
  • `IntoIterator` isn't implemented for *any* array, perhaps you meant something else? Either way, you [can get an iterator of the expected values](https://play.rust-lang.org/?gist=253547197eb8e7d678a8395602442cf2&version=stable&backtrace=0). – Shepmaster May 13 '16 at 16:28

2 Answers2

3
let is_correct = Primes::new()
    .zip(FIRST_100_PRIMES.iter())
    .all(|(a, &b)| a == b);
assert!(is_correct);
A.B.
  • 15,364
  • 3
  • 61
  • 64
2

Turns out I was really close, I believe this works:

#[test]
fn first_thousand() {
    assert_eq!(
        FIRST_100_PRIMES[..],
        Primes::new().take(100).collect::<Vec<_>>()[..]
    );
}

(Although I'm not sure if this is the rustacean way of doing it...)

Sebastian
  • 313
  • 1
  • 15