Clippy lints / Suspicious
Clippy lint · Suspicious · checked with Clippy 0.1.99
clippy::cast_slice_from_raw_parts: Checks for a raw slice being cast to a slice pointer
What it meansChecks for a raw slice being cast to a slice pointer It is in the suspicious group and warns by default.
Does it matter?
This can result in multiple &mut references to the same location when only a pointer is required. ptr::slice_from_raw_parts is a safe alternative that doesn’t require the same safety requirements to be upheld.
Code that is most likely wrong or useless. Warns by default.
How to fix it
Clippy can fix this one for you: run cargo clippy --fix (add --allow-dirty if you have uncommitted changes). Review the diff before you commit.
Flagged
let _: *const [u8] = std::slice::from_raw_parts(ptr, len) as *const _;
let _: *mut [u8] = std::slice::from_raw_parts_mut(ptr, len) as *mut _;
Write this instead
let _: *const [u8] = std::ptr::slice_from_raw_parts(ptr, len);
let _: *mut [u8] = std::ptr::slice_from_raw_parts_mut(ptr, len);
Turn it off, or on
Allow it where it does not fit your code, as narrowly as you can:
On one item
#[allow(clippy::cast_slice_from_raw_parts)]
fn my_function() { /* ... */ }Whole crate (Cargo.toml)
[lints.clippy]
cast_slice_from_raw_parts = "allow"One run
cargo clippy -- -A clippy::cast-slice-from-raw-partsThe [lints] table needs Rust 1.74 or newer. In a workspace, put it under [workspace.lints.clippy] and add [lints] workspace = true to each member.
Clippy's own documentation
What it does
Checks for a raw slice being cast to a slice pointer
Why is this bad?
This can result in multiple &mut references to the same location when only a pointer is
required.
ptr::slice_from_raw_parts is a safe alternative that doesn’t require
the same safety requirements to be upheld.
Example
let _: *const [u8] = std::slice::from_raw_parts(ptr, len) as *const _;
let _: *mut [u8] = std::slice::from_raw_parts_mut(ptr, len) as *mut _;
Use instead:
let _: *const [u8] = std::ptr::slice_from_raw_parts(ptr, len);
let _: *mut [u8] = std::ptr::slice_from_raw_parts_mut(ptr, len);
From the Clippy lint list (0.1.99), part of the Rust project, MIT or Apache-2.0. Official entry.
Related lints
- cast_enum_constructorcast of an enum tuple constructor to an integer
- cast_enum_truncationcasting `main::E::X` to `u8` will truncate the value
- cast_nan_to_intcasting a known NaN to u64
- confusing_method_to_numeric_castcasting function pointer `u16::max` to `usize`
- const_is_emptythis expression always evaluates to true
- crate_in_macro_def`crate` references the macro call's crate
All 847 Clippy lints · Rust compiler errors · Cargo.toml checker
Up next
Related lintclippy::cast_enum_constructorcast of an enum tuple constructor to an integerRead it next →Did this answer your question?