stringrustffi

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


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?


Solution

  • As of Rust 1.77, you can do c"VK_KHR_get_physical_device_properties2".


    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);