xref: /wasmtime-44.0.1/crates/c-api/src/memory.rs (revision 3b3b126f)
1 use crate::{wasm_extern_t, wasm_memorytype_t, wasm_store_t};
2 use wasmtime::{Extern, Memory};
3 
4 #[derive(Clone)]
5 #[repr(transparent)]
6 pub struct wasm_memory_t {
7     ext: wasm_extern_t,
8 }
9 
10 wasmtime_c_api_macros::declare_ref!(wasm_memory_t);
11 
12 pub type wasm_memory_pages_t = u32;
13 
14 impl wasm_memory_t {
15     pub(crate) fn try_from(e: &wasm_extern_t) -> Option<&wasm_memory_t> {
16         match &e.which {
17             Extern::Memory(_) => Some(unsafe { &*(e as *const _ as *const _) }),
18             _ => None,
19         }
20     }
21 
22     fn memory(&self) -> &Memory {
23         match &self.ext.which {
24             Extern::Memory(m) => m,
25             _ => unsafe { std::hint::unreachable_unchecked() },
26         }
27     }
28 }
29 
30 #[no_mangle]
31 pub extern "C" fn wasm_memory_new(
32     store: &wasm_store_t,
33     mt: &wasm_memorytype_t,
34 ) -> Option<Box<wasm_memory_t>> {
35     let memory = Memory::new(&store.store, mt.ty().ty.clone()).ok()?;
36     Some(Box::new(wasm_memory_t {
37         ext: wasm_extern_t {
38             which: memory.into(),
39         },
40     }))
41 }
42 
43 #[no_mangle]
44 pub extern "C" fn wasm_memory_as_extern(m: &wasm_memory_t) -> &wasm_extern_t {
45     &m.ext
46 }
47 
48 #[no_mangle]
49 pub extern "C" fn wasm_memory_type(m: &wasm_memory_t) -> Box<wasm_memorytype_t> {
50     let ty = m.memory().ty();
51     Box::new(wasm_memorytype_t::new(ty))
52 }
53 
54 #[no_mangle]
55 pub extern "C" fn wasm_memory_data(m: &wasm_memory_t) -> *mut u8 {
56     m.memory().data_ptr()
57 }
58 
59 #[no_mangle]
60 pub extern "C" fn wasm_memory_data_size(m: &wasm_memory_t) -> usize {
61     m.memory().data_size()
62 }
63 
64 #[no_mangle]
65 pub extern "C" fn wasm_memory_size(m: &wasm_memory_t) -> wasm_memory_pages_t {
66     m.memory().size()
67 }
68 
69 #[no_mangle]
70 pub extern "C" fn wasm_memory_grow(m: &wasm_memory_t, delta: wasm_memory_pages_t) -> bool {
71     m.memory().grow(delta).is_ok()
72 }
73