I'm trying to write an iterator that generates primes forever, but I'm running into stack overflow and performance issues.

Here's what I have:

```
fn primes() -> Sieve {
Sieve {
iter: Some(Box::new(2..)),
}
}
struct Sieve {
iter: Option<Box<dyn Iterator<Item = u32>>>,
}
impl Iterator for Sieve {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
// Option used to take ownership out of &mut Self
let mut iter = self.iter.take()?;
let prime = iter.next()?;
self.iter = Some(Box::new(iter.filter(move |n| n % prime != 0)));
Some(prime)
}
}
#[test]
fn generate_first_10() {
let first_10: Vec<u32> = primes().take(10).collect();
assert_eq!(first_10, vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
}
```

Here's the "Python pseudo code", it's essentially the Sieve of Eratosthenes, but it's powered by an infinite number generator instead of a fixed Vec, and each number gets filtered away if it's divisible by a past prime:

```
import itertools
def sieve():
yield from _sieve(itertools.count(2))
def _sieve(numbers):
p = next(numbers)
yield p
yield from _sieve(n for n in numbers if n % p != 0)
```

The Python code is obviously recursive and hits the recursion limit very quickly (right after 3557), but the Rust code isn't recursive, and for the life of me I can't figure out why I'm getting a stack overflow panic while trying to do `for p in primes() { println!("{}", p); }`

(curiously it varies where it gives up on life, but always in the 338000s on my Linux machine).

The other issue is performance, where a sloppily written Vec based sieve implementation is over 2000x faster for generating primes up to 338000. I have a feeling it's the many Box::new() allocations, but I don't know how to start profiling this. Could this be pre-allocated/amortized somehow? Is there a way to use generics/monomorphization? Is there some unsafe magic I could be using? Are the unreleased generators what I'm looking for? I don't want to give up this idea just yet.

I'm a little stuck, all insights would be very helpful

FYI, I'm intending to use this for competitive programming (great for lazily finding prime factors for example), so I can't use libraries, but don't mind using unsafe code.