ic_storage/adapter/
cell.rs1use crate::{
4 DefaultMemoryImpl, Memory, RuntimeMemory,
5 stable_cell::{read_payload, stable_cell_payload_length, write_payload},
6 storable::{Bound, Storable},
7};
8use std::{borrow::Cow, mem};
9
10pub struct StableCell<T: Storable, M: Memory = DefaultMemoryImpl> {
17 memory: RuntimeMemory<M>,
18 value: T,
19 encoded_length: usize,
20}
21
22impl<T: Storable, M: Memory> StableCell<T, M> {
23 pub fn create(memory: RuntimeMemory<M>, value: T) -> Self {
28 if Memory::size(&memory) != 0 {
29 panic!("collection memory is not empty");
30 }
31 Self::reset(memory, value)
32 }
33
34 pub fn reset(memory: RuntimeMemory<M>, value: T) -> Self {
39 let bytes = encode(&value);
40 let encoded_length = bytes.len();
41 if !write_payload(&memory, &bytes, None) {
42 panic!("cell growth failed");
43 }
44 drop(bytes);
45 Self {
46 memory,
47 value,
48 encoded_length,
49 }
50 }
51
52 pub fn load(memory: RuntimeMemory<M>) -> Result<Self, crate::StableCellPayloadError> {
64 let maximum = match T::BOUND {
65 Bound::Unbounded => usize::MAX,
66 Bound::Bounded { max_size, .. } => max_size as usize,
67 };
68 let length = stable_cell_payload_length(&memory, maximum)?;
69 check_bound::<T>(length);
70 let bytes = read_payload(&memory, length);
71 let value = T::from_bytes(Cow::Owned(bytes));
72 Ok(Self {
73 memory,
74 value,
75 encoded_length: length,
76 })
77 }
78
79 #[must_use]
81 pub const fn get(&self) -> &T {
82 &self.value
83 }
84
85 pub fn set(&mut self, value: T) -> T {
91 let _ = Memory::size(&self.memory);
94 let bytes = encode(&value);
95 let encoded_length = bytes.len();
96 assert!(
97 write_payload(&self.memory, &bytes, Some(self.encoded_length)),
98 "Cell replacement reservation failed"
99 );
100 drop(bytes);
101 self.encoded_length = encoded_length;
102 mem::replace(&mut self.value, value)
103 }
104}
105
106fn encode<T: Storable>(value: &T) -> Cow<'_, [u8]> {
107 let bytes = value.to_bytes();
108 check_bound::<T>(bytes.len());
109 bytes
110}
111
112fn check_bound<T: Storable>(length: usize) {
113 if let Bound::Bounded {
114 max_size,
115 is_fixed_size,
116 } = T::BOUND
117 {
118 let maximum = max_size as usize;
119 assert!(
120 length <= maximum && (!is_fixed_size || length == maximum),
121 "Cell codec length violates its declared bound"
122 );
123 }
124}