Unsafe tag in the standard library

Hi all,

A simple question.

Some methods in std are tagged as unsafe like from_utf8_unchecked() in the documentation.

But some, like this IntoIterator implementation, are unsafe: impl<T, A: Allocator> IntoIterator for Vec<T, A>

Any way to warn about unsafeness ?

unsafe fn means that you have to ensure some condition is true when you call it. unsafe { blocks inside a safe function are themselves obligated to be sound under all conditions. These are very different; the latter are not marked because you do not need to worry about them (unless you are concerned that the library containing them is poorly written).

It is not possible to write a practical Rust program without executing some unsafe code, because all interfaces to the outside world and resources like memory allocation require some unsafe code.

1 Like

@kpreid Thanks for the clarification :grinning:

These meanings of unsafe are actually somewhat opposite. An unsafe fn like str::from_utf8_unchecked is unsafe to call, and you need to manually uphold additional conditions when calling such API, usually presented in the documentation in a section labeled Safety.

The unsafe { … } blocks are the opposite. They mean that the author has checked the content of the block to be safe to do, and properly encapsulated. API like Vec's into_iter use unsafe code internally, but externally are safe to use and thus not declaring any warnings.

Safe encapsulation of unsafe implementation details is the power of Rust's safety story. It's always clear whose responsibility it is to make sure memory safety is ensured, and the author of a safe function (not labeled unsafe fn) that uses unsafe {} blocks internally takes the responsibility that they must make sure that all possible use-cases, including niche corner cases, are unproblematic.

(Same thing goes for properly documented unsafe fn too, though - usually they have a clear contract what conditions must be upheld, and when those turn out to be insufficient, you could blame the author for writing unsound code.)


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.