#[derive(Debug, Clone)]
pub struct PollInterval {
current: i8,
min: i8,
max: i8,
}
impl PollInterval {
pub fn new() -> Self {
Self {
current: 6,
min: 4, max: 10, }
}
pub fn with_bounds(min: i8, max: i8) -> Self {
let min = min.clamp(4, 17);
let max = max.clamp(min, 17);
Self {
current: min,
min,
max,
}
}
pub fn interval_secs(&self) -> u64 {
1u64 << self.current as u64
}
pub fn exponent(&self) -> i8 {
self.current
}
pub fn increase(&mut self) {
if self.current < self.max {
self.current += 1;
}
}
pub fn decrease(&mut self) {
if self.current > self.min {
self.current -= 1;
}
}
pub fn reset(&mut self) {
self.current = self.min;
}
}
impl Default for PollInterval {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_poll_interval() {
let pi = PollInterval::new();
assert_eq!(pi.interval_secs(), 64);
assert_eq!(pi.exponent(), 6);
}
#[test]
fn increase_decrease() {
let mut pi = PollInterval::new();
pi.increase();
assert_eq!(pi.interval_secs(), 128);
pi.decrease();
assert_eq!(pi.interval_secs(), 64);
}
#[test]
fn respects_bounds() {
let mut pi = PollInterval::with_bounds(6, 8);
assert_eq!(pi.interval_secs(), 64);
pi.increase();
pi.increase();
pi.increase(); assert_eq!(pi.exponent(), 8);
assert_eq!(pi.interval_secs(), 256);
pi.decrease();
pi.decrease();
pi.decrease(); assert_eq!(pi.exponent(), 6);
}
#[test]
fn reset() {
let mut pi = PollInterval::with_bounds(4, 10);
pi.increase();
pi.increase();
pi.increase();
pi.reset();
assert_eq!(pi.exponent(), 4);
}
}