Rust

Rust

Made by DeepSource

Transmute from integer type to char RS-E1030

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.

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 integer to char type is considered bad in Rust as it can lead to undefined behavior. This is because Rust’s char type is a Unicode scalar value, which is a 32-bit value, while integer types are 8, 16, 32, or 64 bits wide.

When you transmute an integer to a char, you are essentially interpreting the bits of the integer as a Unicode scalar value, which would lead to invalid Unicode scalar values which may produce undefined behaviour.

Bad practice

fn main() {
    let x: u32 = 0x0000_0061;
    let c: char = unsafe { std::mem::transmute(x) };
    println!("{}", c); // prints 'a'

    let x: u32 = 0x0000_D800;
    let c: char = unsafe { std::mem::transmute(x) };
    println!("{}", c); // undefined behavior
}

Recommended

fn main() {
    let x: u32 = 0x0000_0061;
    let c: char = x as u8 as char;
    println!("{}", c); // prints 'a'
}