pub struct LoopGuard {
max_ticks: i32,
count: i32,
message: String,
}
impl LoopGuard {
pub fn new(max: i32) -> LoopGuard {
LoopGuard {
max_ticks: max,
count: 0,
message: String::from("Max number of ticks reached"),
}
}
pub fn set_panic_message(mut self, message: &str) -> Self {
self.message = String::from(message);
self
}
pub fn protect(&mut self) {
self.count += 1;
if self.count > self.max_ticks {
panic!("{}", self.message);
}
}
}
#[test]
#[should_panic(expected = "Max number of ticks reached")]
fn infinite_loop_with_guard() {
let mut guard = LoopGuard::new(1000);
loop {
guard.protect();
}
}
#[test]
#[should_panic(expected = "Infinite Loop 2: Electric Boogaloo")]
fn infinite_loop_with_guard_with_custom_message() {
let mut guard = LoopGuard::new(10).set_panic_message("Infinite Loop 2: Electric Boogaloo");
loop {
guard.protect();
}
}
#[test]
#[should_panic(expected = "Max number of ticks reached")]
fn for_loop_surpasses_max_ticks() {
let mut guard = LoopGuard::new(10);
for _i in 0..11 {
guard.protect();
}
}
#[test]
fn for_loop_does_not_surpass_max_ticks() {
let mut guard = LoopGuard::new(10);
for _i in 0..10 {
guard.protect();
}
}