Skip to main content

lox_core/
sync.rs

1// SPDX-FileCopyrightText: 2026 Helge Eichhorn <git@helgeeichhorn.de>
2//
3// SPDX-License-Identifier: MPL-2.0
4
5//! Synchronization primitives for long-running computations.
6
7use alloc::sync::Arc;
8use core::sync::atomic::{AtomicBool, Ordering};
9
10/// A cooperative cancellation handle.
11///
12/// Cloning the token shares the underlying flag: cancelling any clone cancels
13/// all of them.
14#[derive(Clone, Debug, Default)]
15pub struct CancellationToken(Arc<AtomicBool>);
16
17impl CancellationToken {
18    /// Creates a new cancellation token.
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Sends cancellation.
24    pub fn cancel(&self) {
25        self.0.store(true, Ordering::Relaxed);
26    }
27
28    /// Returns `true` if cancellation has been sent.
29    pub fn is_cancelled(&self) -> bool {
30        self.0.load(Ordering::Relaxed)
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_cancellation_token_is_shared() {
40        let token = CancellationToken::new();
41        let clone = token.clone();
42        assert!(!token.is_cancelled());
43        clone.cancel();
44        assert!(token.is_cancelled());
45        assert!(clone.is_cancelled());
46    }
47}