canic_core/ops/storage/
memory.rs

1pub use canic_memory::{MemoryRange, MemoryRegistryEntry, MemoryRegistryView};
2
3use crate::{
4    CRATE_NAME, Error, ThisError, log,
5    log::Topic,
6    model::memory::{CANIC_MEMORY_MAX, CANIC_MEMORY_MIN},
7    ops::storage::StorageOpsError,
8};
9use canic_memory::{
10    MemoryRegistryError,
11    ops::{MemoryRegistryOps as BaseRegistryOps, MemoryRegistrySummary},
12};
13
14///
15/// MemoryRegistryOpsError
16///
17
18#[derive(Debug, ThisError)]
19pub enum MemoryRegistryOpsError {
20    #[error(transparent)]
21    MemoryRegistryError(#[from] MemoryRegistryError),
22}
23
24impl From<MemoryRegistryOpsError> for Error {
25    fn from(err: MemoryRegistryOpsError) -> Self {
26        StorageOpsError::from(err).into()
27    }
28}
29
30///
31/// MemoryRegistryOps
32/// Ops wrapper around the global memory registry.
33///
34
35pub struct MemoryRegistryOps;
36
37impl MemoryRegistryOps {
38    /// Initialise all registered memory segments and ranges.
39    ///
40    /// - Reserves the internal canic range.
41    /// - Applies all deferred range reservations.
42    /// - Applies all deferred registrations (sorted by ID).
43    /// - Emits summary logs per range.
44    pub fn init_memory() -> Result<(), Error> {
45        let summary =
46            BaseRegistryOps::init_memory(Some((CRATE_NAME, CANIC_MEMORY_MIN, CANIC_MEMORY_MAX)))
47                .map_err(MemoryRegistryOpsError::from)?;
48
49        Self::log_summary(&summary);
50
51        Ok(())
52    }
53
54    fn log_summary(summary: &MemoryRegistrySummary) {
55        let entries = &summary.entries;
56
57        for (crate_name, range) in &summary.ranges {
58            let count = entries.iter().filter(|(id, _)| range.contains(*id)).count();
59
60            log!(
61                Topic::Memory,
62                Info,
63                "💾 memory.range: {} [{}-{}] ({}/{} slots used)",
64                crate_name,
65                range.start,
66                range.end,
67                count,
68                range.end - range.start + 1,
69            );
70        }
71    }
72
73    #[must_use]
74    pub fn export() -> MemoryRegistryView {
75        BaseRegistryOps::export()
76    }
77
78    #[must_use]
79    pub fn export_ranges() -> Vec<(String, MemoryRange)> {
80        BaseRegistryOps::export_ranges()
81    }
82
83    #[must_use]
84    pub fn get(id: u8) -> Option<MemoryRegistryEntry> {
85        BaseRegistryOps::get(id)
86    }
87}