ic_storage/adapter/cell.rs
1//! Governed cell collection implementation.
2use super::{Bound, Memory, Storable};
3use crate::{DefaultMemoryImpl, RuntimeMemory, substrate};
4use std::borrow::Cow;
5
6/// Governed upstream `Cell` with explicit initialization and read-only loading.
7///
8/// Values and stored bytes retain the upstream codec and layout contracts.
9///
10pub struct StableCell<T: Storable, M: Memory = DefaultMemoryImpl> {
11 inner: substrate::Cell<CellValue<T>, RuntimeMemory<M>>,
12}
13
14// Upstream has no load constructor. An absent value is an internal loading
15// marker, never a default T or a persisted record. Serialization refuses it
16// before upstream can grow/write on its initialization fallback. Successful
17// construction always holds Some(T), decoded exactly once by upstream.
18struct CellValue<T>(Option<T>);
19
20impl<T: Storable> Storable for CellValue<T> {
21 const BOUND: Bound = T::BOUND;
22
23 fn to_bytes(&self) -> Cow<'_, [u8]> {
24 self.0
25 .as_ref()
26 .expect("cannot initialize a loading cell")
27 .to_bytes_checked()
28 }
29
30 fn into_bytes(self) -> Vec<u8> {
31 self.0
32 .expect("cannot initialize a loading cell")
33 .into_bytes_checked()
34 }
35
36 fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
37 T::check_bounds(&bytes);
38 Self(Some(T::from_bytes(bytes)))
39 }
40}
41
42impl<T: Storable, M: Memory> StableCell<T, M> {
43 /// Create a cell only in zero-page memory, enforcing declared record bounds.
44 ///
45 /// # Panics
46 /// Refuses nonempty memory or a value outside its declared bound before
47 /// writing. Growth and codec failures retain upstream behavior.
48 pub fn create(memory: RuntimeMemory<M>, value: T) -> Self {
49 assert_eq!(memory.size(), 0, "cell memory is not empty");
50 Self::reset(memory, value)
51 }
52
53 /// Deliberately replace any contents, enforcing the record's declared bound.
54 ///
55 /// # Panics
56 /// Refuses oversized/fixed-width mismatches before writing. Growth and codec
57 /// failures retain upstream behavior. Unbounded record types remain allowed.
58 pub fn reset(memory: RuntimeMemory<M>, value: T) -> Self {
59 Self {
60 inner: substrate::Cell::new(memory, CellValue(Some(value))),
61 }
62 }
63
64 /// Load an existing cell without initializing, writing or growing memory.
65 ///
66 /// Requires no default value or `Default`/`Clone` bound. The retained value
67 /// is decoded by upstream using `T::from_bytes`. A successful load retains
68 /// the allocation's exclusive lease until this cell is dropped.
69 ///
70 /// # Errors
71 /// Returns [`crate::StableCellPayloadError`] for empty/foreign memory,
72 /// unsupported layout versions, a payload beyond memory or the declared maximum. The
73 /// consumed lease is released on failure; no bytes are changed.
74 ///
75 /// # Panics
76 /// Codec and backing failures propagate as upstream panics. Loading does
77 /// not write or grow even on these failures. Ordinary unwinding releases
78 /// the consumed lease; Wasm traps retain the host's rollback semantics.
79 /// This validates the envelope, not the application's schema or recovery policy.
80 pub fn load(memory: RuntimeMemory<M>) -> Result<Self, crate::StableCellPayloadError> {
81 let maximum = match T::BOUND {
82 Bound::Bounded { max_size, .. } => max_size as usize,
83 Bound::Unbounded => usize::MAX,
84 };
85 crate::stable_cell_payload_length(&memory, maximum)?;
86 Ok(Self {
87 inner: substrate::Cell::init(memory, CellValue(None)),
88 })
89 }
90
91 /// Delegates to upstream `Cell::get` with the governed allocation.
92 #[expect(
93 clippy::missing_panics_doc,
94 reason = "constructors always establish a cached value"
95 )]
96 pub fn get(&self) -> &T {
97 self.inner.get().0.as_ref().expect("loaded cell value")
98 }
99
100 /// Delegates to upstream `Cell::set` with the governed allocation.
101 ///
102 /// # Panics
103 /// Panics on insufficient memory or codec/backing failure, as upstream.
104 pub fn set(&mut self, value: T) -> T {
105 self.inner
106 .set(CellValue(Some(value)))
107 .0
108 .expect("loaded cell value")
109 }
110}