use super::InstantiationError;
use crate::{module::FuncIdx, AsContextMut, Error, Instance, InstanceEntityBuilder};
#[derive(Debug)]
pub struct InstancePre {
handle: Instance,
builder: InstanceEntityBuilder,
}
impl InstancePre {
pub(super) fn new(handle: Instance, builder: InstanceEntityBuilder) -> Self {
Self { handle, builder }
}
fn start_fn(&self) -> Option<u32> {
self.builder.get_start().map(FuncIdx::into_u32)
}
pub fn start(self, mut context: impl AsContextMut) -> Result<Instance, Error> {
let opt_start_index = self.start_fn();
context
.as_context_mut()
.store
.inner
.initialize_instance(self.handle, self.builder.finish());
if let Some(start_index) = opt_start_index {
let start_func = self
.handle
.get_func_by_index(&mut context, start_index)
.unwrap_or_else(|| {
panic!("encountered invalid start function after validation: {start_index}")
});
start_func.call(context.as_context_mut(), &[], &mut [])?
}
Ok(self.handle)
}
pub fn ensure_no_start(
self,
mut context: impl AsContextMut,
) -> Result<Instance, InstantiationError> {
if let Some(index) = self.start_fn() {
return Err(InstantiationError::FoundStartFn { index });
}
context
.as_context_mut()
.store
.inner
.initialize_instance(self.handle, self.builder.finish());
Ok(self.handle)
}
}