rusticl/util: add CStrExt::from_ptr_or_empty

Reviewed-by: @LingMan
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/42021>
This commit is contained in:
Karol Herbst 2026-06-04 15:36:33 +02:00 committed by Marge Bot
parent 23b0d9c6f7
commit 33f6c01caa

View file

@ -30,10 +30,23 @@ pub unsafe fn char_arr_to_cstr(c_str: &[c_char]) -> &CStr {
}
pub trait CStrExt: ToOwned {
/// # Safety
///
/// The same as CStr::from_ptr except that ptr can be a NULL pointer.
unsafe fn from_ptr_or_empty<'a>(ptr: &'a *const c_char) -> &'a Self;
fn concat(&self, other: impl AsRef<Self>) -> Self::Owned;
}
impl CStrExt for CStr {
#[inline]
unsafe fn from_ptr_or_empty<'a>(ptr: &'a *const c_char) -> &'a Self {
if ptr.is_null() {
return c"";
}
// SAFETY: Callers responsibility
unsafe { CStr::from_ptr(*ptr) }
}
fn concat(&self, other: impl AsRef<Self>) -> Self::Owned {
let other = other.as_ref();
@ -50,6 +63,16 @@ impl CStrExt for CStr {
}
}
#[test]
fn test_from_ptr_or_empty() {
assert_eq!(unsafe { CStr::from_ptr_or_empty(&std::ptr::null()) }, c"");
let some_str = c"SomeStr";
assert_eq!(
unsafe { CStr::from_ptr_or_empty(&some_str.as_ptr()) },
some_str
);
}
#[test]
fn test_concat_cstr() {
assert_eq!(c"Test".concat(c"Other"), c"TestOther".to_owned());