tokio_util/sync/cancellation_token/guard.rs
1use crate::sync::CancellationToken;
2
3/// A wrapper for cancellation token which automatically cancels
4/// it on drop. It is created using [`drop_guard`] method on the [`CancellationToken`].
5///
6/// [`drop_guard`]: CancellationToken::drop_guard
7#[derive(Debug)]
8pub struct DropGuard {
9 pub(super) inner: Option<CancellationToken>,
10}
11
12impl DropGuard {
13 /// Returns a reference to the cancellation token wrapped by this guard.
14 pub fn token(&self) -> &CancellationToken {
15 self.inner
16 .as_ref()
17 .expect("`inner` can only be None in a destructor")
18 }
19
20 /// Returns stored cancellation token and removes this drop guard instance
21 /// (i.e. it will no longer cancel token). Other guards for this token
22 /// are not affected.
23 pub fn disarm(mut self) -> CancellationToken {
24 self.inner
25 .take()
26 .expect("`inner` can be only None in a destructor")
27 }
28}
29
30impl Drop for DropGuard {
31 fn drop(&mut self) {
32 if let Some(inner) = &self.inner {
33 inner.cancel();
34 }
35 }
36}