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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Defines WasmEdge Global and GlobalType structs.
//!
//! A WasmEdge `Global` defines a global variable, which stores a single value of the given `GlobalType`.
//! `GlobalType` specifies whether a global variable is immutable or mutable.

use crate::{
    error::{GlobalError, WasmEdgeError},
    ffi, WasmEdgeResult, WasmValue,
};
use std::sync::Arc;
use wasmedge_types::{Mutability, ValType};

/// Defines a WebAssembly global variable, which stores a single value of the given [type](crate::GlobalType) and a flag indicating whether it is mutable or not.
#[derive(Debug)]
pub struct Global {
    pub(crate) inner: Arc<InnerGlobal>,
    pub(crate) registered: bool,
}
impl Global {
    /// Creates a new [Global] instance to be associated with the given [GlobalType] and [WasmValue](crate::WasmValue).
    ///
    /// The type of the given [WasmValue](crate::WasmValue) must be matched with [GlobalType]; otherwise, it causes a failure. For example, `WasmValue::I32(520)` conflicts with a [GlobalType] with a value type defined as `ValType::F32`.
    ///
    /// # Errors
    ///
    /// * If fail to create the Global instance, then WasmEdgeError::Global(GlobalError::Create)(crate::error::GlobalError) is returned.
    ///
    pub fn create(ty: &GlobalType, val: WasmValue) -> WasmEdgeResult<Self> {
        let ctx = unsafe { ffi::WasmEdge_GlobalInstanceCreate(ty.inner.0, val.as_raw()) };

        match ctx.is_null() {
            true => Err(Box::new(WasmEdgeError::Global(GlobalError::Create))),
            false => Ok(Self {
                inner: Arc::new(InnerGlobal(ctx)),
                registered: false,
            }),
        }
    }

    /// Returns the underlying wasm type of a [Global] instance.
    ///
    /// # Errors
    ///
    /// If fail to get the type, then an error is returned.
    ///
    pub fn ty(&self) -> WasmEdgeResult<GlobalType> {
        let ty_ctx = unsafe { ffi::WasmEdge_GlobalInstanceGetGlobalType(self.inner.0) };
        match ty_ctx.is_null() {
            true => Err(Box::new(WasmEdgeError::Global(GlobalError::Type))),
            false => Ok(GlobalType {
                inner: InnerGlobalType(ty_ctx as *mut _),
                registered: true,
            }),
        }
    }

    /// Returns the value of the [Global] instance.
    pub fn get_value(&self) -> WasmValue {
        let val = unsafe { ffi::WasmEdge_GlobalInstanceGetValue(self.inner.0) };
        val.into()
    }

    /// Sets the value of the [Global] instance.
    ///
    /// Notice that only the [Global] instance of [Mutability::Var](wasmedge_types::Mutability::Var) type can be set a new value. Setting a new value for a [Global] of [Mutability::Const](wasmedge_types::Mutability::Const) causes a failure.
    ///
    /// # Argument
    ///
    /// * `val` - The new wasm value to be set.
    ///
    /// # Errors
    ///
    /// If fail to set value, then an error is returned.
    ///
    /// # Example
    ///
    /// ```
    /// use wasmedge_sys::{Global, GlobalType, WasmValue};
    /// use wasmedge_types::{ValType, Mutability};
    ///
    /// // create a GlobalType instance
    /// let ty = GlobalType::create(ValType::F32, Mutability::Var).expect("fail to create a GlobalType");
    /// // create a Global instance
    /// let mut global = Global::create(&ty, WasmValue::from_f32(3.1415)).expect("fail to create a Global");
    ///
    /// global.set_value(WasmValue::from_f32(314.15)).expect("fail to set a new value for a Global");
    /// assert_eq!(global.get_value().to_f32(), 314.15);
    /// ```
    ///
    ///
    pub fn set_value(&mut self, val: WasmValue) -> WasmEdgeResult<()> {
        let ty = self.ty()?;
        if ty.mutability() == Mutability::Const {
            return Err(Box::new(WasmEdgeError::Global(GlobalError::ModifyConst)));
        }
        if ty.value_type() != val.ty() {
            return Err(Box::new(WasmEdgeError::Global(
                GlobalError::UnmatchedValType,
            )));
        }
        unsafe { ffi::WasmEdge_GlobalInstanceSetValue(self.inner.0, val.as_raw()) }
        Ok(())
    }

    /// Provides a raw pointer to the inner global context.
    #[cfg(feature = "ffi")]
    pub fn as_ptr(&self) -> *const ffi::WasmEdge_GlobalInstanceContext {
        self.inner.0 as *const _
    }
}
impl Drop for Global {
    fn drop(&mut self) {
        if !self.registered && Arc::strong_count(&self.inner) == 1 && !self.inner.0.is_null() {
            unsafe { ffi::WasmEdge_GlobalInstanceDelete(self.inner.0) };
        }
    }
}
impl Clone for Global {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            registered: false,
        }
    }
}

