diplomat_runtime/
lib.rs

1#![cfg_attr(not(any(target_arch = "wasm32")), no_std)]
2
3extern crate alloc;
4
5use alloc::alloc::Layout;
6
7#[cfg(target_arch = "wasm32")]
8// defines `extern "C" diplomat_init()`
9mod wasm_glue;
10
11mod writeable;
12pub use writeable::DiplomatWriteable;
13
14mod result;
15pub use result::DiplomatResult;
16
17/// Like [`char`], but unvalidated.
18pub type DiplomatChar = u32;
19
20/// Like [`str`], but unvalidated.
21pub type DiplomatStr = [u8];
22
23/// Like `Wstr`, but unvalidated.
24pub 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.
29pub 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]
36pub 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]
44pub 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}