use std::cell::RefCell; use crate::status::{EGUICL_ERR_INVALID_ARGUMENT, Error, Result}; thread_local! { static RETURNED_STRING: RefCell = const { RefCell::new(String::new()) }; } /// Borrows a UTF-8 argument passed as pointer and length. /// /// # Safety /// `ptr` must point to `len` readable bytes that outlive the returned slice. pub unsafe fn str_arg<'a>(ptr: *const u8, len: usize) -> Result<&'a str> { if ptr.is_null() { return if len == 0 { Ok("") } else { Err(Error::new( EGUICL_ERR_INVALID_ARGUMENT, "null string pointer with nonzero length", )) }; } // SAFETY: the caller guarantees `ptr` addresses `len` readable bytes. let bytes = unsafe { std::slice::from_raw_parts(ptr, len) }; std::str::from_utf8(bytes).map_err(|e| { Error::new( EGUICL_ERR_INVALID_ARGUMENT, format!("string is not valid UTF-8: {e}"), ) }) } /// Hands a string back to Lisp. The bytes stay valid until the next string is /// returned on the same thread. pub fn return_string(value: String, out_ptr: *mut *const u8, out_len: *mut usize) -> Result<()> { if out_ptr.is_null() || out_len.is_null() { return Err(Error::new(EGUICL_ERR_INVALID_ARGUMENT, "null out-pointer")); } RETURNED_STRING.with(|slot| { let mut slot = slot.borrow_mut(); *slot = value; // SAFETY: both out-pointers were checked for null; Lisp passes pointers to // its own foreign memory of the right type. unsafe { *out_ptr = slot.as_ptr(); *out_len = slot.len(); } }); Ok(()) } pub fn write_out(out: *mut T, value: T) -> Result<()> { if out.is_null() { return Err(Error::new(EGUICL_ERR_INVALID_ARGUMENT, "null out-pointer")); } // SAFETY: checked for null; Lisp passes a pointer to foreign memory of type T. unsafe { out.write(value) }; Ok(()) }