@@ -10,6 +10,7 @@ mod cast_ptr_alignment;
1010mod cast_ref_to_mut;
1111mod cast_sign_loss;
1212mod cast_slice_different_sizes;
13+ mod cast_slice_from_raw_parts;
1314mod char_lit_as_u8;
1415mod fn_to_numeric_cast;
1516mod fn_to_numeric_cast_any;
@@ -568,6 +569,31 @@ declare_clippy_lint! {
568569 pedantic,
569570 "borrowing just to cast to a raw pointer"
570571}
572+ declare_clippy_lint ! {
573+ /// **What it does:** Checks for a raw slice being cast to a slice pointer
574+ ///
575+ /// ### Why is this bad?
576+ /// This can result in multiple `&mut` references to the same location when only a pointer is
577+ /// required.
578+ /// `ptr::slice_from_raw_parts` is a safe alternative that doesn't require
579+ /// the same [safety requirements] to be upheld.
580+ ///
581+ /// ### Example
582+ /// ```rust,ignore
583+ /// let _: *const [u8] = std::slice::from_raw_parts(ptr, len) as *const _;
584+ /// let _: *mut [u8] = std::slice::from_raw_parts_mut(ptr, len) as *mut _;
585+ /// ```
586+ /// Use instead:
587+ /// ```rust,ignore
588+ /// let _: *const [u8] = std::ptr::slice_from_raw_parts(ptr, len);
589+ /// let _: *mut [u8] = std::ptr::slice_from_raw_parts_mut(ptr, len);
590+ /// ```
591+ /// [safety requirements]: https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html#safety
592+ #[ clippy:: version = "1.64.0" ]
593+ pub CAST_SLICE_FROM_RAW_PARTS ,
594+ suspicious,
595+ "casting a slice created from a pointer and length to a slice pointer"
596+ }
571597
572598pub struct Casts {
573599 msrv : Option < RustcVersion > ,
@@ -600,6 +626,7 @@ impl_lint_pass!(Casts => [
600626 CAST_ABS_TO_UNSIGNED ,
601627 AS_UNDERSCORE ,
602628 BORROW_AS_PTR ,
629+ CAST_SLICE_FROM_RAW_PARTS
603630] ) ;
604631
605632impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -624,7 +651,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
624651 if unnecessary_cast:: check ( cx, expr, cast_expr, cast_from, cast_to) {
625652 return ;
626653 }
627-
654+ cast_slice_from_raw_parts :: check ( cx , expr , cast_expr , cast_to , self . msrv ) ;
628655 fn_to_numeric_cast_any:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
629656 fn_to_numeric_cast:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
630657 fn_to_numeric_cast_with_truncation:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
0 commit comments