1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //! Converter that turns a normal [`Fn`] into a [`Future`]
15
16 use std::future::Future;
17 use std::pin::Pin;
18 use std::task::{Context, Poll};
19
20 /// A future object that wraps a [`Fn`]. Awaits on this function will executed
21 /// this underlying function.
22 pub struct PollFn<F> {
23 f: F,
24 }
25
26 impl<F> Unpin for PollFn<F> {}
27
28 impl<T, F> Future for PollFn<F>
29 where
30 F: FnMut(&mut Context<'_>) -> Poll<T>,
31 {
32 type Output = T;
33
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>34 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
35 (self.f)(cx)
36 }
37 }
38
39 /// Creates a new future wrapping around a function or closure.
poll_fn<T, F>(f: F) -> PollFn<F> where F: FnMut(&mut Context<'_>) -> Poll<T>,40 pub fn poll_fn<T, F>(f: F) -> PollFn<F>
41 where
42 F: FnMut(&mut Context<'_>) -> Poll<T>,
43 {
44 PollFn { f }
45 }
46