制限時間付きループ

概要

loop {
   ...
}

の代わりに,

let milli_seconds = 1000
loop_timeout_ms!(milli_seconds, {
    ...
}

と使う

// Example
fn slow_yes() {
    use std::time::Duration;
    use std::thread::sleep;
    println!("yes");
    sleep(Duration::new(0, 100000000));
}

fn main() {
    loop_timeout_ms!(3000; {
        slow_yes();
    });
}
/// Time Limited Loop
#[macro_export]
macro_rules! loop_timeout_ms {
    ( $milli_seconds:expr; $body:expr ) => {
        let now = std::time::SystemTime::now();
        loop {
            match now.elapsed() {
                Ok(elapsed) => {
                    if elapsed.as_millis() > $milli_seconds {
                        break;
                    }
                    $body
                }
                Err(e) => {
                    eprintln!("Err, {:?}", e);
                }
            }
        }
    };
}

#[cfg(test)]
mod test_timed_loop {
    #[test]
    fn test_timed_loop() {
        loop_timeout_ms!(10; {
            eprintln!("y");
        });
    }
}