intrepid_core/
future.rs

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
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

/// A future that resolves to a `Result<Frame>`
pub struct FrameFuture {
    inner: Pin<Box<dyn Future<Output = crate::Result<crate::Frame>> + Send>>,
}

impl FrameFuture {
    /// Create a new `FrameFuture` from a boxed future.
    pub fn new(inner: Pin<Box<dyn Future<Output = crate::Result<crate::Frame>> + Send>>) -> Self {
        Self { inner }
    }

    /// Create a new `FrameFuture` from a future.
    pub fn from_async_block<F>(future: F) -> Self
    where
        F: Future<Output = crate::Result<crate::Frame>> + Send + 'static,
    {
        Self::new(Box::pin(future))
    }

    /// A convenience method to create a new `FrameFuture` from a `Frame`.
    pub fn from_frame(frame: crate::Frame) -> Self {
        Self::from_result(Ok(frame))
    }

    /// A convenience method to create a new `FrameFuture` from a `Result<Frame>`.
    pub fn from_result(result: crate::Result<crate::Frame>) -> Self {
        Self::from_async_block(async move { result })
    }

    /// A convenience method to create a new `FrameFuture` from a `Vec<FrameFuture>`.
    pub fn from_frame_futures(futures: Vec<FrameFuture>) -> Self {
        Self::from_async_block(async move {
            let mut frames = Vec::new();

            for future in futures {
                frames.push(future.await?);
            }

            Ok(frames.into())
        })
    }

    /// An empty `FrameFuture`.
    pub fn empty() -> Self {
        Self::from_frame(crate::Frame::default())
    }
}

impl Future for FrameFuture {
    type Output = crate::Result<crate::Frame>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().inner.as_mut().poll(cx)
    }
}