Idiomatic way to compare a [c_char; N] with a given hardcoded string

Viewed 213

I am iterating over a bunch of null-terminated C strings of type [c_char; 256] and have to compare them against a handful of hardcoded values and ended up with the following monstrosity:

available_instance_extensions.iter().for_each(|extension| {
    if unsafe { CStr::from_ptr(extension.extension_name.as_ptr()) }
        .to_str()
        .unwrap()
        == "VK_KHR_get_physical_device_properties2"
    {
        log::info!("Got it!");
    }
});

Is there any idiomatic and sane approach to do so?

1 Answers

You can create CStr string using:

CStr::from_bytes_with_nul(b"VK_KHR_get_physical_device_properties2\0")
  .unwrap();

Also, unsafe variant:

unsafe {
  CStr::from_bytes_with_nul_unchecked(b"VK_KHR_get_physical_device_properties2\0")
};

But I advice using cstr crate, this will allow faster and shorter code:

use cstr::cstr;

let result = unsafe { CStr::from_bytes_with_nul_unchecked(&extension.extension_name[..]) };
let expected = cstr!("VK_KHR_get_physical_device_properties2");
assert_eq!(result, expected);
Related