fulfil -> setWith, fulfilTry -> setTry
[folly.git] / folly / experimental / fibers / Promise-inl.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/experimental/fibers/Baton.h>
17
18 namespace folly { namespace fibers {
19
20 template <class T>
21 Promise<T>::Promise(folly::Try<T>& value, Baton& baton) :
22     value_(&value), baton_(&baton)
23 {}
24
25 template <class T>
26 Promise<T>::Promise(Promise&& other) noexcept :
27 value_(other.value_), baton_(other.baton_) {
28   other.value_ = nullptr;
29   other.baton_ = nullptr;
30 }
31
32 template <class T>
33 Promise<T>& Promise<T>::operator=(Promise&& other) {
34   std::swap(value_, other.value_);
35   std::swap(baton_, other.baton_);
36   return *this;
37 }
38
39 template <class T>
40 void Promise<T>::throwIfFulfilled() const {
41   if (!value_) {
42     throw std::logic_error("promise already fulfilled");
43   }
44 }
45
46 template <class T>
47 Promise<T>::~Promise() {
48   if (value_) {
49     setException(folly::make_exception_wrapper<std::logic_error>(
50         "promise not fulfilled"));
51   }
52 }
53
54 template <class T>
55 void Promise<T>::setException(folly::exception_wrapper e) {
56   setTry(folly::Try<T>(e));
57 }
58
59 template <class T>
60 void Promise<T>::setTry(folly::Try<T>&& t) {
61   throwIfFulfilled();
62
63   *value_ = std::move(t);
64   baton_->post();
65
66   value_ = nullptr;
67   baton_ = nullptr;
68 }
69
70 template <class T>
71 template <class M>
72 void Promise<T>::setValue(M&& v) {
73   static_assert(!std::is_same<T, void>::value,
74                 "Use setValue() instead");
75
76   setTry(folly::Try<T>(std::forward<M>(v)));
77 }
78
79 template <class T>
80 void Promise<T>::setValue() {
81   static_assert(std::is_same<T, void>::value,
82                 "Use setValue(value) instead");
83
84   setTry(folly::Try<void>());
85 }
86
87 template <class T>
88 template <class F>
89 void Promise<T>::setWith(F&& func) {
90   setTry(makeTryFunction(std::forward<F>(func)));
91 }
92
93 }}