@@ -10,6 +10,7 @@ mod cast_ptr_alignment;
10
10
mod cast_ref_to_mut;
11
11
mod cast_sign_loss;
12
12
mod cast_slice_different_sizes;
13
+ mod cast_slice_from_raw_parts;
13
14
mod char_lit_as_u8;
14
15
mod fn_to_numeric_cast;
15
16
mod fn_to_numeric_cast_any;
@@ -568,6 +569,31 @@ declare_clippy_lint! {
568
569
pedantic,
569
570
"borrowing just to cast to a raw pointer"
570
571
}
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
+ }
571
597
572
598
pub struct Casts {
573
599
msrv : Option < RustcVersion > ,
@@ -600,6 +626,7 @@ impl_lint_pass!(Casts => [
600
626
CAST_ABS_TO_UNSIGNED ,
601
627
AS_UNDERSCORE ,
602
628
BORROW_AS_PTR ,
629
+ CAST_SLICE_FROM_RAW_PARTS
603
630
] ) ;
604
631
605
632
impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -624,7 +651,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
624
651
if unnecessary_cast:: check ( cx, expr, cast_expr, cast_from, cast_to) {
625
652
return ;
626
653
}
627
-
654
+ cast_slice_from_raw_parts :: check ( cx , expr , cast_expr , cast_to , self . msrv ) ;
628
655
fn_to_numeric_cast_any:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
629
656
fn_to_numeric_cast:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
630
657
fn_to_numeric_cast_with_truncation:: check ( cx, expr, cast_expr, cast_from, cast_to) ;
0 commit comments