use std::fmt;
#[derive(Debug)]
pub struct Counter {
pub starting: isize,
pub current: isize,
pub step: isize,
pub limit: Option<isize>,
}
impl fmt::Display for Counter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[{1} {2:+} (from {0}{3})",
self.starting,
self.current,
self.step,
self.limit.map_or("".into(), |v| format![" to {}", v])
)
}
}
impl Counter {
pub fn new(value: isize, step: isize, limit: Option<isize>) -> Self {
if let Some(lim) = limit {
assert![(step < 0) == (lim < 0)];
}
Self { starting: value, current: value, step, limit }
}
pub fn update(&mut self) -> bool {
let limit = if let Some(lim) = self.limit { lim.abs() } else { isize::MAX };
if self.current.abs() >= limit {
true
} else {
self.current += self.step;
false
}
}
pub fn wrapping_update(&mut self) -> bool {
if self.update() {
self.reset();
true
} else {
false
}
}
pub fn is_done(&self) -> bool {
if let Some(lim) = self.limit {
self.current >= lim
} else {
false
}
}
pub fn reset(&mut self) -> isize {
let old = self.current;
self.current = self.starting;
old
}
}