lichtung_plot/
operation.rs1use std::{
4 cell::{Cell, RefCell},
5 rc::Rc,
6 sync::{
7 atomic::{AtomicBool, Ordering},
8 Arc,
9 },
10};
11
12use crate::{errors::OperationPhase, Error, Result};
13
14#[derive(Debug, Clone, Default)]
19pub struct CancelToken(Arc<AtomicBool>);
20
21impl CancelToken {
22 pub fn new() -> Self {
24 Self::default()
25 }
26
27 pub fn cancel(&self) {
29 self.0.store(true, Ordering::Release);
30 }
31
32 pub fn is_cancelled(&self) -> bool {
34 self.0.load(Ordering::Acquire)
35 }
36}
37
38type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;
39
40#[derive(Clone, Default)]
45pub struct OperationOptions {
46 cancellation: Option<CancelToken>,
47 interrupt_check: Option<Arc<InterruptCheck>>,
48}
49
50impl std::fmt::Debug for OperationOptions {
51 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 f.debug_struct("OperationOptions")
53 .field("cancellation", &self.cancellation)
54 .finish_non_exhaustive()
55 }
56}
57
58impl OperationOptions {
59 #[must_use]
61 pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
62 self.cancellation = token.into();
63 self
64 }
65
66 pub fn get_cancellation(&self) -> Option<&CancelToken> {
68 self.cancellation.as_ref()
69 }
70
71 #[doc(hidden)]
74 #[must_use]
75 pub fn with_interrupt_check(
76 mut self,
77 check: impl Fn(OperationPhase) -> Result<()> + Send + Sync + 'static,
78 ) -> Self {
79 self.interrupt_check = Some(Arc::new(check));
80 self
81 }
82}
83
84struct Operation {
85 options: OperationOptions,
86 phase: Cell<OperationPhase>,
87}
88
89impl Operation {
90 fn cancelled(&self) -> Result<()> {
91 if self
92 .options
93 .cancellation
94 .as_ref()
95 .is_some_and(CancelToken::is_cancelled)
96 {
97 return Err(Error::Cancelled);
98 }
99 Ok(())
100 }
101}
102
103thread_local! {
104 static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
108}
109
110struct Scope(Option<Rc<Operation>>);
111
112impl Drop for Scope {
113 fn drop(&mut self) {
114 let previous = ACTIVE.with(|active| active.replace(self.0.take()));
117 drop(previous);
118 }
119}
120
121pub(crate) fn run<T>(options: &OperationOptions, execute: impl FnOnce() -> Result<T>) -> Result<T> {
122 let current = Rc::new(Operation {
123 options: options.clone(),
124 phase: Cell::new(OperationPhase::Check),
125 });
126 let _scope = Scope(ACTIVE.with(|active| active.replace(Some(current))));
127 checkpoint()?;
128 execute()
129}
130
131pub(crate) fn current_phase() -> Option<OperationPhase> {
132 ACTIVE.with_borrow(|active| active.as_ref().map(|active| active.phase.get()))
133}
134
135pub(crate) fn external<T>(call: impl FnOnce() -> T) -> T {
137 let _scope = Scope(ACTIVE.with(|active| active.replace(None)));
138 call()
139}
140
141pub(crate) fn phase(phase: OperationPhase) -> Result<()> {
142 ACTIVE.with_borrow(|active| {
143 if let Some(active) = active {
144 active.phase.set(phase);
145 }
146 });
147 checkpoint()
148}
149
150pub(crate) fn check() -> Result<()> {
152 ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
153}
154
155pub(crate) fn checkpoint() -> Result<()> {
157 let active = ACTIVE.with_borrow(Clone::clone);
158 if let Some(active) = active {
159 active.cancelled()?;
160 if let Some(check) = &active.options.interrupt_check {
161 external(|| check(active.phase.get()))?;
162 }
163 active.cancelled()?;
164 }
165 Ok(())
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 #[test]
173 fn source_selection_observes_cancellation_and_independent_scopes() {
174 let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
175 let token = CancelToken::new();
176 let options = OperationOptions::default().cancellation(token.clone());
177 let result = run(&options, || {
178 token.cancel();
179 assert!(matches!(
180 crate::CategoryValues::new("category", ["A", "B"]),
181 Err(Error::Cancelled)
182 ));
183 assert!(matches!(
184 crate::data::SourceRows::new([10, 20]),
185 Err(Error::Cancelled)
186 ));
187 assert!(matches!(original.select(&[2, 0, 1]), Err(Error::Cancelled)));
188
189 let selected = run(&OperationOptions::default(), || original.select(&[2, 0, 1]))?;
190 assert!(selected.get(0).flatten().unwrap().is_nan());
191 assert_eq!(
192 selected.get(1).flatten().unwrap().to_bits(),
193 (-0.0_f64).to_bits()
194 );
195 assert_eq!(selected.get(2), Some(None));
196 check()
197 });
198 assert!(matches!(result, Err(Error::Cancelled)));
199 check().unwrap();
200 }
201}