`unsafe_code` lint and unsafe method

unsafe_code documentation states:

This lint is intended to restrict the usage of unsafe blocks and other constructs (including, but not limited to no_mangle , link_section and export_name attributes) wrong usage of which causes undefined behavior.

However, defining/implementing an unsafe function/method without using any unsafe operation should not cause any undefined behavior. Could we relax the lint to authorize it?

Take the example of this trait:

trait WriteSlot {
    fn slot_size(&self) -> usize;
    /// # Safety
    /// `slot` slice's length must be equal to the result of [`Self::slot_size`]
    unsafe fn write_slot(self, slot: &mut [u8]);
}

Implementor of this trait could choose to use the precondition to do some unsafe optimization, e.g. core::ptr::copy_non_overlapping without checking the size, but he can also choose to ignore the precondition and simply use safe code like <[u8]>::copy_from_slice. In this case, I find quite unfair to have the lint triggered while I'm just using an API safely.

2 Likes

There are things in the works that will address this.

  • Once RFC 2316 or its successor RFC 3245 refined impls is implemented, it will be possible to implement the trait without using the unsafe keyword at all.
  • Once unsafe blocks and unsafe fns are separated, which is in progress, it should be possible to write an unsafe fn without triggering the unsafe_code lint, because unsafe fn will mean only “unsafe to call”, not “unsafe operations may be in here”.
8 Likes