]> git.lizzy.rs Git - rust.git/blob - src/libstd/future.rs
fix futures aliasing mutable and shared ref
[rust.git] / src / libstd / future.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Asynchronous values.
12
13 use core::cell::Cell;
14 use core::marker::Unpin;
15 use core::pin::Pin;
16 use core::option::Option;
17 use core::ptr::NonNull;
18 use core::task::{LocalWaker, Poll};
19 use core::ops::{Drop, Generator, GeneratorState};
20
21 #[doc(inline)]
22 pub use core::future::*;
23
24 /// Wrap a future in a generator.
25 ///
26 /// This function returns a `GenFuture` underneath, but hides it in `impl Trait` to give
27 /// better error messages (`impl Future` rather than `GenFuture<[closure.....]>`).
28 #[unstable(feature = "gen_future", issue = "50547")]
29 pub fn from_generator<T: Generator<Yield = ()>>(x: T) -> impl Future<Output = T::Return> {
30     GenFuture(x)
31 }
32
33 /// A wrapper around generators used to implement `Future` for `async`/`await` code.
34 #[unstable(feature = "gen_future", issue = "50547")]
35 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
36 struct GenFuture<T: Generator<Yield = ()>>(T);
37
38 // We rely on the fact that async/await futures are immovable in order to create
39 // self-referential borrows in the underlying generator.
40 impl<T: Generator<Yield = ()>> !Unpin for GenFuture<T> {}
41
42 #[unstable(feature = "gen_future", issue = "50547")]
43 impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
44     type Output = T::Return;
45     fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
46         set_task_waker(lw, || match unsafe { Pin::get_mut_unchecked(self).0.resume() } {
47             GeneratorState::Yielded(()) => Poll::Pending,
48             GeneratorState::Complete(x) => Poll::Ready(x),
49         })
50     }
51 }
52
53 thread_local! {
54     static TLS_WAKER: Cell<Option<NonNull<LocalWaker>>> = Cell::new(None);
55 }
56
57 struct SetOnDrop(Option<NonNull<LocalWaker>>);
58
59 impl Drop for SetOnDrop {
60     fn drop(&mut self) {
61         TLS_WAKER.with(|tls_waker| {
62             tls_waker.set(self.0.take());
63         });
64     }
65 }
66
67 #[unstable(feature = "gen_future", issue = "50547")]
68 /// Sets the thread-local task context used by async/await futures.
69 pub fn set_task_waker<F, R>(lw: &LocalWaker, f: F) -> R
70 where
71     F: FnOnce() -> R
72 {
73     let old_waker = TLS_WAKER.with(|tls_waker| {
74         tls_waker.replace(Some(NonNull::from(lw)))
75     });
76     let _reset_waker = SetOnDrop(old_waker);
77     f()
78 }
79
80 #[unstable(feature = "gen_future", issue = "50547")]
81 /// Retrieves the thread-local task waker used by async/await futures.
82 ///
83 /// This function acquires exclusive access to the task waker.
84 ///
85 /// Panics if no waker has been set or if the waker has already been
86 /// retrieved by a surrounding call to get_task_waker.
87 pub fn get_task_waker<F, R>(f: F) -> R
88 where
89     F: FnOnce(&LocalWaker) -> R
90 {
91     let waker_ptr = TLS_WAKER.with(|tls_waker| {
92         // Clear the entry so that nested `get_task_waker` calls
93         // will fail or set their own value.
94         tls_waker.replace(None)
95     });
96     let _reset_waker = SetOnDrop(waker_ptr);
97
98     let waker_ptr = waker_ptr.expect(
99         "TLS LocalWaker not set. This is a rustc bug. \
100         Please file an issue on https://github.com/rust-lang/rust.");
101     unsafe { f(waker_ptr.as_ref()) }
102 }
103
104 #[unstable(feature = "gen_future", issue = "50547")]
105 /// Polls a future in the current thread-local task waker.
106 pub fn poll_with_tls_waker<F>(f: Pin<&mut F>) -> Poll<F::Output>
107 where
108     F: Future
109 {
110     get_task_waker(|lw| F::poll(f, lw))
111 }