forked from tokio-rs/tokio
/
context.rs
38 lines (33 loc) · 974 Bytes
/
context.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
//! This module introduces `TokioContext`, which enables a simple way of using
//! the tokio runtime with any other executor.
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tokio::runtime::Handle;
pin_project! {
/// TODO: add docs. Get some inspiration?
pub struct TokioContext<F> {
#[pin]
inner: F,
handle: Handle,
}
}
impl<F: Future> Future for TokioContext<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
let handle = me.handle;
let fut = me.inner;
handle.enter(|| fut.poll(cx))
}
}
impl<F: Future> TokioContext<F> {
/// Creates a new `TokioContext`. Expects a future as its first argument, and a
/// `tokio::runtime::Handle` as a second.
pub fn new(f: F, handle: Handle) -> Self {
Self { inner: f, handle }
}
}