Function show_notes::e029::add

source ·
pub fn add(a: i32, b: i32) -> Option<i32>
Expand description

A safe interface for the unsafe ffi::add.

Note that this particular check is as silly as calling out to C for addition is, but it shows how you can provide a safe wrapper for a case where C’s implementation differences might actually matter to you.

While it might seem that something like addition is trivially safe, it turns out to be mostly safe. The behavior of overflow for signed integers is not defined for C. In Rust, it is defined, by RFC #0560: in modes where debug_assertions are enabled, an overflow will cause a panic; in modes where those assertions are not enabled (i.e. release mode), Rust wraps them by two’s complement. The net of that is that even something this simple can have unexpected results when calling across the FFI boundary.

assert_eq!(add(1, 2), Some(3));