Skip to main content

canic_memory/macros/
memory.rs

1/// Declare a stable-memory slot backed by the Canic memory registry.
2///
3/// The macro enqueues a registration for later validation (during
4/// `init_eager_tls`) and immediately returns the
5/// [`VirtualMemory`](crate::cdk::structures::memory::VirtualMemory)
6/// handle so callers can wrap it in `Cell`, `BTreeMap`, and other structures.
7/// Memory IDs are automatically namespaced per crate via `CARGO_PKG_NAME`.
8#[macro_export]
9macro_rules! ic_memory {
10    ($label:path, $id:expr) => {{
11        if cfg!(target_arch = "wasm32") {
12            $crate::runtime::assert_memory_bootstrap_ready(stringify!($label), $id);
13        }
14
15        // Force the compiler to resolve the type. This causes a compile-time error
16        // if `$label` does not exist or is not a valid local type.
17        let _type_check: Option<$label> = None;
18
19        // Enqueue this memory ID registration for deferred validation.
20        $crate::registry::defer_register($id, env!("CARGO_PKG_NAME"), stringify!($label));
21
22        // Return the stable memory handle immediately for further wrapping.
23        $crate::manager::MEMORY_MANAGER
24            .with_borrow_mut(|mgr| mgr.get($crate::cdk::structures::memory::MemoryId::new($id)))
25    }};
26}
27
28/// Reserve a contiguous block of stable-memory IDs for the current crate.
29///
30/// Stores the range request for validation during eager TLS initialization.
31/// The reservation shares the crate namespace used by [`macro@ic_memory`].
32#[macro_export]
33macro_rules! ic_memory_range {
34    ($start:expr, $end:expr) => {{
35        // Enqueue this range reservation. The actual check/insert happens in
36        // `init_eager_tls()`. This guarantees the reservation is made
37        // before any memory IDs from this range are registered.
38        $crate::registry::defer_reserve_range(env!("CARGO_PKG_NAME"), $start, $end);
39    }};
40}