raylib_wasm/util/
small_c_string.rs1use std::{ptr, slice};
4use std::mem::MaybeUninit;
5use std::ffi::{CStr, CString};
6
7#[cfg(not(target_os = "espidf"))]
10const MAX_STACK_ALLOCATION: usize = 384;
11#[cfg(target_os = "espidf")]
12const MAX_STACK_ALLOCATION: usize = 32;
13
14#[inline]
15pub fn run_with_cstr<R>(bytes: &[u8], f: impl FnOnce(&CStr) -> R) -> R {
16 if bytes.len() >= MAX_STACK_ALLOCATION {
19 run_with_cstr_allocating(bytes, f)
20 } else {
21 unsafe { run_with_cstr_stack(bytes, f) }
22 }
23}
24
25#[inline]
29unsafe fn run_with_cstr_stack<R>(
30 bytes: &[u8],
31 f: impl FnOnce(&CStr) -> R,
32) -> R {
33 let mut buf = MaybeUninit::<[u8; MAX_STACK_ALLOCATION]>::uninit();
34 let buf_ptr = buf.as_mut_ptr() as *mut u8;
35
36 unsafe {
37 ptr::copy_nonoverlapping(bytes.as_ptr(), buf_ptr, bytes.len());
38 buf_ptr.add(bytes.len()).write(0);
39 }
40
41 match CStr::from_bytes_with_nul(unsafe { slice::from_raw_parts(buf_ptr, bytes.len() + 1) }) {
42 Ok(s) => f(s),
43 Err(_) => panic!("file name contained an unexpected NUL byte")
44 }
45}
46
47#[inline]
48fn run_with_cstr_allocating<R>(bytes: &[u8], f: impl FnOnce(&CStr) -> R) -> R {
49 match CString::new(bytes) {
50 Ok(s) => f(&s),
51 Err(_) => panic!("file name contained an unexpected NUL byte")
52 }
53}