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
#[cfg(test)]
use stdarch_test::assert_instr;

extern "C" {
    #[link_name = "llvm.wasm.memory.grow"]
    fn llvm_memory_grow(mem: u32, pages: usize) -> usize;
    #[link_name = "llvm.wasm.memory.size"]
    fn llvm_memory_size(mem: u32) -> usize;
}

/// 对应 wasm 的 [`memory.size` 指令][instr]
///
/// 调用此函数时,它将以页为单位返回当前的内存大小。
/// 当前的 WebAssembly 页面大小为 65536 字节 (64 KB)。
///
/// 参数 `MEM` 是返回内存大小的数字索引。
/// 请注意,当前 WebAssembly 规范仅支持一个内存,因此要求传入零。
///
/// 该参数与 future WebAssembly 修订版向前兼容。
/// 如果将非零参数传递给此函数,则它将当前无条件中止。
///
/// [instr]: http://webassembly.github.io/spec/core/exec/instructions.html#exec-memory-size
#[inline]
#[cfg_attr(test, assert_instr("memory.size", MEM = 0))]
#[rustc_legacy_const_generics(0)]
#[stable(feature = "simd_wasm32", since = "1.33.0")]
#[doc(alias("memory.size"))]
pub fn memory_size<const MEM: u32>() -> usize {
    static_assert!(MEM == 0);
    unsafe { llvm_memory_size(MEM) }
}

/// 对应 wasm 的 [`memory.grow` 指令][instr]
///
/// 调用此函数时,它将尝试通过指定的 `delta` 页增长默认的线性内存。
/// 当前的 WebAssembly 页面大小为
/// 65536 字节 (64 KB)。如果成功增加了内存,则将返回先前的内存大小 (以页为单位)。
/// 如果无法增加内存,则返回 `usize::MAX`。
///
/// 参数 `MEM` 是返回内存大小的数字索引。
/// 请注意,当前 WebAssembly 规范仅支持一个内存,因此要求传入零。
///
/// 该参数与 future WebAssembly 修订版向前兼容。
/// 如果将非零参数传递给此函数,则它将当前无条件中止。
///
/// [instr]: http://webassembly.github.io/spec/core/exec/instructions.html#exec-memory-grow
///
#[inline]
#[cfg_attr(test, assert_instr("memory.grow", MEM = 0))]
#[rustc_legacy_const_generics(0)]
#[stable(feature = "simd_wasm32", since = "1.33.0")]
#[doc(alias("memory.grow"))]
pub fn memory_grow<const MEM: u32>(delta: usize) -> usize {
    unsafe {
        static_assert!(MEM == 0);
        llvm_memory_grow(MEM, delta)
    }
}