junobuild_shared/
canister.rs

1use crate::types::interface::MemorySize;
2#[cfg(target_arch = "wasm32")]
3use core::arch::wasm32::memory_size as wasm_memory_size;
4use ic_cdk::stable::{stable_size, WASM_PAGE_SIZE_IN_BYTES};
5
6/// Returns the current memory usage of the WebAssembly module.
7///
8/// This function calculates the memory size allocated for both the heap and the stable storage
9/// by querying the WebAssembly system interface and the Internet Computer's stable storage API.
10///
11/// # Returns
12/// A `MemorySize` struct containing two fields:
13/// - `heap`: The total size of the WebAssembly module's heap memory in bytes.
14/// - `stable`: The total size of the stable storage used by the module in bytes.
15///
16/// Both sizes are calculated based on the WebAssembly page size.
17///
18/// # Example
19/// ```
20/// let memory_usage = junobuild_shared::canister::memory_size();
21/// println!("Heap size: {} bytes", memory_usage.heap);
22/// println!("Stable storage size: {} bytes", memory_usage.stable);
23/// ```
24///
25#[cfg(target_arch = "wasm32")]
26pub fn memory_size() -> MemorySize {
27    MemorySize {
28        heap: wasm_memory_size(0) as u64 * WASM_PAGE_SIZE_IN_BYTES,
29        stable: stable_size() * WASM_PAGE_SIZE_IN_BYTES,
30    }
31}
32
33// For cargo test only
34#[cfg(not(target_arch = "wasm32"))]
35pub fn memory_size() -> MemorySize {
36    MemorySize { heap: 0, stable: 0 }
37}