Created
October 29, 2016 21:11
-
-
Save meiamsome/2d59da4f65da016e07cdcfb3cc743aba to your computer and use it in GitHub Desktop.
Revisions
-
meiamsome created this gist
Oct 29, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,73 @@ use std::cmp; use std::fs; extern "C" { fn signal(sig: u32, cb: extern fn(u32)) -> fn(u32); } extern fn interrupt(_:u32) { panic!(); } struct Sieve { limit: Option<usize>, data: Vec<bool>, current: usize, } impl Sieve { fn new(limit: Option<usize>) -> Sieve { Sieve { limit: limit, data: vec![false, false], current: 0, } } fn clear(self: &mut Sieve, num: usize) { if self.data[num] { for j in 2 .. self.data.len() / num + 1 { if num * j < self.data.len() { self.data[num * j] = false } } } } } impl Iterator for Sieve { type Item = usize; fn next(self: &mut Sieve) -> Option<usize> { while self.limit.map_or(true, |x| self.current < x) { self.current += 1; if self.limit.map_or(false, |x| self.current >= x) { return None } if self.current == self.data.len() { let new_size = self.limit.map_or(self.current * 2, |x| cmp::min(self.current * 2, x)); self.data.resize(new_size, true); for i in 0 .. self.current { self.clear(i); } } if self.data[self.current] { let value = self.current; self.clear(value); return Some(value) } } None } } fn main() { unsafe { signal(8, interrupt); } let sieve = Sieve::new(None); for i in sieve { print!("{}, ", i); if i > 10000 { return; } } }