• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 write;
12 pub use write::DiplomatWrite;
13 pub use write::{diplomat_buffer_write_create, diplomat_buffer_write_destroy};
14 mod slices;
15 pub use slices::{
16     DiplomatOwnedSlice, DiplomatOwnedStr16Slice, DiplomatOwnedStrSlice, DiplomatOwnedUTF8StrSlice,
17     DiplomatSlice, DiplomatSliceMut, DiplomatStr16Slice, DiplomatStrSlice, DiplomatUtf8StrSlice,
18 };
19 
20 mod callback;
21 pub use callback::DiplomatCallback;
22 
23 mod result;
24 pub use result::{DiplomatOption, DiplomatResult};
25 
26 /// Like [`char`], but unvalidated.
27 pub type DiplomatChar = u32;
28 
29 /// Like [`str`], but unvalidated.
30 pub type DiplomatStr = [u8];
31 
32 /// Like `Wstr`, but unvalidated.
33 pub type DiplomatStr16 = [u16];
34 
35 /// Like [`u8`], but interpreted explicitly as a raw byte as opposed to a numerical value.
36 /// This matters for languages like JavaScript or Dart, where there's only a single numeric
37 /// type, but special types for byte buffers.
38 pub type DiplomatByte = u8;
39 
40 /// Allocates a buffer of a given size in Rust's memory.
41 ///
42 /// # Safety
43 /// - The allocated buffer must be freed with [`diplomat_free()`].
44 #[no_mangle]
diplomat_alloc(size: usize, align: usize) -> *mut u845 pub unsafe extern "C" fn diplomat_alloc(size: usize, align: usize) -> *mut u8 {
46     alloc::alloc::alloc(Layout::from_size_align(size, align).unwrap())
47 }
48 
49 /// Frees a buffer that was allocated in Rust's memory.
50 /// # Safety
51 /// - `ptr` must be a pointer to a valid buffer allocated by [`diplomat_alloc()`].
52 #[no_mangle]
diplomat_free(ptr: *mut u8, size: usize, align: usize)53 pub unsafe extern "C" fn diplomat_free(ptr: *mut u8, size: usize, align: usize) {
54     alloc::alloc::dealloc(ptr, Layout::from_size_align(size, align).unwrap())
55 }
56 
57 /// Whether a `&[u8]` is a `&str`
58 /// # Safety
59 /// - `ptr` and `size` must be a valid `&[u8]`
60 #[no_mangle]
diplomat_is_str(ptr: *const u8, size: usize) -> bool61 pub unsafe extern "C" fn diplomat_is_str(ptr: *const u8, size: usize) -> bool {
62     core::str::from_utf8(core::slice::from_raw_parts(ptr, size)).is_ok()
63 }
64