feat(core/rust): improve behavior of from_c_str / from_c_array

pull/2879/head
matejcik 1 year ago
parent 7e96b96d00
commit e10b6ecc26

@ -7,25 +7,15 @@ pub use super::model_tr::screens::*;
pub use super::model_tt::screens::*;
use crate::ui::util::from_c_str;
macro_rules! convert_str {
($str:expr) => {
if ($str).is_null() {
""
} else {
unwrap!(unsafe { from_c_str($str) })
}
};
}
#[no_mangle]
extern "C" fn screen_fatal_error_rust(
title: *const cty::c_char,
msg: *const cty::c_char,
footer: *const cty::c_char,
) {
let title = convert_str!(title);
let msg = convert_str!(msg);
let footer = convert_str!(footer);
let title = unsafe { from_c_str(title) }.unwrap_or("");
let msg = unsafe { from_c_str(msg) }.unwrap_or("");
let footer = unsafe { from_c_str(footer) }.unwrap_or("");
screen_fatal_error(title, msg, footer);
}

@ -45,11 +45,13 @@ pub fn u32_to_str(num: u32, buffer: &mut [u8]) -> Option<&str> {
/// # Safety
///
/// The caller is responsible that the pointer is valid, which means that:
/// (a) it is not null,
/// (b) it points to a memory containing a valid C string (zero-terminated
/// (a) it points to a memory containing a valid C string (zero-terminated
/// sequence of characters), and
/// (c) that the pointer has appropriate lifetime.
/// (b) that the pointer has appropriate lifetime.
pub unsafe fn from_c_str<'a>(c_str: *const cty::c_char) -> Option<&'a str> {
if c_str.is_null() {
return None;
}
unsafe {
let bytes = CStr::from_ptr(c_str).to_bytes();
if bytes.is_ascii() {
@ -65,11 +67,13 @@ pub unsafe fn from_c_str<'a>(c_str: *const cty::c_char) -> Option<&'a str> {
/// # Safety
///
/// The caller is responsible that the pointer is valid, which means that:
/// (a) it is not null,
/// (b) it points to a memory containing array of characters, with length `len`,
/// (a) it points to a memory containing array of characters, with length `len`,
/// and
/// (c) that the pointer has appropriate lifetime.
/// (b) that the pointer has appropriate lifetime.
pub unsafe fn from_c_array<'a>(c_str: *const cty::c_char, len: usize) -> Option<&'a str> {
if c_str.is_null() {
return None;
}
unsafe {
let slice = core::slice::from_raw_parts(c_str as *const u8, len);
if slice.is_ascii() {

Loading…
Cancel
Save