teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
//! Stopping asynchronous tasks, e.g., [listeners].
//!
//! [listeners]: crate::update_listeners

use std::{future::Future, pin::Pin, task};

use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};

/// Create a new token/flag pair.
#[must_use]
pub fn mk_stop_token() -> (StopToken, StopFlag) {
    let token = CancellationToken::new();
    let flag = StopFlag::new(token.clone());
    (StopToken(token), flag)
}

/// A stop token which corresponds to a [`StopFlag`].
#[derive(Clone)]
pub struct StopToken(CancellationToken);

/// A flag which corresponds to [`StopToken`].
///
/// To know if the stop token was used you can either repeatedly call
/// [`is_stopped`] or use this type as a `Future`.
///
/// [`is_stopped`]: StopFlag::is_stopped
pub struct StopFlag {
    token: CancellationToken,
    wait: Pin<Box<WaitForCancellationFutureOwned>>,
}

impl StopToken {
    /// Stops all flags associated with this token.
    ///
    /// Subsequent calls do not change the stopped state.
    pub fn stop(&self) {
        self.0.cancel();
    }
}

impl StopFlag {
    fn new(token: CancellationToken) -> Self {
        let wait = Box::pin(token.clone().cancelled_owned());
        Self { token, wait }
    }

    /// Returns true if the stop token linked to `self` was used.
    #[must_use]
    pub fn is_stopped(&self) -> bool {
        self.token.is_cancelled()
    }
}

impl Clone for StopFlag {
    fn clone(&self) -> Self {
        Self::new(self.token.clone())
    }
}

/// This future resolves when a stop token was used.
impl Future for StopFlag {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        if self.is_stopped() {
            task::Poll::Ready(())
        } else {
            self.wait.as_mut().poll(cx)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{atomic::AtomicBool, Arc};

    use futures::task::{waker, ArcWake};

    use super::*;

    #[test]
    fn stop_wakes_every_registered_flag() {
        struct Wake(AtomicBool);

        impl ArcWake for Wake {
            fn wake_by_ref(arc_self: &Arc<Self>) {
                arc_self.0.store(true, std::sync::atomic::Ordering::Relaxed);
            }
        }

        let (token, flag) = mk_stop_token();
        let mut flags = [flag.clone(), flag];
        let wakes =
            [Arc::new(Wake(AtomicBool::new(false))), Arc::new(Wake(AtomicBool::new(false)))];
        for (flag, wake) in flags.iter_mut().zip(&wakes) {
            let waker = waker(Arc::clone(wake));
            assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_pending());
        }
        token.stop();
        for (flag, wake) in flags.iter_mut().zip(wakes) {
            assert!(wake.0.load(std::sync::atomic::Ordering::Relaxed));
            let waker = waker(wake);
            assert!(Pin::new(flag).poll(&mut task::Context::from_waker(&waker)).is_ready());
        }
    }
}