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