use crate::{
DefaultMemoryImpl, Memory, RuntimeMemory,
stable_cell::{read_payload, stable_cell_payload_length, write_payload},
storable::{Bound, Storable},
};
use std::{borrow::Cow, mem};
pub struct StableCell<T: Storable, M: Memory = DefaultMemoryImpl> {
memory: RuntimeMemory<M>,
value: T,
encoded_length: usize,
}
impl<T: Storable, M: Memory> StableCell<T, M> {
pub fn create(memory: RuntimeMemory<M>, value: T) -> Self {
if Memory::size(&memory) != 0 {
panic!("collection memory is not empty");
}
Self::reset(memory, value)
}
pub fn reset(memory: RuntimeMemory<M>, value: T) -> Self {
let bytes = encode(&value);
let encoded_length = bytes.len();
if !write_payload(&memory, &bytes, None) {
panic!("cell growth failed");
}
drop(bytes);
Self {
memory,
value,
encoded_length,
}
}
pub fn load(memory: RuntimeMemory<M>) -> Result<Self, crate::StableCellPayloadError> {
let maximum = match T::BOUND {
Bound::Unbounded => usize::MAX,
Bound::Bounded { max_size, .. } => max_size as usize,
};
let length = stable_cell_payload_length(&memory, maximum)?;
check_bound::<T>(length);
let bytes = read_payload(&memory, length);
let value = T::from_bytes(Cow::Owned(bytes));
Ok(Self {
memory,
value,
encoded_length: length,
})
}
#[must_use]
pub const fn get(&self) -> &T {
&self.value
}
pub fn set(&mut self, value: T) -> T {
let _ = Memory::size(&self.memory);
let bytes = encode(&value);
let encoded_length = bytes.len();
assert!(
write_payload(&self.memory, &bytes, Some(self.encoded_length)),
"Cell replacement reservation failed"
);
drop(bytes);
self.encoded_length = encoded_length;
mem::replace(&mut self.value, value)
}
}
fn encode<T: Storable>(value: &T) -> Cow<'_, [u8]> {
let bytes = value.to_bytes();
check_bound::<T>(bytes.len());
bytes
}
fn check_bound<T: Storable>(length: usize) {
assert!(
T::BOUND.accepts_length(length),
"Cell codec length violates its declared bound"
);
}