]> git.lizzy.rs Git - rust.git/blob - src/libstd/future.rs
Error when generator trait is not found
[rust.git] / src / libstd / future.rs
1 //! Asynchronous values.
2
3 use core::cell::Cell;
4 use core::marker::Unpin;
5 use core::pin::Pin;
6 use core::option::Option;
7 use core::ptr::NonNull;
8 use core::task::{Context, Poll};
9 use core::ops::{Drop, Generator, GeneratorState};
10
11 #[doc(inline)]
12 #[stable(feature = "futures_api", since = "1.36.0")]
13 pub use core::future::*;
14
15 /// Wrap a generator in a future.
16 ///
17 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
18 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
19 #[doc(hidden)]
20 #[unstable(feature = "gen_future", issue = "50547")]
21 pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
22     GenFuture(x)
23 }
24
25 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
26 #[doc(hidden)]
27 #[unstable(feature = "gen_future", issue = "50547")]
28 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
29 struct GenFuture<T: Generator<Yield = ()>>(T);
30
31 // We rely on the fact that async/await futures are immovable in order to create
32 // self-referential borrows in the underlying generator.
33 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
34
35 #[doc(hidden)]
36 #[unstable(feature = "gen_future", issue = "50547")]
37 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
38     type Output = T::Return;
39     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
40         // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
41         let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
42         set_task_context(cx, || match gen.resume() {
43             GeneratorState::Yielded(()) => Poll::Pending,
44             GeneratorState::Complete(x) => Poll::Ready(x),
45         })
46     }
47 }
48
49 thread_local! {
50     static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
51 }
52
53 struct SetOnDrop(Option<NonNull<Context<'static>>>);
54
55 impl Drop for SetOnDrop {
56     fn drop(&mut self) {
57         TLS_CX.with(|tls_cx| {
58             tls_cx.set(self.0.take());
59         });
60     }
61 }
62
63 #[doc(hidden)]
64 #[unstable(feature = "gen_future", issue = "50547")]
65 /// Sets the thread-local task context used by async/await futures.
66 pub fn set_task_context<F, R>(cx: &mut Context<'_>, f: F) -> R
67 where
68     F: FnOnce() -> R
69 {
70     // transmute the context's lifetime to 'static so we can store it.
71     let cx = unsafe {
72         core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx)
73     };
74     let old_cx = TLS_CX.with(|tls_cx| {
75         tls_cx.replace(Some(NonNull::from(cx)))
76     });
77     let _reset = SetOnDrop(old_cx);
78     f()
79 }
80
81 #[doc(hidden)]
82 #[unstable(feature = "gen_future", issue = "50547")]
83 /// Retrieves the thread-local task context used by async/await futures.
84 ///
85 /// This function acquires exclusive access to the task context.
86 ///
87 /// Panics if no context has been set or if the context has already been
88 /// retrieved by a surrounding call to get_task_context.
89 pub fn get_task_context<F, R>(f: F) -> R
90 where
91     F: FnOnce(&mut Context<'_>) -> R
92 {
93     let cx_ptr = TLS_CX.with(|tls_cx| {
94         // Clear the entry so that nested `get_task_waker` calls
95         // will fail or set their own value.
96         tls_cx.replace(None)
97     });
98     let _reset = SetOnDrop(cx_ptr);
99
100     let mut cx_ptr = cx_ptr.expect(
101         "TLS Context not set. This is a rustc bug. \
102         Please file an issue on https://github.com/rust-lang/rust.");
103
104     // Safety: we've ensured exclusive access to the context by
105     // removing the pointer from TLS, only to be replaced once
106     // we're done with it.
107     //
108     // The pointer that was inserted came from an `&mut Context<'_>`,
109     // so it is safe to treat as mutable.
110     unsafe { f(cx_ptr.as_mut()) }
111 }
112
113 #[doc(hidden)]
114 #[unstable(feature = "gen_future", issue = "50547")]
115 /// Polls a future in the current thread-local task waker.
116 pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
117 where
118     F: Future
119 {
120     get_task_context(|cx| F::poll(f, cx))
121 }