Ditto 4.11.1
 
Loading...
Searching...
No Matches
async_helpers.hpp
1#ifndef _DITTO_ASYNC_HELPERS_
2#define _DITTO_ASYNC_HELPERS_
3
4#include "Errors.hpp"
5
6#include <future>
7
8namespace ditto {
9
10// Type-independent base class for the AsyncContext<T> template
12public:
13 virtual ~AsyncContextBase() = default;
14};
15
16// "free" function for any class derived from AsyncContextBase.
17extern "C" void async_context_deleter(void *ptr) {
18 auto ctx_ptr = static_cast<AsyncContextBase *>(ptr);
19 delete ctx_ptr;
20}
21
73template <typename ReturnType> class AsyncContext : public AsyncContextBase {
74 std::promise<ReturnType> promise;
75
76public:
77 typedef ReturnType return_type;
78
80 AsyncContext() = default;
81
82 AsyncContext(const AsyncContext &) = delete;
83 AsyncContext &operator=(const AsyncContext &) = delete;
84
85 AsyncContext(AsyncContext &&) = delete;
86 AsyncContext &operator=(AsyncContext &&) = delete;
87
89 void set_value(ReturnType value) { promise.set_value(value); }
90
92 void set_exception(std::exception_ptr e) { promise.set_exception(e); }
93
100 std::future<ReturnType> get_future() { return promise.get_future(); }
101
103 void (*get_deleter())(void *) { return async_context_deleter; }
104};
105
134
135#define DITTO_DEFINE_ASYNC_CONTEXT_CALLBACK(cb_name, FfiResultType, \
136 SuccessType) \
137 extern "C" void cb_name(void *env_ptr, FfiResultType ffi_result) { \
138 auto ctx = static_cast<AsyncContext<SuccessType> *>(env_ptr); \
139 if (ffi_result.error != nullptr) { \
140 ctx->set_exception( \
141 std::make_exception_ptr(DittoError(ffi_result.error))); \
142 return; \
143 } \
144 ctx->set_value(ffi_result.success); \
145 }
146
147} // namespace ditto
148
149#endif
Definition async_helpers.hpp:11
void set_exception(std::exception_ptr e)
Set an exception to be thrown.
Definition async_helpers.hpp:92
void set_value(ReturnType value)
Set the value to be returned.
Definition async_helpers.hpp:89
AsyncContext()=default
std::future< ReturnType > get_future()
Get a future that can be used to wait for the return value.
Definition async_helpers.hpp:100
void(*)(void *) get_deleter()
Get the deleter function for this context.
Definition async_helpers.hpp:103