use super::{Backing, Error, Geometry, Grant, Read, Root, Runtime, Write};
use core::cell::RefCell;
std::thread_local! { static ENGINE: RefCell<Option<Runtime>> = const {RefCell::new(None)}; }
#[expect(
unsafe_code,
reason = "mandatory import resolved only by the supplier's artifact preparation"
)]
#[link(wasm_import_module = "ic_storage_retained_v1")]
unsafe extern "C" {
fn admitted() -> i32;
}
#[expect(
unsafe_code,
reason = "invoke the artifact gate before touching generation-local Rust state"
)]
fn gate() -> Result<(), Error> {
if unsafe { admitted() } != 0x535401 {
return Err(Error::Startup);
}
Ok(())
}
pub struct Canister;
impl Canister {
pub fn create(geometry: Geometry, roots: &[Root]) -> Result<(), Error> {
gate()?;
ENGINE.with(|slot| {
let mut slot = slot.try_borrow_mut().map_err(|_| Error::Busy)?;
if slot.is_some() {
return Err(Error::State);
}
*slot = Some(Runtime::create(Backing::wasm(geometry)?, roots)?);
Ok(())
})
}
pub fn reopen(geometry: Geometry, roots: &[Root]) -> Result<(), Error> {
gate()?;
super::declarations(roots)?;
ENGINE.with(|slot| {
let mut slot = slot.try_borrow_mut().map_err(|_| Error::Busy)?;
if let Some(engine) = slot.as_ref() {
if engine.backing.geometry != geometry {
return Err(Error::Geometry);
}
return engine.reopen(roots);
}
let runtime = Runtime {
backing: Backing::wasm(geometry)?,
roots: roots.to_vec(),
state: RefCell::new(None),
};
runtime.reopen(roots)?;
*slot = Some(runtime);
Ok(())
})
}
fn with<R>(operation: impl FnOnce(&Runtime) -> Result<R, Error>) -> Result<R, Error> {
gate()?;
ENGINE.with(|slot| {
let slot = slot.try_borrow().map_err(|_| Error::Busy)?;
operation(slot.as_ref().ok_or(Error::State)?)
})
}
pub fn grant(participant: u64) -> Result<Grant, Error> {
Self::with(|r| r.grant(participant))
}
pub fn read<R>(
grants: &[&Grant],
operation: impl for<'a> FnOnce(Read<'a>) -> R,
) -> Result<R, Error> {
Self::with(|r| r.read(grants, operation))
}
pub fn update<R>(
grants: &[&Grant],
operation: impl for<'a> FnOnce(Write<'a>) -> R,
) -> Result<R, Error> {
Self::with(|r| r.update(grants, operation))
}
pub fn close() -> Result<(), Error> {
Self::with(Runtime::close)
}
}