Skip to main content

tokio_util/sync/cancellation_token/
guard_ref.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_ref`] method on the [`CancellationToken`].
5///
6/// This is a borrowed version of [`DropGuard`].
7///
8/// [`drop_guard_ref`]: CancellationToken::drop_guard_ref
9/// [`DropGuard`]: super::DropGuard
10#[derive(Debug)]
11pub struct DropGuardRef<'a> {
12    pub(super) inner: Option<&'a CancellationToken>,
13}
14
15impl<'a> DropGuardRef<'a> {
16    /// Returns a reference to the cancellation token wrapped by this guard.
17    pub fn token(&self) -> &CancellationToken {
18        self.inner
19            .as_ref()
20            .expect("`inner` can only be None in a destructor")
21    }
22
23    /// Returns stored cancellation token and removes this drop guard instance
24    /// (i.e. it will no longer cancel token). Other guards for this token
25    /// are not affected.
26    pub fn disarm(mut self) -> &'a CancellationToken {
27        self.inner
28            .take()
29            .expect("`inner` can be only None in a destructor")
30    }
31}
32
33impl Drop for DropGuardRef<'_> {
34    fn drop(&mut self) {
35        if let Some(inner) = self.inner {
36            inner.cancel();
37        }
38    }
39}