Rust

Rust

Made by DeepSource

Found transmute between a numeric type and array or slice RS-E1031

Bug risk
Major

In Rust, the transmute function is used to reinterpret the bits of a value of one type as another type. Hence, both types must have the same size.

Compilation will fail if this is not guaranteed. Transmute is semantically equivalent to a bitwise move of one type into another. It copies the bits from the source value into the destination value.

Hence transmuting from a numeric type to array or slice whose layouts is not fixed is considered undefined behaviour.

Consider using the to_le_bytes() method if you want to convert it to bytes array.

Bad practice

fn foo() {
    let zeroed_bytes: [u8; 8] = unsafe { std::mem::transmute(0u64) };
}

Recommended

fn foo() {
    let zeroed_bytes = 0u64.to_le_bytes();
}