use super::{Bound, Memory, Storable};
use crate::substrate::{self, DefaultMemoryImpl};
use ic_memory::RuntimeMemory;
use std::borrow::Cow;
pub struct StableCell<T: Storable, M: Memory = DefaultMemoryImpl> {
inner: substrate::Cell<CellValue<T>, RuntimeMemory<M>>,
}
struct CellValue<T>(Option<T>);
impl<T: Storable> Storable for CellValue<T> {
const BOUND: Bound = T::BOUND;
fn to_bytes(&self) -> Cow<'_, [u8]> {
self.0
.as_ref()
.expect("cannot initialize a loading cell")
.to_bytes_checked()
}
fn into_bytes(self) -> Vec<u8> {
self.0
.expect("cannot initialize a loading cell")
.into_bytes_checked()
}
fn from_bytes(bytes: Cow<'_, [u8]>) -> Self {
T::check_bounds(&bytes);
Self(Some(T::from_bytes(bytes)))
}
}
impl<T: Storable, M: Memory> StableCell<T, M> {
pub fn create(memory: RuntimeMemory<M>, value: T) -> Self {
assert_eq!(memory.size(), 0, "cell memory is not empty");
Self::reset(memory, value)
}
pub fn reset(memory: RuntimeMemory<M>, value: T) -> Self {
Self {
inner: substrate::Cell::new(memory, CellValue(Some(value))),
}
}
pub fn load(memory: RuntimeMemory<M>) -> Result<Self, ic_memory::StableCellPayloadError> {
let maximum = match T::BOUND {
Bound::Bounded { max_size, .. } => max_size as usize,
Bound::Unbounded => usize::MAX,
};
ic_memory::stable_cell_payload_length(&memory, maximum)?;
Ok(Self {
inner: substrate::Cell::init(memory, CellValue(None)),
})
}
#[expect(
clippy::missing_panics_doc,
reason = "constructors always establish a cached value"
)]
pub fn get(&self) -> &T {
self.inner.get().0.as_ref().expect("loaded cell value")
}
pub fn set(&mut self, value: T) -> T {
self.inner
.set(CellValue(Some(value)))
.0
.expect("loaded cell value")
}
}