Wasmtime
helpers.hh
1#ifndef WASMTIME_HELPERS_HH
2#define WASMTIME_HELPERS_HH
3
4#include <memory>
5
6#define WASMTIME_OWN_WRAPPER(name, capi_type) \
7public: \
8 \
11 using Raw = capi_type##_t; \
12 \
13private: \
14 struct deleter { \
15 void operator()(Raw *p) const { capi_type##_delete(p); } \
16 }; \
17 \
18 std::unique_ptr<Raw, deleter> ptr; \
19 \
20public: \
21 \
24 explicit name(Raw *raw) : ptr(raw) {} \
25 \
26 ~name() = default; \
27 \
28 \
31 name(name &&other) = default; \
32 \
33 \
36 name &operator=(name &&other) = default; \
37 \
38 \
41 const Raw *capi() const { return ptr.get(); } \
42 \
43 \
46 Raw *capi() { return ptr.get(); } \
47 \
48 \
51 Raw *capi_release() { return ptr.release(); } \
52 \
53 \
57 static const name *from_capi(Raw *const *capi) { \
58 static_assert(sizeof(name) == sizeof(void *)); \
59 return reinterpret_cast<const name *>(capi); \
60 }
61
62#define WASMTIME_CLONE_WRAPPER(name, capi_type) \
63 WASMTIME_OWN_WRAPPER(name, capi_type) \
64 \
65public: \
66 \
69 name(const name &other) : ptr(capi_type##_clone(other.ptr.get())) {} \
70 \
71 \
74 name &operator=(const name &other) { \
75 ptr.reset(capi_type##_clone(other.ptr.get())); \
76 return *this; \
77 }
78
79#define WASMTIME_CLONE_EQUAL_WRAPPER(name, capi_type) \
80 WASMTIME_CLONE_WRAPPER(name, capi_type) \
81 \
82 \
85 bool operator==(const name &other) const { \
86 return capi_type##_equal(ptr.get(), other.ptr.get()); \
87 } \
88 \
89 \
92 bool operator!=(const name &other) const { return !(*this == other); }
93
94#define WASMTIME_REF_WRAPPER(name, capi_type) \
95public: \
96 \
99 using Raw = capi_type##_t; \
100 \
101private: \
102 Raw raw; \
103 \
104public: \
105 \
108 explicit name(Raw raw) : raw(raw) {} \
109 name(const name &other) { capi_type##_clone(&other.raw, &raw); } \
110 \
111 name &operator=(const name &other) { \
112 capi_type##_unroot(&raw); \
113 capi_type##_clone(&other.raw, &raw); \
114 return *this; \
115 } \
116 name(name &&other) { \
117 raw = other.raw; \
118 capi_type##_set_null(&other.raw); \
119 } \
120 name &operator=(name &&other) { \
121 capi_type##_unroot(&raw); \
122 raw = other.raw; \
123 capi_type##_set_null(&other.raw); \
124 return *this; \
125 } \
126 \
127 ~name() { capi_type##_unroot(&raw); } \
128 \
129 \
132 const Raw *capi() const { return &raw; } \
133 \
134 \
137 Raw *capi() { return &raw; }
138
139#define WASMTIME_TOP_REF_WRAPPER(name, capi_type) \
140 WASMTIME_REF_WRAPPER(name, capi_type) \
141 \
142 \
146 uint32_t take_raw(Store::Context cx) { \
147 uint32_t ret = capi_type##_to_raw(cx.capi(), &raw); \
148 capi_type##_set_null(&raw); \
149 return ret; \
150 } \
151 \
152 \
155 uint32_t borrow_raw(Store::Context cx) const { \
156 return capi_type##_to_raw(cx.capi(), &raw); \
157 }
158
159#endif // WASMTIME_HELPERS_HH