How can I decide when to mark a function as unsafe?

When is it advisable to mark a function as unsafe compared to using the unsafe block? I saw this function while reading another answer :

 unsafe fn as_u8_slice(xs: &[i32]) -> &[u8] { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * std::mem::size_of::<i32>()) } 

I would probably write this function as:

 fn as_u8_slice(xs: &[i32]) -> &[u8] { unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * std::mem::size_of::<i32>()) } } 

That is, I feel that calling the function is safe in all cases, but that the internal function cannot be checked by the compiler. However, I have no rules when it is advisable to use one or the other.

+6
source share
2 answers

Mark the function as unsafe if the security of the function depends on its parameters or on the global state. If a function is safe regardless of arguments and global state, do not mark it as unsafe . Regardless of whether you consider which function using unsafe internally safe, the same as you consider the safe program C.

+11
source

unsafe designed as a local mechanism to step around a type system when the compiler cannot prove safety. If the behavior contained in unsafe is safe, that is, there is no way to call it, which will lead to memory insecurity, then there is no need to specify a general function insecure. The user does not need to worry about whether the internal functions of the function are fully implemented with safe code or with unsafe if the open interface is correct.

+4
source

Source: https://habr.com/ru/post/983792/


All Articles