When interfacing with C code, I find myself writing repetitive code like this a lot:
p_vertex_input_state: vertex_input_state
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null()),
p_input_assembly_state: input_assembly_state
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null()),
p_tessellation_state: tessellation_state
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null()),
p_viewport_state: viewport_state
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null()),
p_rasterization_state: rasterization_state
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null()),
...etc
The p_
members here are all pointers which can be null, while the other variables are Option
. Some
should be converted to a regular valid pointer, while None
should become null. At least in my case this seems like a common enough operation that it might be useful to have two additional methods on Option
:
pub fn as_ptr(&self) -> *const T {
self
.as_ref()
.map(|p| p as *const _)
.unwrap_or(ptr::null())
}
pub fn as_mut_ptr(&mut self) -> *mut T {
self
.as_mut()
.map(|p| p as *mut _)
.unwrap_or(ptr::null_mut())
}