use wasmtime::*;
use anyhow::{Result, Error, anyhow};
const ALLOC_FN: &str = "alloc";
const MEMORY: &str = "memory";
pub(crate) fn copy_memory_to_instance(
store: &mut impl AsContextMut,
instance: &Instance,
bytes: &[u8],
) -> Result<isize, Error> {
let memory = instance
.get_memory(&mut *store, MEMORY)
.ok_or_else(|| anyhow!("Missing memory"))?;
let alloc = instance
.get_func(&mut *store, ALLOC_FN)
.ok_or_else(|| anyhow!("missing alloc"))?;
let mut alloc_result = [Val::I32(0)];
alloc.call(
&mut *store,
&[Val::from(bytes.len() as i32)],
&mut alloc_result,
)?;
let guest_ptr_offset = match alloc_result
.first()
.ok_or_else(|| anyhow!("missing alloc"))?
{
Val::I32(val) => *val as isize,
_ => return Err(Error::msg("guest pointer must be Val::I32")),
};
unsafe {
let raw = memory.data_ptr(store).offset(guest_ptr_offset);
raw.copy_from(bytes.as_ptr(), bytes.len());
}
Ok(guest_ptr_offset)
}