aboutsummaryrefslogtreecommitdiff
path: root/promise.hpp
blob: 58b644f84bc52b5874e9a5d27561d09d2c074773 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#ifndef _CPPROMISE_HPP
#define _CPPROMISE_HPP

#include <vector>
#include <memory>
#include <any>
#include <functional>

/** Implement type-safe Promise primitives similar to the ones specified by
 * Javascript A+. */
namespace promise {
    using std::function;
    using pm_any_t = std::any;
    using None = std::nullptr_t;
    using values_t = std::vector<pm_any_t>;
    const auto none = nullptr;
    const auto do_nothing = [](){};

    class Promise;
    class promise_t {
        std::shared_ptr<Promise> ptr;
        public:
        promise_t(function<void(promise_t)> callback) {
            ptr = std::make_shared<Promise>();
            callback(*this);
        }

        template<typename T> inline void resolve(T result) const;
        template<typename T> inline void reject(T reason) const;

        template<typename F_, typename F = pm_any_t, typename R_, typename R = pm_any_t>
        inline promise_t then(function<F_(pm_any_t)> fulfilled_callback,
                        function<R_(pm_any_t)> rejected_callback) const;

        template<typename F_, typename F = pm_any_t>
        inline promise_t then(function<F_(pm_any_t)> fulfilled_callback) const;

        template<typename R_, typename R = pm_any_t>
        inline promise_t fail(function<R_(pm_any_t)> rejected_callback) const;

        template<typename F_, typename F>
        inline promise_t then(function<F_(F)> on_fulfilled) const;

        template<typename F_, typename F, typename R_, typename R>
        inline promise_t then(function<F_(F)> on_fulfilled, function<R_(R)> on_rejected) const;

        template<typename F_, typename F>
        inline promise_t fail(function<F_(F)> on_fulfilled) const;
    };

#define PROMISE_ERR_INVALID_STATE do {throw std::runtime_error("invalid promise state");} while (0)
#define PROMISE_ERR_MISMATCH_TYPE do {throw std::runtime_error("mismatching promise value types");} while (0)
    
    class Promise {
        function<void()> fulfilled_callback;
        function<void()> rejected_callback;
        enum class State {
            Pending,
            Fulfilled,
            Rejected,
        } state;
        pm_any_t result;
        pm_any_t reason;

        void add_on_fulfilled(function<void()> cb) {
            auto old_cbs = fulfilled_callback;
            fulfilled_callback = function<void()>(
                [cb, old_cbs]() {
                    old_cbs();
                    cb();
                });
        }

        void add_on_rejected(function<void()> cb) {
            auto old_cbs = rejected_callback;
            rejected_callback = function<void()>(
                [cb, old_cbs]() {
                    old_cbs();
                    cb();
                });
        }

        function<void()> gen_on_fulfilled(
                function<promise_t(pm_any_t)> on_fulfilled,
                const promise_t &npm) {
            return [this, on_fulfilled, npm]() {
                on_fulfilled(result).then(
                    function<None(pm_any_t)>([npm] (pm_any_t result_) {
                        npm.resolve(result_);
                        return none;
                    }),
                    function<None(pm_any_t)>([npm] (pm_any_t reason_) {
                        npm.reject(reason_);
                        return none;
                    }));
            };
        }

        function<void()> gen_on_fulfilled(
                function<pm_any_t(pm_any_t)> on_fulfilled,
                const promise_t &npm) {
            return [this, on_fulfilled, npm]() {
                npm.resolve(on_fulfilled(result));
            };
        }

        function<void()> gen_on_rejected(
                function<promise_t(pm_any_t)> on_rejected,
                const promise_t &npm) {
            return [this, on_rejected, npm]() {
                on_rejected(reason).then(
                    function<None(pm_any_t)>([npm] (pm_any_t result_) {
                        npm.resolve(result_);
                        return none;
                    }),
                    function<None(pm_any_t)>([npm] (pm_any_t reason_) {
                        npm.reject(reason_);
                        return none;
                    }));
            };
        }

