Default value for nullable FFI pointer input

Have a RIIR project and to maintain an exact copy of the logic, I'm finding myself doing the below a lot. Is there a cleaner way of doing this?

pub unsafe extern "C" fn do_something(value: *mut i32) {

    let value = value.as_mut();

    // Is there a better/cleaner way of doing this?
    if let Some(value ) = value {
        *value = 123; //Set a default value
    }

    // Some other work here....

}

Another common pattern i'm finding is where an input may be a null pointer, but i want to bring it into safe-land so i create a dummy substitute variable.

pub unsafe extern "C" fn do_something(value: *mut i32) {

    // Is there a better/cleaner way of doing this?
    let mut _value = 123;
    let value = match value.as_mut() {
        Some(x) => x,
        None => &mut _value,
    };

    // Some other work here....
    other_stuff(value);

}

Your first snippet cannot really be simplified, but the second is just value.as_mut().unwrap_or(&mut default).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.