monoio_compat/
box_future.rs

1use std::{future::Future, io};
2
3use monoio::BufResult;
4use reusable_box_future::ReusableLocalBoxFuture;
5
6use crate::buf::{Buf, RawBuf};
7
8#[derive(Debug)]
9pub struct MaybeArmedBoxFuture<T> {
10    slot: ReusableLocalBoxFuture<T>,
11    armed: bool,
12}
13
14impl<T> MaybeArmedBoxFuture<T> {
15    pub fn armed(&self) -> bool {
16        self.armed
17    }
18
19    pub fn arm_future<F>(&mut self, f: F)
20    where
21        F: Future<Output = T> + 'static,
22    {
23        self.armed = true;
24        self.slot.set(f);
25    }
26
27    pub fn poll(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<T> {
28        match self.slot.poll(cx) {
29            r @ std::task::Poll::Ready(_) => {
30                self.armed = false;
31                r
32            }
33            p => p,
34        }
35    }
36
37    pub fn new<F>(f: F) -> Self
38    where
39        F: Future<Output = T> + 'static,
40    {
41        Self {
42            slot: ReusableLocalBoxFuture::new(f),
43            armed: false,
44        }
45    }
46}
47
48impl Default for MaybeArmedBoxFuture<BufResult<usize, Buf>> {
49    fn default() -> Self {
50        Self {
51            slot: ReusableLocalBoxFuture::new(async { (Ok(0), Buf::uninit()) }),
52            armed: false,
53        }
54    }
55}
56
57impl Default for MaybeArmedBoxFuture<BufResult<usize, RawBuf>> {
58    fn default() -> Self {
59        Self {
60            slot: ReusableLocalBoxFuture::new(async { (Ok(0), RawBuf::uninit()) }),
61            armed: false,
62        }
63    }
64}
65
66impl<T> Default for MaybeArmedBoxFuture<BufResult<usize, T>>
67where
68    T: Default,
69{
70    fn default() -> Self {
71        Self {
72            slot: ReusableLocalBoxFuture::new(async { (Ok(0), T::default()) }),
73            armed: false,
74        }
75    }
76}
77
78impl Default for MaybeArmedBoxFuture<io::Result<()>> {
79    fn default() -> Self {
80        Self {
81            slot: ReusableLocalBoxFuture::new(async { Ok(()) }),
82            armed: false,
83        }
84    }
85}