Debian Codegraph @

third_party/rust/diplomat-runtime/src/lib.rs

raw
1 #![cfg_attr(not(any(target_arch = "wasm32")), no_std)]
2
3 extern crate alloc;
4
5 use alloc::alloc::Layout;
6
7 #[cfg(target_arch = "wasm32")]
8 // defines `extern "C" diplomat_init()`
9 mod wasm_glue;
10
11 mod writeable;
12 pub use writeable::DiplomatWriteable;
13
14 mod result;
15 pub use result::DiplomatResult;
16
17 /// Like [`char`], but unvalidated.
18 pub type DiplomatChar = u32;
19
20 /// Like [`str`], but unvalidated.
21 pub type DiplomatStr = [u8];
22
23 /// Like `Wstr`, but unvalidated.
24 pub type DiplomatStr16 = [u16];
25
26 /// Like [`u8`], but interpreted explicitly as a raw byte as opposed to a numerical value.
27 /// This matters for languages like JavaScript or Dart, where there's only a single numeric
28 /// type, but special types for byte buffers.
29 pub type DiplomatByte = u8;
30
31 /// Allocates a buffer of a given size in Rust's memory.
32 ///
33 /// # Safety
34 /// - The allocated buffer must be freed with [`diplomat_free()`].
35 #[no_mangle]
36 pub unsafe extern "C" fn diplomat_alloc(size: usize, align: usize) -> *mut u8 {
37 alloc::alloc::alloc(Layout::from_size_align(size, align).unwrap())
38 }
39
40 /// Frees a buffer that was allocated in Rust's memory.
41 /// # Safety
42 /// - `ptr` must be a pointer to a valid buffer allocated by [`diplomat_alloc()`].
43 #[no_mangle]
44 pub unsafe extern "C" fn diplomat_free(ptr: *mut u8, size: usize, align: usize) {
45 alloc::alloc::dealloc(ptr, Layout::from_size_align(size, align).unwrap())
46 }