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
use crate::{Error, Internal};

/// A list of all possible value types in WebAssembly.
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
#[repr(C)]
pub enum ValType {
    // NB: the ordering here is intended to match the ordering in
    // `wasmtime_types::WasmType` to help improve codegen when converting.
    /// Signed 32 bit integer.
    I32,
    /// Signed 64 bit integer.
    I64,
    /// Floating point 32 bit integer.
    F32,
    /// Floating point 64 bit integer.
    F64,
    /// A 128 bit number.
    V128,
    /// A reference to a Wasm function.
    FuncRef,
    /// A reference to opaque data in the Wasm instance.
    ExternRef,
}

impl From<wasmtime::ValType> for ValType {
    fn from(value: wasmtime::ValType) -> Self {
        use wasmtime::ValType::*;
        match value {
            I32 => ValType::I32,
            I64 => ValType::I64,
            F32 => ValType::F32,
            F64 => ValType::F64,
            V128 => ValType::V128,
            FuncRef => ValType::FuncRef,
            ExternRef => ValType::ExternRef,
        }
    }
}

impl From<ValType> for wasmtime::ValType {
    fn from(value: ValType) -> Self {
        use ValType::*;
        match value {
            I32 => wasmtime::ValType::I32,
            I64 => wasmtime::ValType::I64,
            F32 => wasmtime::ValType::F32,
            F64 => wasmtime::ValType::F64,
            V128 => wasmtime::ValType::V128,
            FuncRef => wasmtime::ValType::FuncRef,
            ExternRef => wasmtime::ValType::ExternRef,
        }
    }
}

pub type Val = wasmtime::Val;

pub struct UserData {
    ptr: *mut std::ffi::c_void,
    free: Option<extern "C" fn(_: *mut std::ffi::c_void)>,
    is_any: bool,
}

extern "C" fn free_any(ptr: *mut std::ffi::c_void) {
    let ptr = ptr as *mut dyn std::any::Any;
    unsafe { drop(Box::from_raw(ptr)) }
}

impl UserData {
    pub fn new_pointer(
        ptr: *mut std::ffi::c_void,
        free: Option<extern "C" fn(_: *mut std::ffi::c_void)>,
    ) -> Self {
        UserData {
            ptr,
            free,
            is_any: false,
        }
    }

    pub fn new<T: std::any::Any>(x: T) -> Self {
        let ptr = Box::into_raw(Box::new(x)) as *mut _;
        UserData {
            ptr,
            free: Some(free_any),
            is_any: true,
        }
    }

    pub fn is_null(&self) -> bool {
        self.ptr.is_null()
    }

    pub fn as_ptr(&self) -> *mut std::ffi::c_void {
        self.ptr
    }

    pub(crate) fn make_copy(&self) -> Self {
        UserData {
            ptr: self.ptr,
            free: None,
            is_any: self.is_any,
        }
    }

    pub fn any(&self) -> Option<&dyn std::any::Any> {
        if !self.is_any || self.is_null() {
            return None;
        }

        unsafe { Some(&*self.ptr) }
    }

    pub fn any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        if !self.is_any || self.is_null() {
            return None;
        }

        unsafe { Some(&mut *self.ptr) }
    }
}

impl Default for UserData {
    fn default() -> Self {
        UserData {
            ptr: std::ptr::null_mut(),
            free: None,
            is_any: false,
        }
    }
}

impl Drop for UserData {
    fn drop(&mut self) {
        if self.ptr.is_null() {
            return;
        }

        if let Some(free) = self.free {
            free(self.ptr);
        }

        self.ptr = std::ptr::null_mut();
    }
}

unsafe impl Send for UserData {}
unsafe impl Sync for UserData {}

type FunctionInner = dyn Fn(wasmtime::Caller<Internal>, &[wasmtime::Val], &mut [wasmtime::Val]) -> Result<(), Error>
    + Sync
    + Send;

#[derive(Clone)]
pub struct Function {
    pub(crate) name: String,
    pub(crate) ty: wasmtime::FuncType,
    pub(crate) f: std::sync::Arc<FunctionInner>,
    pub(crate) namespace: Option<String>,
    pub(crate) _user_data: std::sync::Arc<UserData>,
}

impl Function {
    pub fn new<F>(
        name: impl Into<String>,
        args: impl IntoIterator<Item = ValType>,
        returns: impl IntoIterator<Item = ValType>,
        user_data: Option<UserData>,
        f: F,
    ) -> Function
    where
        F: 'static
            + Fn(&mut Internal, &[Val], &mut [Val], UserData) -> Result<(), Error>
            + Sync
            + Send,
    {
        let user_data = user_data.unwrap_or_default();
        let data = user_data.make_copy();
        Function {
            name: name.into(),
            ty: wasmtime::FuncType::new(
                args.into_iter().map(wasmtime::ValType::from),
                returns.into_iter().map(wasmtime::ValType::from),
            ),
            f: std::sync::Arc::new(move |mut caller, inp, outp| {
                f(caller.data_mut(), inp, outp, data.make_copy())
            }),
            namespace: None,
            _user_data: std::sync::Arc::new(user_data),
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

    pub fn set_namespace(&mut self, namespace: impl Into<String>) {
        self.namespace = Some(namespace.into());
    }

    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.set_namespace(namespace);
        self
    }

    pub fn ty(&self) -> &wasmtime::FuncType {
        &self.ty
    }
}