pub struct Cell<T, M>{ /* private fields */ }Expand description
Represents a value stored in stable memory.
A Cell stores a single value directly in stable memory and provides immediate persistence
on every write operation. This makes it ideal for configuration values, metadata, or any
small state that needs to survive canister upgrades.
You should use cells only for small (up to a few MiB) values to keep upgrades safe. For larger
values, consider using other data structures like Vec or BTreeMap instead.
§Example
use ic_stable_structures::{Cell, DefaultMemoryImpl, Storable, storable::Bound};
use std::borrow::Cow;
use std::cell::RefCell;
#[derive(Clone)]
struct Config {
name: String,
version: u32,
}
// Implement Storable for serialization/deserialization when saving to stable memory.
impl Storable for Config {
fn to_bytes(&self) -> Cow<'_, [u8]> {
// Convert config into bytes...
}
fn into_bytes(self) -> Vec<u8> {
// Convert config into bytes...
}
fn from_bytes(bytes: Cow<[u8]>) -> Self {
// Convert bytes back to Config
}
// Types can be bounded or unbounded:
// - Use Bound::Unbounded if the size can vary or isn't known in advance (recommended for most cases)
// - Use Bound::Bounded if you know the maximum size and want memory optimization
const BOUND: Bound = Bound::Unbounded;
}
// Create a global cell variable
thread_local! {
static CONFIG: RefCell<Cell<Config, DefaultMemoryImpl>> = RefCell::new(
Cell::init(
DefaultMemoryImpl::default(),
Config {
name: "MyConfig".to_string(),
version: 1,
}
)
);
}
// Read the current configuration
fn get_version() -> u32 {
CONFIG.with(|c| c.borrow().get().version)
}
// Update the configuration
fn update_version(new_version: u32) {
CONFIG.with(|c| {
let mut cell = c.borrow_mut();
let mut config = cell.get().clone();
config.version = new_version;
cell.set(config);
});
}
Implementations§
Source§impl<T, M> Cell<T, M>
impl<T, M> Cell<T, M>
Sourcepub fn new(memory: M, value: T) -> Cell<T, M>
pub fn new(memory: M, value: T) -> Cell<T, M>
Creates a new cell in the specified memory, overwriting the previous contents of the memory.
Sourcepub fn init(memory: M, default_value: T) -> Cell<T, M>
pub fn init(memory: M, default_value: T) -> Cell<T, M>
Initializes the value of the cell based on the contents of the memory.
If the memory already contains a cell, initializes the cell with the decoded value.
Otherwise, sets the cell value to default_value and writes it to the memory.
Sourcepub fn into_memory(self) -> M
pub fn into_memory(self) -> M
Returns the underlying memory.