        function<void()> gen_on_rejected(
                function<pm_any_t(pm_any_t)> on_rejected,
                const promise_t &npm) {
            return [this, on_rejected, npm]() {
                npm.reject(on_rejected(reason));
            };
        }

        public:

        Promise():
            fulfilled_callback(do_nothing),
            rejected_callback(do_nothing),
            state(State::Pending) {
            //printf("%lx constructed\n", (uintptr_t)this);
        }

        ~Promise() {
            //printf("%lx freed\n", (uintptr_t)this);
        }

        template<typename OnFulfilled, typename OnRejected>
        promise_t then(function<OnFulfilled(pm_any_t)> on_fulfilled,
                      function<OnRejected(pm_any_t)> on_rejected) {
            switch (state)
            {
                case State::Pending:
                    return promise_t([this, on_fulfilled, on_rejected](promise_t npm) {
                        add_on_fulfilled(gen_on_fulfilled(on_fulfilled, npm));
                        add_on_rejected(gen_on_rejected(on_rejected, npm));
                    });
                case State::Fulfilled:
                    return promise_t([this, on_fulfilled](promise_t npm) {
                        gen_on_fulfilled(on_fulfilled, npm)();
                    });
                case State::Rejected:
                    return promise_t([this, on_rejected](promise_t npm) {
                        gen_on_rejected(on_rejected, npm)();
                    });
                default: PROMISE_ERR_INVALID_STATE;
            }
        }

        template<typename OnFulfilled>
        promise_t then(function<OnFulfilled(pm_any_t)> on_fulfilled) {
            switch (state)
            {
                case State::Pending:
                    return promise_t([this, on_fulfilled](promise_t npm) {
                        add_on_fulfilled(gen_on_fulfilled(on_fulfilled, npm));
                        add_on_rejected([this, npm]() {npm.reject(reason);});
                    });
                case State::Fulfilled:
                    return promise_t([this, on_fulfilled](promise_t npm) {
                        gen_on_fulfilled(on_fulfilled, npm)();
                    });
                case State::Rejected:
                    return promise_t([this](promise_t npm) {npm.reject(reason);});
                default: PROMISE_ERR_INVALID_STATE;
            }
        }
 
        template<typename OnRejected>
        promise_t fail(function<OnRejected(pm_any_t)> on_rejected) {
            switch (state)
            {
                case State::Pending:
                    return promise_t([this, on_rejected](promise_t npm) {
                        add_on_rejected(gen_on_rejected(on_rejected, npm));
                        add_on_fulfilled([this, npm]() {npm.resolve(result);});
                    });
                case State::Fulfilled:
                    return promise_t([this](promise_t npm) {npm.resolve(result);});
                case State::Rejected:
                    return promise_t([this, on_rejected](promise_t npm) {
                        add_on_rejected(gen_on_rejected(on_rejected, npm));
                    });
                default: PROMISE_ERR_INVALID_STATE;
            }
        }
 
        void resolve(pm_any_t _result) {
            switch (state)
            {
                case State::Pending:
                    result = _result;
                    state = State::Fulfilled;
                    fulfilled_callback();
                    break;
                default:
                    break;
            }
        }

        void reject(pm_any_t _reason) {
            switch (state)
            {
                case State::Pending:
                    reason = _reason;
                    state = State::Rejected;
                    rejected_callback();
                    break;
                default:
                    break;
            }
        }
    };
        
    template<typename PList> promise_t all(PList promise_list) {
        auto size = std::make_shared<size_t>(promise_list.size());
        auto results = std::make_shared<values_t>();
        if (!size) PROMISE_ERR_MISMATCH_TYPE;
        results->resize(*size);
        return promise_t([=] (promise_t npm) {
            size_t idx = 0;
            for (const auto &pm: promise_list) {
                pm.then(function<pm_any_t(pm_any_t)>(
                    [results, size, idx, npm](pm_any_t result) {
                        (*results)[idx] = result;