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