ic_stable_structures/
ic0_memory.rs

1use crate::Memory;
2
3#[link(wasm_import_module = "ic0")]
4extern "C" {
5    pub fn stable64_size() -> u64;
6    pub fn stable64_grow(additional_pages: u64) -> i64;
7    pub fn stable64_read(dst: u64, offset: u64, size: u64);
8    pub fn stable64_write(offset: u64, src: u64, size: u64);
9}
10
11#[derive(Clone, Copy, Default)]
12pub struct Ic0StableMemory;
13
14impl Memory for Ic0StableMemory {
15    #[inline]
16    fn size(&self) -> u64 {
17        // SAFETY: This is safe because of the ic0 api guarantees.
18        unsafe { stable64_size() }
19    }
20
21    #[inline]
22    fn grow(&self, pages: u64) -> i64 {
23        // SAFETY: This is safe because of the ic0 api guarantees.
24        unsafe { stable64_grow(pages) }
25    }
26
27    #[inline]
28    fn read(&self, offset: u64, dst: &mut [u8]) {
29        // SAFETY: This is safe because of the ic0 api guarantees.
30        unsafe { stable64_read(dst.as_ptr() as u64, offset, dst.len() as u64) }
31    }
32
33    #[inline]
34    unsafe fn read_unsafe(&self, offset: u64, dst: *mut u8, count: usize) {
35        // SAFETY: This is safe because of the ic0 api guarantees.
36        stable64_read(dst as u64, offset, count as u64);
37    }
38
39    #[inline]
40    fn write(&self, offset: u64, src: &[u8]) {
41        // SAFETY: This is safe because of the ic0 api guarantees.
42        unsafe { stable64_write(offset, src.as_ptr() as u64, src.len() as u64) }
43    }
44}