Skip to main content

workyard_core/
control.rs

1use crate::Problem;
2use std::sync::Arc;
3
4/// Cancellation is supplied by the host; the domain does not choose its runtime.
5#[derive(Clone)]
6pub struct Control(Arc<dyn Fn() -> bool + Send + Sync>);
7
8impl Control {
9	/// Adapt a caller-owned cancellation check for use by lifecycle operations.
10	pub fn new(cancelled: impl Fn() -> bool + Send + Sync + 'static) -> Self {
11		Self(Arc::new(cancelled))
12	}
13
14	/// Query the caller's cancellation signal.
15	pub fn cancelled(&self) -> bool {
16		(self.0)()
17	}
18
19	/// Return a cancellation problem if the caller requested a stop.
20	pub fn check(&self) -> Result<(), Problem> {
21		if self.cancelled() {
22			return Err(Problem::new(
23				crate::ProblemCode::Cancelled,
24				"Operation cancelled.",
25			));
26		}
27
28		Ok(())
29	}
30}
31
32impl Default for Control {
33	fn default() -> Self {
34		Self::new(|| false)
35	}
36}