rspec/rules/S7420/rust/rule.adoc
github-actions[bot] 96bd90a6a9
Create rule S7420: Collections should not be transmuted to different types (#4761)
* Create rule S7420

* Update RSPEC

---------

Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
2025-03-19 13:07:22 +00:00

29 lines
848 B
Plaintext

== Why is this an issue?
Transmuting between collections of different types can lead to undefined behavior due to differences in ABI, size, or alignment. This can result in serious issues like out-of-bounds memory access.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let vec = vec![2_u16];
unsafe {
std::mem::transmute::<_, Vec<u32>>(vec); // Noncompliant: Different size, likely out-of-bounds memory access.
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
let vec = vec![2_u16];
let vec_u32: Vec<u32> = vec.into_iter().map(u32::from).collect(); // Compliant: Iterates, maps, and collects the values safely.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#unsound_collection_transmute