11#include <userver/engine/deadline.hpp>
12#include <userver/engine/future_status.hpp>
13#include <userver/engine/impl/future_state.hpp>
16#include <userver/utils/assert.hpp>
18USERVER_NAMESPACE_BEGIN
56 Future(
const Future&) =
delete;
57 Future(Future&&)
noexcept =
default;
58 Future& operator=(
const Future&) =
delete;
59 Future& operator=(Future&&)
noexcept =
default;
84 template <
typename Rep,
typename Period>
93 template <
typename Clock,
typename Duration>
106 impl::ContextAccessor* TryGetContextAccessor()
noexcept {
107 return state_ ? state_->TryGetContextAccessor() :
nullptr;
112 friend class Promise<T>;
114 explicit Future(std::shared_ptr<impl::FutureState<T>> state);
116 void CheckValid()
const;
118 std::shared_ptr<impl::FutureState<T>> state_;
129 Promise(
const Promise&) =
delete;
130 Promise(Promise&&)
noexcept =
default;
131 Promise& operator=(
const Promise&) =
delete;
132 Promise& operator=(Promise&&)
noexcept =
default;
151 std::shared_ptr<impl::FutureState<T>> state_;
155class Promise<
void>
final {
162 Promise(
const Promise&) =
delete;
163 Promise(Promise&&)
noexcept =
default;
164 Promise& operator=(
const Promise&) =
delete;
165 Promise& operator=(Promise&&)
noexcept =
default;
180 std::shared_ptr<impl::FutureState<
void>> state_;
184bool Future<T>::
valid()
const noexcept {
191 return std::exchange(state_,
nullptr)->Get();
197 return state_->WaitUntil({});
201template <
typename Rep,
typename Period>
203 std::chrono::duration<Rep, Period> timeout)
const {
204 return wait_until(Deadline::FromDuration(timeout));
208template <
typename Clock,
typename Duration>
210 std::chrono::time_point<Clock, Duration> until)
const {
211 return wait_until(Deadline::FromTimePoint(until));
217 return state_->WaitUntil(deadline);
221Future<T>::Future(std::shared_ptr<impl::FutureState<T>> state)
222 : state_(std::move(state)) {
224 state_->OnFutureCreated();
228void Future<T>::CheckValid()
const {
230 throw std::future_error(std::future_errc::no_state);
235Promise<T>::
Promise() : state_(std::make_shared<impl::FutureState<T>>()) {}
238Promise<T>::~Promise() {
239 if (state_ && !state_->IsReady()) {
241 state_->SetException(std::make_exception_ptr(
242 std::future_error(std::future_errc::broken_promise)));
243 }
catch (
const std::future_error&) {
251 return Future<T>(state_);
256 state_->SetValue(value);
261 state_->SetValue(std::move(value));
266 state_->SetException(std::move(ex));
272inline Promise<
void>::~Promise() {
273 if (state_ && !state_->IsReady()) {
275 state_->SetException(std::make_exception_ptr(
276 std::future_error(std::future_errc::broken_promise)));
277 }
catch (
const std::future_error&) {
283inline Future<
void> Promise<
void>::
get_future() {
return Future<
void>(state_); }
285inline void Promise<
void>::
set_value() { state_->SetValue(); }
288 state_->SetException(std::move(ex));