Skip to main content

canic_core/
memory_macros.rs

1/// Declare a stable-memory slot with an explicit ABI-stable key.
2///
3/// Use this for every Canic-managed memory. The stable key, not crate or Rust
4/// type identity, is the durable allocation identity.
5#[macro_export]
6macro_rules! ic_memory_key {
7    ($stable_key:literal, $label:path, $id:expr) => {{
8        const _: () = {
9            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
10            fn __canic_declare_memory_slot() {
11                $crate::memory::registry::declare_memory_slot_with_key(
12                    $id,
13                    env!("CARGO_PKG_NAME"),
14                    stringify!($label),
15                    $stable_key,
16                )
17                .expect("memory id declaration validation failed");
18            }
19        };
20
21        let _type_check: Option<$label> = None;
22
23        $crate::memory::open_validated_memory($stable_key, stringify!($label), $id)
24    }};
25}
26
27/// Register one eager-init body for execution during lifecycle bootstrap.
28#[macro_export]
29macro_rules! eager_init {
30    ($body:block) => {
31        const _: () = {
32            fn __canic_registered_eager_init_body() {
33                $body
34            }
35
36            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
37            fn __canic_register_eager_init() {
38                $crate::memory::runtime::defer_eager_init(__canic_registered_eager_init_body);
39            }
40        };
41    };
42}
43
44/// Declare a thread-local static and schedule an eager initialization touch.
45#[macro_export]
46macro_rules! eager_static {
47    ($vis:vis static $name:ident : $ty:ty = $init:expr;) => {
48        thread_local! {
49            $vis static $name: $ty = $init;
50        }
51
52        const _: () = {
53            fn __canic_touch_tls() {
54                $name.with(|_| {});
55            }
56
57            #[ $crate::__reexports::ctor::ctor(unsafe, anonymous, crate_path = $crate::__reexports::ctor) ]
58            fn __canic_register_eager_tls() {
59                $crate::memory::runtime::defer_tls_initializer(__canic_touch_tls);
60            }
61        };
62    };
63}