Why is this an issue?

Using size_of::<T> or size_of_val::<T> as a count of elements is misleading because these functions are meant to return the size in bytes, not the count of elements. This can lead to logical errors in the code.

Code examples

Noncompliant code example

const SIZE: usize = 128;
let x = [2u8; SIZE];
let mut y = [2u8; SIZE];
unsafe { std::ptr::copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), std::mem::size_of::<u8>() * SIZE) }; // Noncompliant: uses size_of::<u8>() to determine element count.

Compliant solution

const SIZE: usize = 128;
let x = [2u8; SIZE];
let mut y = [2u8; SIZE];
unsafe { std::ptr::copy_nonoverlapping(x.as_ptr(), y.as_mut_ptr(), SIZE) }; // Compliant: uses the actual element count.

Resources

Documentation