Module ic_stable_structures::memory_manager

source ·
Expand description

A module for simulating multiple memories within a single memory.

The typical way for a canister to have multiple stable structures is by dividing the memory into distinct ranges, dedicating each range to a stable structure. This approach has two problems:

  1. The developer needs to put in advance an upper bound on the memory of each stable structure.
  2. It wastes the canister’s memory allocation. For example, if a canister creates two stable structures A and B, and gives each one of them a 1GiB region of memory, then writing to B will require growing > 1GiB of memory just to be able to write to it.

The MemoryManager in this module solves both of these problems. It simulates having multiple memories, each being able to grow without bound. That way, a developer doesn’t need to put an upper bound to how much stable structures can grow, and the canister’s memory allocation becomes less wasteful.

Example Usage:

use ic_stable_structures::{DefaultMemoryImpl, Memory};
use ic_stable_structures::memory_manager::{MemoryManager, MemoryId};

let mem_mgr = MemoryManager::init(DefaultMemoryImpl::default());

// Create different memories, each with a unique ID.
let memory_0 = mem_mgr.get(MemoryId::new(0));
let memory_1 = mem_mgr.get(MemoryId::new(1));

// Each memory can be used independently.
memory_0.grow(1);
memory_0.write(0, &[1, 2, 3]);

memory_1.grow(1);
memory_1.write(0, &[4, 5, 6]);

let mut bytes = vec![0; 3];
memory_0.read(0, &mut bytes);
assert_eq!(bytes, vec![1, 2, 3]);

let mut bytes = vec![0; 3];
memory_1.read(0, &mut bytes);
assert_eq!(bytes, vec![4, 5, 6]);

Structs§