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