7 #include "../generic/static_if.h"
9 #include "../threads/thread.h"
13 namespace promise_impl {
17 typedef std::shared_ptr<PromiseState<T>> ptr;
24 typedef std::shared_ptr<PromiseState<void>> ptr;
29 template<
typename Func,
typename T>
32 void operator()(Func f,
typename PromiseState<T>::ptr state) {
37 template<
typename Func>
40 void operator()(Func f,
typename PromiseState<void>::ptr state) {
49 template <
typename C,
typename Ret,
typename... Args>
51 using result_type = Ret;
53 template <std::
size_t i>
55 using type =
typename std::tuple_element<i, std::tuple<Args...>>::type;
62 void cr_yield_for(
const Seconds& seconds);
63 void cr_run_main(std::function<
void ()> func);
68 bool is_ready()
const {
69 return state_ && state_->value;
80 S_WARN(
"Tried to fulfill a Promise without state");
88 state_->value = std::move(value);
93 assert(state_->value);
94 return (state_->value.value());
99 template<
typename Func>
100 auto then(Func&& func) -> Promise<typename promise_impl::func_traits<typename std::decay<Func>::type>::result_type> {
104 auto cb = [func, state]() ->
typename promise_impl::func_traits<
typename std::decay<Func>::type>::result_type {
105 while(!state->value) {
109 return func(state->value.value());
118 bool is_initialized()
const {
122 static Promise<T> create() {
124 std::make_shared<promise_impl::PromiseState<T>>()
129 template<
typename Func>
130 friend Promise<
typename std::result_of<Func()>::type> cr_async(Func func);
132 Promise(
typename promise_impl::PromiseState<T>::ptr state):
137 typename promise_impl::PromiseState<T>::ptr state_;
143 template<
typename Func>
144 friend Promise<
typename std::result_of<Func()>::type> cr_async(Func func);
146 Promise(
typename promise_impl::PromiseState<void>::ptr state):
151 typename promise_impl::PromiseState<void>::ptr state_;
163 bool is_initialized()
const {
167 bool is_ready()
const {
168 return state_ && state_->value;
173 S_WARN(
"Tried to fulfill a Promise without state");
181 state_->value =
true;
185 void value()
const {}
189 template<
typename Func>
194 while(!state->value) {
205 void _trigger_coroutine(std::function<
void ()> func);
206 void _trigger_idle_updates();
208 template<
typename Func>
209 Promise<
typename std::result_of<Func()>::type> cr_async(Func func) {
210 typedef typename std::result_of<Func()>::type T;
212 auto state = std::make_shared<typename promise_impl::PromiseState<T>>();
215 _trigger_coroutine([state, func]() {
232 T cr_await(
const Promise<T>& promise) {
233 while(!promise.is_ready()) {
234 if(cort::within_coroutine()){
237 _trigger_idle_updates();
242 return promise.value();