Make the callback optional again

The C API allows passing a NULL pointer is for the callback function.
However when calling the callback nothing checks for this null pointer
and thus things fail badly.  Even worse since the C API is defined
using an "fn pointer" rather than a "*-ptr" or raw pointer to the
function rust does not realise this can be invalid and therefore the
typechecker does not catch this even though there are no unsafe casts.

Fix this by making the callback an Option in rust, this can be easily
checked when calling.  Also add a Context.call_cb() function which
simplifies calling the callback, hides the weird syntax due to the
function pointer and makes the call a little easier.  Finally it also
means the option checking is only needed in one place.

For the C API this needs to check if this is a NULL pointer or not,
this is implicitly done by rust using the "nullable pointer
optimisation":
https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization
This commit is contained in:
Floris Bruynooghe
2019-06-17 01:30:22 +02:00
parent 70bfc6d5e0
commit db9bc15d3e
19 changed files with 111 additions and 232 deletions

View File

@@ -83,7 +83,7 @@ pub unsafe fn dc_reset_tables(context: &Context, bits: i32) -> i32 {
info!(context, 0, "(8) Rest but server config reset.");
}
(context.cb)(context, Event::MSGS_CHANGED, 0 as uintptr_t, 0 as uintptr_t);
context.call_cb(Event::MSGS_CHANGED, 0 as uintptr_t, 0 as uintptr_t);
1
}
@@ -215,7 +215,7 @@ unsafe fn poke_spec(context: &Context, spec: *const libc::c_char) -> libc::c_int
as_str(real_spec)
);
if read_cnt > 0 {
(context.cb)(context, Event::MSGS_CHANGED, 0 as uintptr_t, 0 as uintptr_t);
context.call_cb(Event::MSGS_CHANGED, 0 as uintptr_t, 0 as uintptr_t);
}
success = 1
}
@@ -1180,7 +1180,7 @@ pub unsafe fn dc_cmdline(context: &Context, line: &str) -> Result<(), failure::E
"event" => {
ensure!(!arg1.is_empty(), "Argument <id> missing.");
let event = Event::from_u32(arg1.parse().unwrap()).unwrap();
let r = (context.cb)(context, event, 0 as uintptr_t, 0 as uintptr_t);
let r = context.call_cb(event, 0 as uintptr_t, 0 as uintptr_t);
println!(
"Sending event {:?}({}), received value {}.",
event, event as usize, r as libc::c_int,