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 .expect("memory id registration validation failed");
22 $crate::runtime::registry::MemoryRegistryRuntime::commit_pending_if_initialized()
23 .expect("late memory id registration commit failed");
24
25 // Return the stable memory handle immediately for further wrapping.
26 $crate::manager::MEMORY_MANAGER
27 .with_borrow_mut(|mgr| mgr.get($crate::cdk::structures::memory::MemoryId::new($id)))
28 }};
29}
30
31/// Reserve a contiguous block of stable-memory IDs for the current crate.
32///
33/// Stores the range request for validation during eager TLS initialization.
34/// The reservation shares the crate namespace used by [`macro@ic_memory`].
35#[macro_export]
36macro_rules! ic_memory_range {
37 ($start:expr, $end:expr) => {{
38 // Enqueue this range reservation. The actual check/insert happens in
39 // `init_eager_tls()`. This guarantees the reservation is made
40 // before any memory IDs from this range are registered.
41 $crate::registry::defer_reserve_range(env!("CARGO_PKG_NAME"), $start, $end)
42 .expect("memory range reservation validation failed");
43 $crate::runtime::registry::MemoryRegistryRuntime::commit_pending_if_initialized()
44 .expect("late memory range registration commit failed");
45 }};
46}