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 // Force the compiler to resolve the type. This causes a compile-time error
12 // if `$label` does not exist or is not a valid local type.
13 let _type_check: Option<$label> = None;
14
15 // Enqueue this memory ID registration for deferred validation.
16 $crate::registry::defer_register($id, env!("CARGO_PKG_NAME"), stringify!($label));
17
18 // Return the stable memory handle immediately for further wrapping.
19 $crate::manager::MEMORY_MANAGER
20 .with_borrow_mut(|mgr| mgr.get($crate::cdk::structures::memory::MemoryId::new($id)))
21 }};
22}
23
24/// Reserve a contiguous block of stable-memory IDs for the current crate.
25///
26/// Stores the range request for validation during eager TLS initialization.
27/// The reservation shares the crate namespace used by [`macro@ic_memory`].
28#[macro_export]
29macro_rules! ic_memory_range {
30 ($start:expr, $end:expr) => {{
31 // Enqueue this range reservation. The actual check/insert happens in
32 // `init_eager_tls()`. This guarantees the reservation is made
33 // before any memory IDs from this range are registered.
34 $crate::registry::defer_reserve_range(env!("CARGO_PKG_NAME"), $start, $end);
35 }};
36}