1 /**
2  * \file wasmtime/extern.hh
3  */
4 
5 #ifndef WASMTIME_EXTERN_HH
6 #define WASMTIME_EXTERN_HH
7 
8 #include <wasmtime/extern.h>
9 #include <wasmtime/extern_declare.hh>
10 #include <wasmtime/func.hh>
11 #include <wasmtime/global.hh>
12 #include <wasmtime/memory.hh>
13 #include <wasmtime/table.hh>
14 
15 namespace wasmtime {
16 
17 // Internal helpers for converting between `Extern`, a `std::variant`, and
18 // `wasmtime_extern_t`.
19 namespace detail {
20 static Extern cvt_extern(wasmtime_extern_t &e) {
21   switch (e.kind) {
22   case WASMTIME_EXTERN_FUNC:
23     return Func(e.of.func);
24   case WASMTIME_EXTERN_GLOBAL:
25     return Global(e.of.global);
26   case WASMTIME_EXTERN_MEMORY:
27     return Memory(e.of.memory);
28   case WASMTIME_EXTERN_TABLE:
29     return Table(e.of.table);
30   }
31   std::abort();
32 }
33 
34 static void cvt_extern(const Extern &e, wasmtime_extern_t &raw) {
35   if (const auto *func = std::get_if<Func>(&e)) {
36     raw.kind = WASMTIME_EXTERN_FUNC;
37     raw.of.func = func->capi();
38   } else if (const auto *global = std::get_if<Global>(&e)) {
39     raw.kind = WASMTIME_EXTERN_GLOBAL;
40     raw.of.global = global->capi();
41   } else if (const auto *table = std::get_if<Table>(&e)) {
42     raw.kind = WASMTIME_EXTERN_TABLE;
43     raw.of.table = table->capi();
44   } else if (const auto *memory = std::get_if<Memory>(&e)) {
45     raw.kind = WASMTIME_EXTERN_MEMORY;
46     raw.of.memory = memory->capi();
47   } else {
48     std::abort();
49   }
50 }
51 } // namespace detail
52 
53 inline std::optional<Extern> Caller::get_export(std::string_view name) {
54   wasmtime_extern_t item;
55   if (wasmtime_caller_export_get(ptr, name.data(), name.size(), &item)) {
56     return detail::cvt_extern(item);
57   }
58   return std::nullopt;
59 }
60 
61 } // namespace wasmtime
62 
63 #endif // WASMTIME_EXTERN_HH
64