'Compare raw strings of different types and store them properly
I am currently learning Rust with Vulkan (via the ash bindings).
This is the basic code of my problem:
const REQUESTED_LAYERS: &'static [&'static str] = &["VK_LAYER_KHRONOS_validation"];
let available_layers: HashSet<[i8, _]> = entry
.enumerate_instance_layer_properties()?
.iter()
.map(|l| l.layer_name)
.collect();
let mut enabled_layers: Vec<*const c_char> = vec![];
Now my goal is to filter the REQUIRED_LAYERS depending on the available_layers. I think it's best explained with some pseudo code:
for required_layer in REQUIRED_LAYERS {
if available_layers.contains(required_layer) {
enabled_layers.push(required_layer);
}
}
It is pretty straight forward, but the problem are the types. My REQUIRED_LAYERS slice is of type &[&str], available_layers is a HashSet<[i8, _]> and enabled_layers must be a Vec<*const c_char>. (But the types in the containers are all strings, just represented differently).
Now my question is effectively how to convert all types inside of the containers so that the logic of the pseudo code would work.
I already tried creating new vectors of type Vec<CString> and then again new vectors of type Vec<CStr> but I still didn't get everything to work. This also ended in a bunch of chaos with so many vectors that I don't think are required.
This is what I got working:
let requested_layers: Vec<CString> = REQUESTED_LAYERS
.iter()
.map(|s| CString::new(*s).unwrap())
.collect();
let available_layers: HashSet<CString> = entry
.enumerate_instance_layer_properties()?
.iter()
.map(|l| unsafe { CStr::from_ptr(l.layer_name.as_ptr()).to_owned() })
.collect();
let mut enabled_layers: Vec<CString> = vec![];
for requested_layer in requested_layers {
if available_layers.contains(&requested_layer) {
println!("Added layer! {:?}", &requested_layer);
enabled_layers.push(requested_layer);
} else {
println!("Layer not available! {:?}", &requested_layer);
}
}
let enabled_layers_raw: Vec<*const c_char> = enabled_layers.iter().map(|l| l.as_ptr()).collect();
But I would love to know if you can achieve this more elegantly.
Thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
