use crate::error::CheckpointError;
use crate::io::{load, save};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct ProgressTracker {
total: u64,
current: u64,
path: PathBuf,
interval: Duration,
last_save: Instant,
dirty: bool,
}
impl ProgressTracker {
pub fn new(
total: u64,
path: impl AsRef<Path>,
interval: Duration,
) -> Result<Self, CheckpointError> {
let path = path.as_ref().to_path_buf();
let current = load::<ProgressState>(&path)?.map_or(0, |state| state.progress.min(total));
Ok(Self {
total,
current,
path,
interval,
last_save: Instant::now(),
dirty: false,
})
}
pub fn increment(&mut self, n: u64) -> Result<u64, CheckpointError> {
let previous = self.current;
self.current = self.current.saturating_add(n).min(self.total);
if self.current != previous {
self.dirty = true;
}
if self.dirty
&& (self.interval.is_zero()
|| self.last_save.elapsed() >= self.interval
|| self.current == self.total)
{
self.persist()?;
}
Ok(self.current)
}
pub fn resume(&self) -> Result<u64, CheckpointError> {
Ok(load::<ProgressState>(&self.path)?.map_or(0, |state| state.progress.min(self.total)))
}
#[must_use]
pub const fn current(&self) -> u64 {
self.current
}
#[must_use]
pub const fn total(&self) -> u64 {
self.total
}
pub fn flush(&mut self) -> Result<(), CheckpointError> {
self.dirty = true;
self.persist()
}
fn persist(&mut self) -> Result<(), CheckpointError> {
if !self.dirty {
return Ok(());
}
save(
&self.path,
&ProgressState {
total: self.total,
progress: self.current,
},
)?;
self.last_save = Instant::now();
self.dirty = false;
Ok(())
}
}
impl Drop for ProgressTracker {
fn drop(&mut self) {
if self.dirty && self.persist().is_err() {
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct ProgressState {
total: u64,
progress: u64,
}