rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

Suggest `.cast()` instead of `as` for pointer casts

Open scottmcm opened this issue 2 years ago • 1 comments

What it does

Suggests using the more-scoped cast methods https://doc.rust-lang.org/std/primitive.pointer.html#method.cast https://doc.rust-lang.org/std/primitive.pointer.html#method.cast-1 for pointer casting instead of the more-general as.

Categories (optional)

  • Kind: style

(One could argue that this is more pedantic, as that's what https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless is. But I think that pointer casts are generally around unsafe code, so the pedantry is more generally appropriate.)

This helps avoid mistakes where the as cast is accidentally converting between *const _ and *mut _, for example. For pointers it's often tempting to slap on as _ to make something work, but that's a very broad conversion.

(This is not applicable for *const T <-> *mut T casts, which this lint should not warn about.)

Drawbacks

None.

Example

From https://users.rust-lang.org/t/converting-between-unsized-transparent-types-safely-in-place/67680/19?u=scottmcm

impl<T> From<OrderedVecSet<T>> for Rc<OrderedVecSetUnsized<T>>
where
    T: Ord,
{
    fn from(set: OrderedVecSet<T>) -> Self {
        let rc: Rc<[T]> = set.0.into();
        unsafe { Rc::from_raw(Rc::into_raw(rc) as _) }
    }
}

Could be written as:

impl<T> From<OrderedVecSet<T>> for Rc<OrderedVecSetUnsized<T>>
where
    T: Ord,
{
    fn from(set: OrderedVecSet<T>) -> Self {
        let rc: Rc<[T]> = set.0.into();
        unsafe { Rc::from_raw(Rc::into_raw(rc).cast()) }
    }
}

scottmcm avatar Nov 22 '21 06:11 scottmcm

Does this seem implemented as clippy::ptr_as_ptr?

taiki-e avatar Jul 23 '22 04:07 taiki-e

Does ptr_as_ptr support the new cast_{mut,ref}?

SUPERCILEX avatar Nov 05 '22 04:11 SUPERCILEX

Does ptr_as_ptr support the new cast_{mut,ref}?

This is now covered by ptr_cast_constness.

Centri3 avatar May 31 '23 03:05 Centri3