1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use ic_kit_sys::ic0;
use ic_kit_sys::types::StableMemoryError;
#[cfg(feature = "experimental-stable64")]
pub type StableSize = u64;
#[cfg(not(feature = "experimental-stable64"))]
pub type StableSize = u32;
#[inline(always)]
pub fn stable_size() -> StableSize {
#[cfg(not(feature = "experimental-stable64"))]
unsafe {
ic0::stable_size() as u32
}
#[cfg(feature = "experimental-stable64")]
unsafe {
ic0::stable64_size() as u64
}
}
#[inline(always)]
pub fn stable_grow(new_pages: StableSize) -> Result<StableSize, StableMemoryError> {
#[cfg(not(feature = "experimental-stable64"))]
unsafe {
match ic0::stable_grow(new_pages as i32) {
-1 => Err(StableMemoryError::OutOfMemory),
x => Ok(x as u32),
}
}
#[cfg(feature = "experimental-stable64")]
unsafe {
match if new_pages < (u32::MAX as u64 - 1) {
ic0::stable_grow(new_pages as i32) as i64
} else {
ic0::stable64_grow(new_pages as i64) as i64
} {
-1 => Err(StableMemoryError::OutOfMemory),
x => Ok(x as u64),
}
}
}
#[inline(always)]
pub fn stable_write(offset: StableSize, buf: &[u8]) {
#[cfg(not(feature = "experimental-stable64"))]
unsafe {
ic0::stable_write(offset as i32, buf.as_ptr() as isize, buf.len() as isize)
}
#[cfg(feature = "experimental-stable64")]
unsafe {
if offset < (u32::MAX as u64 - 1) {
ic0::stable_write(offset as i32, buf.as_ptr() as isize, buf.len() as isize)
} else {
ic0::stable64_write(offset as i64, buf.as_ptr() as i64, buf.len() as i64)
}
}
}
#[inline(always)]
pub fn stable_read(offset: StableSize, buf: &mut [u8]) {
#[cfg(not(feature = "experimental-stable64"))]
unsafe {
ic0::stable_read(buf.as_ptr() as isize, offset as i32, buf.len() as isize);
};
#[cfg(feature = "experimental-stable64")]
unsafe {
if offset < (u32::MAX as u64 - 1) {
ic0::stable_read(buf.as_ptr() as isize, offset as i32, buf.len() as isize);
} else {
ic0::stable64_read(buf.as_ptr() as i64, offset as i64, buf.len() as i64);
}
}
}
pub(crate) fn stable_bytes() -> Vec<u8> {
let size = (stable_size() as usize) << 16;
let mut vec = Vec::with_capacity(size);
unsafe {
ic0::stable_read(vec.as_ptr() as isize, 0, size as isize);
vec.set_len(size);
}
vec
}