Skip to main content

bity_ic_utils/
memory.rs

1//! Memory usage tracking utilities for Internet Computer canisters.
2
3use candid::CandidType;
4use serde::{Deserialize, Serialize};
5
6/// Represents the memory usage of a canister.
7#[derive(Serialize, Deserialize, CandidType)]
8pub struct MemorySize {
9    /// Heap memory usage in bytes
10    heap: u64,
11    /// Stable memory usage in bytes
12    stable: u64,
13}
14
15impl MemorySize {
16    pub fn used() -> Self {
17        Self {
18            heap: wasm_memory_size(),
19            stable: bity_ic_stable_memory::used(),
20        }
21    }
22}
23
24/// Returns the current WebAssembly memory size in bytes.
25pub fn wasm_memory_size() -> u64 {
26    #[cfg(target_arch = "wasm32")]
27    {
28        const UPPER_LIMIT_WASM_SIZE_BYTES: u64 = 3 * 1024 * 1024; // 3MB
29        UPPER_LIMIT_WASM_SIZE_BYTES + ((core::arch::wasm32::memory_size(0) * 65536) as u64)
30    }
31
32    #[cfg(not(target_arch = "wasm32"))]
33    {
34        // This branch won't actually ever be taken
35        1024 * 1024 * 100 // 100Mb
36    }
37}