use crate::error::{Error, Result};
use std::rc::Rc;
use std::sync::Mutex;
use wamrx_sys as sys;
static RUNTIME_REFCOUNT: Mutex<usize> = Mutex::new(0);
struct EngineInner;
impl Drop for EngineInner {
fn drop(&mut self) {
let mut count = RUNTIME_REFCOUNT.lock().unwrap();
*count -= 1;
if *count == 0 {
unsafe { sys::wasm_runtime_destroy() };
}
}
}
#[derive(Clone)]
pub struct Engine {
#[allow(dead_code)]
inner: Rc<EngineInner>,
}
impl Engine {
pub fn new() -> Result<Engine> {
let mut count = RUNTIME_REFCOUNT.lock().unwrap();
if *count == 0 {
let mut args = sys::RuntimeInitArgs {
mem_alloc_type: sys::Alloc_With_System_Allocator,
..Default::default()
};
let ok = unsafe { sys::wasm_runtime_full_init(&mut args) };
if !ok {
return Err(Error::RuntimeInit);
}
}
*count += 1;
Ok(Engine {
inner: Rc::new(EngineInner),
})
}
}