Skip to main content

ic_storage/adapter/
cell.rs

1//! One cached application value persisted under an exclusive governed lease.
2
3use 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
10///
11/// `StableCell`
12///
13/// An application value cached in memory and persisted in an exclusive Storage
14/// allocation. Dropping the Cell releases its lease without changing its bytes.
15///
16pub 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    /// Create a Cell only in an empty allocation.
24    ///
25    /// # Panics
26    /// Panics on encoding, backing or growth failure.
27    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    /// Explicitly replace an allocation's contents with a new Cell.
35    ///
36    /// # Panics
37    /// Panics on encoding, backing or growth failure.
38    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    /// Open a Cell without modifying its allocation.
53    ///
54    /// The type's declared ceiling is checked
55    /// before allocating or reading the application payload.
56    ///
57    /// # Errors
58    /// Returns a Cell framing error if framing, extent or size admission fails.
59    ///
60    /// # Panics
61    /// Panics if decoding fails, the length violates a fixed-size codec bound,
62    /// or backing IO fails. Decode failure releases the lease without writing.
63    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    /// Borrow the cached value without accessing backing memory or its codec.
80    #[must_use]
81    pub const fn get(&self) -> &T {
82        &self.value
83    }
84
85    /// Persist a replacement and return the previous cached value.
86    ///
87    /// # Panics
88    /// Panics on encoding or bound failure, refused growth, or backing IO
89    /// failure.
90    pub fn set(&mut self, value: T) -> T {
91        // RuntimeMemory checks owner health from its admitted heap state here,
92        // even when the replacement will need no backing IO.
93        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}