#[derive(Debug)]
pub(crate) struct InnerGlobal(pub(crate) *mut ffi::WasmEdge_GlobalInstanceContext);
unsafe impl Send for InnerGlobal {}
unsafe impl Sync for InnerGlobal {}

/// Defines the type of a wasm global variable.
///
/// A [GlobalType] classifies a global variable that hold a value and can either be mutable or immutable.
#[derive(Debug)]
pub struct GlobalType {
    pub(crate) inner: InnerGlobalType,
    pub(crate) registered: bool,
}
impl GlobalType {
    /// Create a new [GlobalType] to be associated with the given [ValType](wasmedge_types::ValType) and [Mutability](wasmedge_types::Mutability).
    ///
    /// # Arguments
    ///
    /// * `val_type` - The value type of the global variable.
    ///
    /// * `mutability` - The mutability of the global variable.
    ///
    /// # Errors
    ///
    /// If fail to create a new [GlobalType], then an error is returned.
    pub fn create(val_ty: ValType, mutable: Mutability) -> WasmEdgeResult<Self> {
        let ctx = unsafe { ffi::WasmEdge_GlobalTypeCreate(val_ty.into(), mutable.into()) };
        match ctx.is_null() {
            true => Err(Box::new(WasmEdgeError::GlobalTypeCreate)),
            false => Ok(Self {
                inner: InnerGlobalType(ctx),
                registered: false,
            }),
        }
    }

    /// Returns the value type of the [GlobalType].
    pub fn value_type(&self) -> ValType {
        let val = unsafe { ffi::WasmEdge_GlobalTypeGetValType(self.inner.0 as *const _) };
        val.into()
    }

    /// Returns the [Mutability](wasmedge_types::Mutability) value of the [GlobalType].
    pub fn mutability(&self) -> Mutability {
        let val = unsafe { ffi::WasmEdge_GlobalTypeGetMutability(self.inner.0) };
        val.into()
    }

    /// Provides a raw pointer to the inner global type context.
    #[cfg(feature = "ffi")]
    pub fn as_ptr(&self) -> *const ffi::WasmEdge_GlobalTypeContext {
        self.inner.0 as *const _
    }
}
impl Drop for GlobalType {
    fn drop(&mut self) {
        if !self.registered && !self.inner.0.is_null() {
            unsafe { ffi::WasmEdge_GlobalTypeDelete(self.inner.0) };
        }
    }
}
impl From<wasmedge_types::GlobalType> for GlobalType {
    fn from(ty: wasmedge_types::GlobalType) -> Self {
        GlobalType::create(ty.value_ty(), ty.mutability()).expect(
            "[wasmedge-sys] Failed to convert wasmedge_types::GlobalType into wasmedge_sys::GlobalType.",
        )
    }
}
impl From<GlobalType> for wasmedge_types::GlobalType {
    fn from(ty: GlobalType) -> Self {
        wasmedge_types::GlobalType::new(ty.value_type(), ty.mutability())
    }
}

