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