fire_stream/standalone_util/
poll_fn.rs

1//!
2//! copy from the std library
3//!
4//! TODO: once our msrv get's increased to 1.64
5
6use std::fmt;
7use std::future::Future;
8use std::pin::Pin;
9use std::task::{Context, Poll};
10
11/// Creates a future that wraps a function returning [`Poll`].
12///
13/// Polling the future delegates to the wrapped function.
14pub fn poll_fn<T, F>(f: F) -> PollFn<F>
15where
16	F: FnMut(&mut Context<'_>) -> Poll<T>,
17{
18	PollFn { f }
19}
20
21/// A Future that wraps a function returning [`Poll`].
22///
23/// This `struct` is created by [`poll_fn()`]. See its
24/// documentation for more.
25#[must_use = "futures do nothing unless you `.await` or poll them"]
26pub struct PollFn<F> {
27	f: F,
28}
29
30impl<F: Unpin> Unpin for PollFn<F> {}
31
32impl<F> fmt::Debug for PollFn<F> {
33	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34		f.debug_struct("PollFn").finish()
35	}
36}
37
38impl<T, F> Future for PollFn<F>
39where
40	F: FnMut(&mut Context<'_>) -> Poll<T>,
41{
42	type Output = T;
43
44	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
45		// SAFETY: We are not moving out of the pinned field.
46		(unsafe { &mut self.get_unchecked_mut().f })(cx)
47	}
48}
49