| 1 | use std::{ |
| 2 | sync::{Condvar, Mutex}, |
| 3 | time::Duration, |
| 4 | }; |
| 5 | |
| 6 | /// A cancellation token. |
| 7 | pub(crate) struct CancellationToken { |
| 8 | // The "check" for the cancellation token. Setting this to true will mark the cancellation |
| 9 | // token as "cancelled". |
| 10 | mutex: Mutex<bool>, |
| 11 | cvar: Condvar, |
| 12 | } |
| 13 | |
| 14 | impl Default for CancellationToken { |
| 15 | fn default() -> Self { |
| 16 | Self { |
| 17 | mutex: Mutex::new(false), |
| 18 | cvar: Condvar::new(), |
| 19 | } |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl CancellationToken { |
| 24 | /// Mark the [`CancellationToken`] as cancelled. |
| 25 | /// |
| 26 | /// This is idempotent, and once cancelled, will stay cancelled. Sending it |
| 27 | /// again will not do anything. |
| 28 | pub fn cancel(&self) { |
| 29 | let mut guard = self |
| 30 | .mutex |
| 31 | .lock() |
| 32 | .expect("cancellation token lock should not be poisoned"); |
| 33 | |
| 34 | if !*guard { |
| 35 | *guard = true; |
| 36 | self.cvar.notify_all(); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// Try and check the [`CancellationToken`]'s status. Note that |
| 41 | /// this will not block. |
| 42 | pub fn try_check(&self) -> Option<bool> { |
| 43 | self.mutex.try_lock().ok().map(|guard| *guard) |
| 44 | } |
| 45 | |
| 46 | /// Allows a thread to sleep while still being interruptible with by the |
| 47 | /// token. |
| 48 | /// |
| 49 | /// Returns the condition state after either sleeping or being woken up. |
| 50 | pub fn sleep_with_cancellation(&self, duration: Duration) -> bool { |
| 51 | let guard = self |
| 52 | .mutex |
| 53 | .lock() |
| 54 | .expect("cancellation token lock should not be poisoned"); |
| 55 | |
| 56 | let (result, _) = self |
| 57 | .cvar |
| 58 | .wait_timeout(guard, duration) |
| 59 | .expect("cancellation token lock should not be poisoned"); |
| 60 | |
| 61 | *result |
| 62 | } |
| 63 | } |