ferron/common/with_runtime.rs
1use pin_project_lite::pin_project;
2use std::{
3 future::Future,
4 pin::Pin,
5 task::{Context, Poll},
6};
7use tokio::runtime::Handle;
8
9pin_project! {
10 /// A future that executes within a specific Tokio runtime.
11 ///
12 /// This struct ensures that the wrapped future (`fut`) is polled within the context of the provided Tokio runtime handle (`runtime`).
13 pub struct WithRuntime<F> {
14 runtime: Handle,
15 #[pin]
16 fut: F,
17 }
18}
19
20impl<F> WithRuntime<F> {
21 /// Creates a new `WithRuntime` instance.
22 ///
23 /// # Parameters
24 ///
25 /// - `runtime`: A `Handle` to the Tokio runtime in which the future should be executed.
26 /// - `fut`: The future to be executed within the specified runtime.
27 ///
28 /// # Returns
29 ///
30 /// A `WithRuntime` object encapsulating the provided runtime handle and future.
31 pub fn new(runtime: Handle, fut: F) -> Self {
32 Self { runtime, fut }
33 }
34}
35
36impl<F> Future for WithRuntime<F>
37where
38 F: Future,
39{
40 type Output = F::Output;
41
42 /// Polls the wrapped future within the context of the specified Tokio runtime.
43 ///
44 /// # Parameters
45 ///
46 /// - `ctx`: The current task context.
47 ///
48 /// # Returns
49 ///
50 /// A `Poll` indicating the state of the wrapped future (`Pending` or `Ready`).
51 fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {
52 let this = self.project();
53 let _guard = this.runtime.enter();
54 this.fut.poll(ctx)
55 }
56}