rust-clippy
rust-clippy copied to clipboard
Suggest `.cast()` instead of `as` for pointer casts
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()) }
}
}
Does this seem implemented as clippy::ptr_as_ptr?
Does ptr_as_ptr support the new cast_{mut,ref}?
Does ptr_as_ptr support the new
cast_{mut,ref}?
This is now covered by ptr_cast_constness.