pub struct InlineFuture<'a, T, const WORDS: usize> { /* private fields */ }Expand description
Type-erased future stored inline when it fits into WORDS machine words.
A future is stored inline when its size is at most max(WORDS, 1) words
and its alignment is at most the alignment of usize. Other futures are
boxed. The slot always holds at least one word, so WORDS = 0 boxes every
future larger than a pointer.
The future and its output may borrow data for 'a. Like
Pin<Box<dyn Future>>, InlineFuture is neither Send nor Sync. Unlike
a box, it is not Unpin; pin it before polling, for example with
std::pin::pin! or by awaiting it.
Implementations§
Source§impl<'a, T, const WORDS: usize> InlineFuture<'a, T, WORDS>
impl<'a, T, const WORDS: usize> InlineFuture<'a, T, WORDS>
Sourcepub fn new<F>(fut: F) -> Selfwhere
F: Future<Output = T> + 'a,
pub fn new<F>(fut: F) -> Selfwhere
F: Future<Output = T> + 'a,
Erases the type of fut, storing it inline if it fits and boxing it
otherwise.
Sourcepub fn new_with<F>(f: impl FnOnce() -> F) -> Selfwhere
F: Future<Output = T> + 'a,
pub fn new_with<F>(f: impl FnOnce() -> F) -> Selfwhere
F: Future<Output = T> + 'a,
Erases the type of the future returned by f, storing it inline if it
fits and boxing it otherwise.
Unlike new, the storage is prepared before f runs, so
the future can be built directly in place instead of on the stack and
then copied. This matters for large futures that are boxed.
use ntex_service::dev::InlineFuture;
fn double(value: u32) -> InlineFuture<'static, u32, 0> {
InlineFuture::new_with(|| async move { value * 2 })
}Sourcepub const fn empty() -> Self
pub const fn empty() -> Self
Creates an empty placeholder, to be filled by set_with
once pinned.
Polling an empty future panics, dropping it does nothing.
Sourcepub fn set_with<F>(self: Pin<&mut Self>, f: impl FnOnce() -> F)where
F: Future<Output = T> + 'a,
pub fn set_with<F>(self: Pin<&mut Self>, f: impl FnOnce() -> F)where
F: Future<Output = T> + 'a,
Drops the stored future and replaces it with the future returned by
f, storing it inline if it fits and boxing it otherwise.
The new future is built directly in the pinned storage, so a large
future is never copied. With empty, this lets a callee
build its future in storage owned by the caller instead of returning
it by value.
If dropping the previous future or calling f panics, the future is
left empty.
use std::pin::{Pin, pin};
use ntex_service::dev::InlineFuture;
fn double(value: u32, fut: Pin<&mut InlineFuture<'static, u32, 4>>) {
fut.set_with(|| async move { value * 2 });
}
let mut fut = pin!(InlineFuture::empty());
double(21, fut.as_mut());
assert_eq!(fut.await, 42);