use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Debug, Clone, PartialEq)]
pub struct Progress {
pub value: Option<f64>,
pub total: Option<f64>,
pub message: Option<String>,
}
impl Progress {
pub fn fraction(&self) -> Option<f64> {
match (self.value, self.total) {
(Some(value), Some(total)) if total > 0.0 => Some(value / total),
_ => None,
}
}
}
pub type Listener = Arc<dyn Fn(&Progress) + Send + Sync>;
tokio::task_local! {
static LISTENER: Option<Listener>;
static CANCELLATION: Arc<AtomicBool>;
}
pub async fn listen<F: Future>(listener: Option<Listener>, future: F) -> F::Output {
LISTENER.scope(listener, future).await
}
pub fn listener() -> Option<Listener> {
LISTENER.try_with(Clone::clone).ok().flatten()
}
pub fn report(progress: Progress) {
if let Some(listener) = listener() {
listener(&progress);
}
}
pub async fn watch<F: Future>(flag: Arc<AtomicBool>, future: F) -> F::Output {
CANCELLATION.scope(flag, future).await
}
pub fn is_cancelled() -> bool {
CANCELLATION
.try_with(|flag| flag.load(Ordering::SeqCst))
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fraction_needs_a_positive_total() {
let progress = |value, total| Progress {
value,
total,
message: None,
};
assert_eq!(progress(Some(1.0), Some(2.0)).fraction(), Some(0.5));
assert_eq!(progress(Some(1.0), Some(0.0)).fraction(), None);
assert_eq!(progress(None, Some(2.0)).fraction(), None);
}
}