diff --git a/src/gallium/frontends/rusticl/util/string.rs b/src/gallium/frontends/rusticl/util/string.rs index a5a8646d1fc..5e74144cc3b 100644 --- a/src/gallium/frontends/rusticl/util/string.rs +++ b/src/gallium/frontends/rusticl/util/string.rs @@ -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::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::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());