Skip to main content

ic_storage/
stable_cell.rs

1use crate::{Memory, WASM_PAGE_SIZE_BYTES};
2use thiserror::Error;
3
4/// Stable-cell magic prefix written by `ic-stable-structures Cell`.
5pub const STABLE_CELL_MAGIC: &[u8; 3] = b"SCL";
6/// Stable-cell header byte length.
7pub const STABLE_CELL_HEADER_SIZE: usize = 8;
8/// Byte offset where the stable-cell value payload starts.
9pub const STABLE_CELL_VALUE_OFFSET: u64 = STABLE_CELL_HEADER_SIZE as u64;
10
11///
12/// StableCellPayloadError
13///
14/// Stable-cell payload decode failure.
15///
16#[non_exhaustive]
17#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
18pub enum StableCellPayloadError {
19    /// Declared bytes exceed the current recovery ceiling before allocation.
20    #[error("stable-cell payload length {value_len} exceeds the caller's limit")]
21    TooLarge {
22        /// Declared payload length in bytes.
23        value_len: u64,
24    },
25    /// Memory contents do not start with the stable-cell marker.
26    #[error("memory is not a ic-stable-structures Cell")]
27    NotStableCell,
28    /// Stable-cell header length does not fit inside the memory.
29    #[error("stable-cell payload length {value_len} exceeds available bytes {available_bytes}")]
30    InvalidLength {
31        /// Encoded value length.
32        value_len: u64,
33        /// Available payload bytes in memory.
34        available_bytes: u64,
35    },
36}
37
38/// Validate a stable-cell envelope and return its payload length.
39///
40/// Reject empty/foreign memory, unsupported layouts, lengths beyond the backing
41/// extent, and lengths above the caller's `maximum`. No payload is allocated or
42/// read, and memory is never written or grown. This does not validate the value's
43/// codec or schema.
44///
45/// # Panics
46/// Propagates backing `size`/`read` failures.
47pub fn stable_cell_payload_length<M: Memory>(
48    memory: &M,
49    maximum: usize,
50) -> Result<usize, StableCellPayloadError> {
51    if memory.size() == 0 {
52        return Err(StableCellPayloadError::NotStableCell);
53    }
54
55    let mut header = [0; STABLE_CELL_HEADER_SIZE];
56    memory.read(0, &mut header);
57    if &header[..3] != STABLE_CELL_MAGIC || header[3] != 1 {
58        return Err(StableCellPayloadError::NotStableCell);
59    }
60    let value_len = u64::from(u32::from_le_bytes(header[4..8].try_into().unwrap()));
61    let available_bytes = memory.size().saturating_mul(WASM_PAGE_SIZE_BYTES);
62    let payload_capacity = available_bytes.saturating_sub(STABLE_CELL_VALUE_OFFSET);
63    if value_len > payload_capacity {
64        return Err(StableCellPayloadError::InvalidLength {
65            value_len,
66            available_bytes: payload_capacity,
67        });
68    }
69    if value_len > maximum as u64 {
70        return Err(StableCellPayloadError::TooLarge { value_len });
71    }
72    #[expect(
73        clippy::cast_possible_truncation,
74        reason = "the admitted caller ceiling is representable as usize"
75    )]
76    let value_len = value_len as usize;
77    Ok(value_len)
78}