summaryrefslogtreecommitdiff
path: root/monoio-compat/src/box_future.rs
blob: a0d37fcdb309977e45bfaffc09d46d5a9e7ae4c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::{future::Future, io};

use monoio::BufResult;
use reusable_box_future::ReusableLocalBoxFuture;

use crate::buf::{Buf, RawBuf};

#[derive(Debug)]
pub struct MaybeArmedBoxFuture<T> {
    slot: ReusableLocalBoxFuture<T>,
    armed: bool,
}

impl<T> MaybeArmedBoxFuture<T> {
    pub fn armed(&self) -> bool {
        self.armed
    }

    pub fn arm_future<F>(&mut self, f: F)
    where
        F: Future<Output = T> + 'static,
    {
        self.armed = true;
        self.slot.set(f);
    }

    pub fn poll(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<T> {
        match self.slot.poll(cx) {
            r @ std::task::Poll::Ready(_) => {
                self.armed = false;
                r
            }
            p => p,
        }
    }

    pub fn new<F>(f: F) -> Self
    where
        F: Future<Output = T> + 'static,
    {
        Self {
            slot: ReusableLocalBoxFuture::new(f),
            armed: false,
        }
    }
}

impl Default for MaybeArmedBoxFuture<BufResult<usize, Buf>> {
    fn default() -> Self {
        Self {
            slot: ReusableLocalBoxFuture::new(async { (Ok(0), Buf::uninit()) }),
            armed: false,
        }
    }
}

impl Default for MaybeArmedBoxFuture<BufResult<usize, RawBuf>> {
    fn default() -> Self {
        Self {
            slot: ReusableLocalBoxFuture::new(async { (Ok(0), RawBuf::uninit()) }),
            armed: false,
        }
    }
}

impl<T> Default for MaybeArmedBoxFuture<BufResult<usize, T>>
where
    T: Default,
{
    fn default() -> Self {
        Self {
            slot: ReusableLocalBoxFuture::new(async { (Ok(0), T::default()) }),
            armed: false,
        }
    }
}

impl Default for MaybeArmedBoxFuture<io::Result<()>> {
    fn default() -> Self {
        Self {
            slot: ReusableLocalBoxFuture::new(async { Ok(()) }),
            armed: false,
        }
    }
}