pub const DELAY_MS: f64 = 1_000.0;
#[derive(Clone, Debug, Default)]
pub(crate) struct AutoSave {
pub on: bool,
changed: Option<f64>,
urgent: bool,
pub saves: u64,
}
impl AutoSave {
pub fn touch(&mut self, now: f64) {
if self.on {
self.changed = Some(now);
}
}
pub fn hide(&mut self) {
if self.changed.is_some() {
self.urgent = true;
}
}
pub fn clear(&mut self) {
self.changed = None;
self.urgent = false;
}
pub fn owed(&self) -> bool {
self.changed.is_some()
}
pub fn due(&self) -> Option<f64> {
self.changed
.map(|t| if self.urgent { t } else { t + DELAY_MS })
}
pub fn poll(&mut self, now: f64, slack: f64, settled: bool) -> bool {
match self.due() {
Some(due) if settled && due <= now + slack => {
self.clear();
true
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn on() -> AutoSave {
AutoSave {
on: true,
..AutoSave::default()
}
}
#[test]
fn nothing_is_owed_without_a_change() {
let mut a = on();
for t in [0.0, 5_000.0, 60_000.0, 3_600_000.0] {
assert!(!a.poll(t, 1.0, true), "{t}");
}
assert_eq!(a.due(), None);
a.hide();
assert!(!a.poll(3_600_001.0, 1.0, true), "hidden, unchanged");
}
#[test]
fn a_change_is_saved_once_after_the_delay() {
let mut a = on();
a.touch(1_000.0);
assert_eq!(a.due(), Some(1_000.0 + DELAY_MS));
assert!(!a.poll(1_000.0 + DELAY_MS / 2.0, 1.0, true), "too early");
assert!(a.poll(1_000.0 + DELAY_MS, 1.0, true));
assert!(!a.poll(1_001.0 + DELAY_MS, 1.0, true), "once");
assert!(!a.poll(60_000.0, 1.0, true), "nothing new");
}
#[test]
fn each_change_moves_the_save_on() {
let mut a = on();
a.touch(0.0);
a.touch(DELAY_MS * 0.8);
assert!(
!a.poll(DELAY_MS, 1.0, true),
"the delay counts from the last"
);
assert!(a.poll(DELAY_MS * 1.8, 1.0, true));
assert!(!a.poll(20_000.0, 1.0, true), "once");
}
#[test]
fn a_busy_machine_is_saved_once_it_settles() {
let mut a = on();
a.touch(0.0);
assert!(!a.poll(10_000.0, 1.0, false), "computing");
assert!(!a.poll(20_000.0, 1.0, false), "still");
assert!(a.poll(20_500.0, 1.0, true), "settled: saved at once");
}
#[test]
fn hidden_saves_at_once_when_settled() {
let mut a = on();
a.touch(1_000.0);
a.hide();
assert_eq!(a.due(), Some(1_000.0));
assert!(!a.poll(1_200.0, 1.0, false), "mid-transfer: waits");
assert!(a.poll(1_300.0, 1.0, true), "settled: no delay");
assert_eq!(a.due(), None);
a.touch(2_000.0);
assert_eq!(a.due(), Some(2_000.0 + DELAY_MS));
}
#[test]
fn off_owes_nothing() {
let mut a = AutoSave::default();
a.touch(0.0);
a.hide();
assert!(!a.owed());
assert!(!a.poll(10_000.0, 1.0, true));
}
}