]> git.lizzy.rs Git - rust.git/blob - src/libstd/future.rs
Added minor clarification to specification of realloc.
[rust.git] / src / libstd / future.rs
1 //! Asynchronous values.
2
3 use core::cell::Cell;
4 use core::marker::Unpin;
5 use core::ops::{Drop, Generator, GeneratorState};
6 use core::option::Option;
7 use core::pin::Pin;
8 use core::ptr::NonNull;
9 use core::task::{Context, Poll};
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         let _guard = unsafe { set_task_context(cx) };
43         match gen.resume() {
44             GeneratorState::Yielded(()) => Poll::Pending,
45             GeneratorState::Complete(x) => Poll::Ready(x),
46         }
47     }
48 }
49
50 thread_local! {
51     static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
52 }
53
54 struct SetOnDrop(Option<NonNull<Context<'static>>>);
55
56 impl Drop for SetOnDrop {
57     fn drop(&mut self) {
58         TLS_CX.with(|tls_cx| {
59             tls_cx.set(self.0.take());
60         });
61     }
62 }
63
64 // Safety: the returned guard must drop before `cx` is dropped and before
65 // any previous guard is dropped.
66 unsafe fn set_task_context(cx: &mut Context<'_>) -> SetOnDrop {
67     // transmute the context's lifetime to 'static so we can store it.
68     let cx = core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx);
69     let old_cx = TLS_CX.with(|tls_cx| tls_cx.replace(Some(NonNull::from(cx))));
70     SetOnDrop(old_cx)
71 }
72
73 #[doc(hidden)]
74 #[unstable(feature = "gen_future", issue = "50547")]
75 /// Polls a future in the current thread-local task waker.
76 pub fn poll_with_tls_context<F>(f: Pin<&mut F>) -> Poll<F::Output>
77 where
78     F: Future,
79 {
80     let cx_ptr = TLS_CX.with(|tls_cx| {
81         // Clear the entry so that nested `get_task_waker` calls
82         // will fail or set their own value.
83         tls_cx.replace(None)
84     });
85     let _reset = SetOnDrop(cx_ptr);
86
87     let mut cx_ptr = cx_ptr.expect(
88         "TLS Context not set. This is a rustc bug. \
89         Please file an issue on https://github.com/rust-lang/rust.",
90     );
91
92     // Safety: we've ensured exclusive access to the context by
93     // removing the pointer from TLS, only to be replaced once
94     // we're done with it.
95     //
96     // The pointer that was inserted came from an `&mut Context<'_>`,
97     // so it is safe to treat as mutable.
98     unsafe { F::poll(f, cx_ptr.as_mut()) }
99 }