A practical example

One of the methods in the library takes a vector of int values to perform a mean, median, and mode calculation, which in turn returns an array of float values containing these values. However, we need to validate the values first (essentially, test the array is not empty) and that there are five or more values. This will return a boolean.

The unsafe version of the code would be:

[link(name="mathlib")] 
extern 
 { 
     fn check_mean_mode_median(a: Vec<i32>) -> bool; 
} 

We can create a wrapper for this quite simply:

pub fn calc_mean_mode_median_check(a:Vec<int32>) -> bool 
 { 
    unsafe 
 { 
        check_mean_mode_median(a) == 0; 
    } 
} 

We expose the safe function to the code and hide (wrap) the unsafe part. Once we have a value of true returned, we know the data is safe to have the calculation.

Now, this is a pretty pointless piece of code (it is simply a test to ensure we have the right number of parameters in the vector). Let's modify this wrapper so that we return a Vec<f32>, which will  contain -999f, -999f, or -999f if the check fails, or mean, median and mode of the values of the vector.

The issue though is that the original library is in C, so we need to get the results as an array and then put that into a vector.

The first part is making the first check:

pub fn mean_mode_median(a: Vec<int32>) -> Vec<f32> 
{ 
    // we can have this result outside of the unsafe as it is a guaranteed parameter 
    // it must be mutable as it is used to store the result if the result is returned 
    let mut result = vec![-999f32, -999f32, -999f32]; 
    unsafe 
 { 
        if check_mean_mode_median(a) != 0 
 { 
             return result; 
        } 
 else 
 { 
             let res = calc_mean_median_mode(a); 
              
result = res.to_vec(); 
             return result; 
       
        } 
    } 
} 

Not only do we now have a single call to the external library, but we also have guarantees the compiler needs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset