ic_storage/adapter/cell.rs
1//! One cached application value persisted under an exclusive governed lease.
2
3use super::error::{CollectionError as Error, Result};
4use crate::{
5 DefaultMemoryImpl, Memory, RuntimeMemory,
6 stable_cell::{read_payload, stable_cell_payload_length, write_payload},
7 storable::{Bound, Storable},
8};
9use std::{borrow::Cow, mem};
10
11///
12/// `StableCell`
13///
14/// An application value cached in memory and persisted in an exclusive Storage
15/// allocation. Dropping the Cell releases its lease without changing its bytes.
16///
17pub struct StableCell<T: Storable, M: Memory = DefaultMemoryImpl> {
18 memory: RuntimeMemory<M>,
19 value: T,
20 encoded_length: usize,
21}
22
23impl<T: Storable, M: Memory> StableCell<T, M> {
24 /// Create a Cell only in an empty allocation.
25 ///
26 /// # Errors
27 /// Returns `NotEmpty` without mutation if the allocation is nonempty, or
28 /// `Growth` if its initial reservation cannot accommodate the encoding.
29 ///
30 /// # Panics
31 /// Panics if encoding fails, violates the declared bound, or backing IO
32 /// fails. A native mutation panic poisons the backing owner.
33 pub fn create(memory: RuntimeMemory<M>, value: T) -> Result<Self> {
34 if Memory::size(&memory) != 0 {
35 return Err(Error::NotEmpty);
36 }
37 Self::reset(memory, value)
38 }
39
40 /// Explicitly replace an allocation's contents with a new Cell.
41 ///
42 /// # Errors
43 /// Returns `Growth` if the allocation cannot accommodate the encoding.
44 ///
45 /// # Panics
46 /// Panics if encoding fails, violates the declared bound, or backing IO
47 /// fails. A native mutation panic poisons the backing owner.
48 pub fn reset(memory: RuntimeMemory<M>, value: T) -> Result<Self> {
49 #[cfg(not(target_arch = "wasm32"))]
50 let _guard = memory.poison_on_unwind();
51 let bytes = encode(&value);
52 let encoded_length = bytes.len();
53 if !write_payload(&memory, &bytes, None) {
54 return Err(Error::Growth);
55 }
56 drop(bytes);
57 Ok(Self {
58 memory,
59 value,
60 encoded_length,
61 })
62 }
63
64 /// Open a Cell without modifying its allocation.
65 ///
66 /// The smaller of `maximum` and the type's declared ceiling is checked
67 /// before allocating or reading the application payload.
68 ///
69 /// # Errors
70 /// Returns a Cell framing error if framing, extent or size admission fails.
71 ///
72 /// # Panics
73 /// Panics if decoding fails, the length violates a fixed-size codec bound,
74 /// or backing IO fails. Decode failure releases the lease without poisoning
75 /// the owner or changing the persisted image.
76 pub fn load(memory: RuntimeMemory<M>, maximum: usize) -> Result<Self> {
77 let maximum = match T::BOUND {
78 Bound::Unbounded => maximum,
79 Bound::Bounded { max_size, .. } => maximum.min(max_size as usize),
80 };
81 let length = stable_cell_payload_length(&memory, maximum)?;
82 check_bound::<T>(length);
83 let bytes = read_payload(&memory, length);
84 let value = T::from_bytes(Cow::Owned(bytes))
85 .unwrap_or_else(|error| panic!("Cell decoding failed: {error}"));
86 Ok(Self {
87 memory,
88 value,
89 encoded_length: length,
90 })
91 }
92
93 /// Borrow the cached value without accessing backing memory or its codec.
94 #[must_use]
95 pub const fn get(&self) -> &T {
96 &self.value
97 }
98
99 /// Persist a replacement and return the previous cached value.
100 ///
101 /// # Panics
102 /// Panics on encoding or bound failure, refused growth, or backing IO
103 /// failure. A native mutation panic poisons the backing owner; subsequent
104 /// backing access and new leases are refused.
105 pub fn set(&mut self, value: T) -> T {
106 // RuntimeMemory checks owner health from its admitted heap state here,
107 // even when the replacement will need no backing IO.
108 let _ = Memory::size(&self.memory);
109 #[cfg(not(target_arch = "wasm32"))]
110 let _guard = self.memory.poison_on_unwind();
111 let bytes = encode(&value);
112 let encoded_length = bytes.len();
113 assert!(
114 write_payload(&self.memory, &bytes, Some(self.encoded_length)),
115 "Cell replacement reservation failed"
116 );
117 drop(bytes);
118 self.encoded_length = encoded_length;
119 mem::replace(&mut self.value, value)
120 }
121}
122
123fn encode<T: Storable>(value: &T) -> Cow<'_, [u8]> {
124 let bytes = value
125 .to_bytes()
126 .unwrap_or_else(|error| panic!("Cell encoding failed: {error}"));
127 check_bound::<T>(bytes.len());
128 bytes
129}
130
131fn check_bound<T: Storable>(length: usize) {
132 if let Bound::Bounded {
133 max_size,
134 is_fixed_size,
135 } = T::BOUND
136 {
137 let maximum = max_size as usize;
138 assert!(
139 length <= maximum && (!is_fixed_size || length == maximum),
140 "Cell codec length violates its declared bound"
141 );
142 }
143}