#[derive(Debug)]
pub(crate) struct InnerGlobalType(pub(crate) *mut ffi::WasmEdge_GlobalTypeContext);
unsafe impl Send for InnerGlobalType {}
unsafe impl Sync for InnerGlobalType {}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        sync::{Arc, Mutex},
        thread,
    };
    use wasmedge_types::{Mutability, ValType};

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_global_type() {
        // create a GlobalType instance
        let result = GlobalType::create(ValType::I32, Mutability::Const);
        assert!(result.is_ok());
        let global_ty = result.unwrap();
        assert!(!global_ty.inner.0.is_null());
        assert!(!global_ty.registered);

        // value type
        assert_eq!(global_ty.value_type(), ValType::I32);
        // Mutability
        assert_eq!(global_ty.mutability(), Mutability::Const);
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_global_const_i32() {
        // create a GlobalType instance
        let result = GlobalType::create(ValType::I32, Mutability::Const);
        assert!(result.is_ok());
        let ty = result.unwrap();
        assert!(!ty.inner.0.is_null());

        // create a const Global instance
        let result = Global::create(&ty, WasmValue::from_i32(99));
        assert!(result.is_ok());
        let mut global_const = result.unwrap();

        // access the value held by global_const
        assert_eq!(global_const.get_value().to_i32(), 99);
        let result = global_const.set_value(WasmValue::from_i32(0));
        assert!(result.is_err());

        // access the global type
        let result = global_const.ty();
        assert!(result.is_ok());
        let ty = result.unwrap();
        assert!(!ty.inner.0.is_null());
        assert!(ty.registered);
        assert_eq!(ty.value_type(), ValType::I32);
        assert_eq!(ty.mutability(), Mutability::Const);
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_global_var_f32() {
        // create a GlobalType instance
        let result = GlobalType::create(ValType::F32, Mutability::Var);
        assert!(result.is_ok());
        let ty = result.unwrap();
        assert!(!ty.inner.0.is_null());

        // create a Var Global instance
        let result = Global::create(&ty, WasmValue::from_f32(13.14));
        assert!(result.is_ok());
        let mut global_var = result.unwrap();

        // access the value held by global_var
        assert_eq!(global_var.get_value().to_f32(), 13.14);
        let result = global_var.set_value(WasmValue::from_f32(1.314));
        assert!(result.is_ok());
        assert_eq!(global_var.get_value().to_f32(), 1.314);

        // access the global type
        let result = global_var.ty();
        assert!(result.is_ok());
        let ty = result.unwrap();
        assert!(!ty.inner.0.is_null());
        assert!(ty.registered);
        assert_eq!(ty.value_type(), ValType::F32);
        assert_eq!(ty.mutability(), Mutability::Var);
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_global_conflict() {
        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::F32, Mutability::Var);
            assert!(result.is_ok());
            let ty = result.unwrap();
            assert!(!ty.inner.0.is_null());

            // create a Var Global instance with a value of mis-matched Value::I32 type
            let result = Global::create(&ty, WasmValue::from_i32(520));
            assert!(result.is_err());
        }

        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::F32, Mutability::Var);
            assert!(result.is_ok());
            let ty = result.unwrap();
            assert!(!ty.inner.0.is_null());

            // create a Var Global instance with a value of Value::F32 type
            let result = Global::create(&ty, WasmValue::from_f32(13.14));
            assert!(result.is_ok());
            let mut global_var = result.unwrap();

            // set a new value of mis-matched Value::I32 type
            let result = global_var.set_value(WasmValue::from_i32(1314));
            assert!(result.is_err());
            assert_eq!(global_var.get_value().to_f32(), 13.14);

            // set a new value of Value::F32 type
            let result = global_var.set_value(WasmValue::from_f32(1.314));
            assert!(result.is_ok());
            assert_eq!(global_var.get_value().to_f32(), 1.314);
        }
    }

    #[test]
    fn test_global_send() {
        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::I32, Mutability::Const);
            assert!(result.is_ok());
            let global_ty = result.unwrap();

            let handle = thread::spawn(move || {
                assert!(!global_ty.inner.0.is_null());
                assert!(!global_ty.registered);

                // value type
                assert_eq!(global_ty.value_type(), ValType::I32);
                // Mutability
                assert_eq!(global_ty.mutability(), Mutability::Const);
            });

            handle.join().unwrap()
        }

        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::I32, Mutability::Const);
            assert!(result.is_ok());
            let global_ty = result.unwrap();

            // create a Global instance
            let result = Global::create(&global_ty, WasmValue::from_i32(5));
            assert!(result.is_ok());
            let global = result.unwrap();

            let handle = thread::spawn(move || {
                // access the value held by global
                assert_eq!(global.get_value().to_i32(), 5);
            });

            handle.join().unwrap()
        }
    }

    #[test]
    fn test_global_sync() {
        // create a GlobalType instance
        let result = GlobalType::create(ValType::I32, Mutability::Const);
        assert!(result.is_ok());
        let global_ty = result.unwrap();

        // create a Global instance
        let result = Global::create(&global_ty, WasmValue::from_i32(5));
        assert!(result.is_ok());
        let global = Arc::new(Mutex::new(result.unwrap()));

        let global_cloned = Arc::clone(&global);
        let handle = thread::spawn(move || {
            let result = global_cloned.lock();
            assert!(result.is_ok());
            let global = result.unwrap();

            assert_eq!(global.get_value().to_i32(), 5);
        });

        handle.join().unwrap()
    }

    #[test]
    fn test_global_clone() {
        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::I32, Mutability::Const);
            assert!(result.is_ok());
            let global_ty = result.unwrap();

            // create a Global instance
            let result = Global::create(&global_ty, WasmValue::from_i32(5));
            assert!(result.is_ok());
            let global = result.unwrap();

            let global_cloned = global.clone();

            drop(global);

            assert_eq!(global_cloned.get_value().to_i32(), 5);
        }

        {
            // create a GlobalType instance
            let result = GlobalType::create(ValType::F32, Mutability::Var);
            assert!(result.is_ok());
            let ty = result.unwrap();
            assert!(!ty.inner.0.is_null());

            // create a Var Global instance
            let result = Global::create(&ty, WasmValue::from_f32(13.14));
            assert!(result.is_ok());
            let mut global_var = result.unwrap();
            assert_eq!(global_var.get_value().to_f32(), 13.14);

            let global_var_cloned = global_var.clone();
            assert_eq!(
                global_var_cloned.get_value().to_f32(),
                global_var.get_value().to_f32()
            );

            // access the value held by global_var
            let result = global_var.set_value(WasmValue::from_f32(1.314));
            assert!(result.is_ok());
            assert_eq!(global_var.get_value().to_f32(), 1.314);

            drop(global_var);

            assert_eq!(global_var_cloned.get_value().to_f32(), 1.314);
        }
    }
}