Skip to content

Instantly share code, notes, and snippets.

@meiamsome
Created October 29, 2016 21:11
Show Gist options
  • Save meiamsome/2d59da4f65da016e07cdcfb3cc743aba to your computer and use it in GitHub Desktop.
Save meiamsome/2d59da4f65da016e07cdcfb3cc743aba to your computer and use it in GitHub Desktop.
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;
}
}
}
@Stebalien
Copy link

Not relevant to your issue but panicing in an interrupt handler is UB (panicing across FFI boundaries in general is UB).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment