Pro@programming.dev to Programmer Humor@programming.devEnglish · 7 days agoRustprogramming.devimagemessage-square6linkfedilinkarrow-up15arrow-down10
arrow-up15arrow-down1imageRustprogramming.devPro@programming.dev to Programmer Humor@programming.devEnglish · 7 days agomessage-square6linkfedilink
minus-squarecalcopiritus@lemmy.worldlinkfedilinkarrow-up1·6 days agoRust doesn’t have “safe” and “unsafe” modes in the sense your comment alludes to. You can just do the little unsafe thing in a function that guarantees its safety, and then the rest of the code is safe. For example, using C functions from rust is unsafe, but most of the time a simple wrapper can be made safe. Example C function: int arraysum(const int *array, int length) { int sum = 0; while (length > 0) { sum += *array; array++; length--; } } In rust, you can call that function safely by just wrapping it with a function that makes sure that length is always the size of array. Such as: fn rust_arraysum(array: Vec<i32>) -> i32 { unsafe{ arraysum(array.as_ptr(), array.len() as i32)} } Even though unsafe is used, it is perfectly safe to do so. And now we can call rust_arraysum without entering “unsafe mode” You could do similar wrappers if you want to write your embedded code. Where only a fraction of the code is potentially unsafe. And even in unsafe blocks, you don’t disable all of the rust checks.
Rust doesn’t have “safe” and “unsafe” modes in the sense your comment alludes to.
You can just do the little unsafe thing in a function that guarantees its safety, and then the rest of the code is safe.
For example, using C functions from rust is unsafe, but most of the time a simple wrapper can be made safe.
Example C function:
int arraysum(const int *array, int length) { int sum = 0; while (length > 0) { sum += *array; array++; length--; } }
In rust, you can call that function safely by just wrapping it with a function that makes sure that
length
is always the size ofarray
. Such as:fn rust_arraysum(array: Vec<i32>) -> i32 { unsafe{ arraysum(array.as_ptr(), array.len() as i32)} }
Even though
unsafe
is used, it is perfectly safe to do so. And now we can callrust_arraysum
without entering “unsafe mode”You could do similar wrappers if you want to write your embedded code. Where only a fraction of the code is potentially unsafe.
And even in unsafe blocks, you don’t disable all of the rust checks.