use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Stage {
Geometry,
Classify,
Mesh,
Assemble,
Measure,
}
impl Stage {
pub fn name(self) -> &'static str {
match self {
Self::Geometry => "geometry",
Self::Classify => "classify",
Self::Mesh => "mesh",
Self::Assemble => "assemble",
Self::Measure => "measure",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Progress {
pub stage: Stage,
pub done: u64,
pub total: u64,
}
#[derive(Clone, Copy, Default)]
pub struct Control<'a> {
cancel: Option<&'a AtomicBool>,
progress: Option<&'a (dyn Fn(Progress) + Sync)>,
}
impl fmt::Debug for Control<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Control")
.field("cancel", &self.cancel)
.field("progress", &self.progress.map(|_| "Fn(Progress)"))
.finish()
}
}
impl<'a> Control<'a> {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_cancel(mut self, flag: &'a AtomicBool) -> Self {
self.cancel = Some(flag);
self
}
#[must_use]
pub fn with_progress(mut self, callback: &'a (dyn Fn(Progress) + Sync)) -> Self {
self.progress = Some(callback);
self
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_some_and(|c| c.load(Ordering::Relaxed))
}
pub(crate) fn check(&self) -> Result<()> {
if self.is_cancelled() {
Err(Error::Cancelled)
} else {
Ok(())
}
}
pub(crate) fn report(&self, stage: Stage, done: u64, total: u64) {
if let Some(p) = self.progress {
p(Progress { stage, done, total });
}
}
pub(crate) fn has_progress(&self) -> bool {
self.progress.is_some()
}
}