When a transmute is placed within an expression that uses eager evaluation (like bool::then_some), it will execute even if a preceding
validity check fails. This can result in creating invalid values, potentially leading to undefined behavior.
Use lazy evaluation (for example by replacing then_some with then) and providing a closure that contains the transmute.
This ensures the transmute only occurs if the validity check passes.
#[repr(u8)]
enum Opcode {
Add = 0,
Sub = 1,
Mul = 2,
Div = 3
}
fn int_to_opcode(op: u8) -> Option<Opcode> {
(op < 4).then_some(unsafe { std::mem::transmute(op) })
}
#[repr(u8)]
enum Opcode {
Add = 0,
Sub = 1,
Mul = 2,
Div = 3
}
fn int_to_opcode(op: u8) -> Option<Opcode> {
(op < 4).then(|| unsafe { std::mem::transmute(op) })
}