Skip to main content

compio_runtime\future/
mod.rs

1//! Future combinators.
2
3mod cancel;
4mod personality;
5
6pub use cancel::*;
7use compio_driver::Extra;
8pub use personality::*;
9
10use crate::CancelToken;
11
12#[non_exhaustive]
13#[derive(Clone, Debug, Default)]
14pub(crate) struct Ext {
15    personality: Option<u16>,
16    cancel: Option<CancelToken>,
17}
18
19impl Ext {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    pub fn with_personality(self, personality: u16) -> Self {
25        Self {
26            personality: Some(personality),
27            ..self
28        }
29    }
30
31    pub fn set_personality(&mut self, personality: u16) {
32        self.personality = Some(personality);
33    }
34
35    pub fn get_cancel(&self) -> Option<&CancelToken> {
36        self.cancel.as_ref()
37    }
38
39    pub fn with_cancel(mut self, token: &CancelToken) -> Self {
40        self.set_cancel(token);
41        self
42    }
43
44    pub fn set_cancel(&mut self, cancel: &CancelToken) {
45        // to avoid unnecessary clones
46        if self.cancel.as_ref().is_some_and(|c| c == cancel) {
47            return;
48        }
49        self.cancel = Some(cancel.clone());
50    }
51
52    pub fn set_extra(&self, extra: &mut Extra) -> bool {
53        let mut changed = false;
54        if let Some(personality) = self.personality {
55            extra.set_personality(personality);
56            changed = true;
57        }
58        changed
59    }
60}
61
62/// Extension trait for futures.
63pub trait FutureExt {
64    /// Sets the personality for this future.
65    fn with_personality(self, personality: u16) -> WithPersonality<Self>
66    where
67        Self: Sized,
68    {
69        WithPersonality::new(self, personality)
70    }
71
72    /// Sets the cancel token for this future.
73    fn with_cancel(self, token: CancelToken) -> WithCancel<Self>
74    where
75        Self: Sized,
76    {
77        WithCancel::new(self, token)
78    }
79}
80
81impl<F: Future + ?Sized> FutureExt for F {}