mirror of
https://gitlab.freedesktop.org/mesa/mesa.git
synced 2026-06-10 01:18:18 +02:00
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:
parent
23b0d9c6f7
commit
33f6c01caa
1 changed files with 23 additions and 0 deletions
|
|
@ -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());
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue