Is there a stable way to use likely/unlikely on branch prediction?

In my case I want to use 'unlikely' to check some error which has a low chance to happen. I found that std::intrinsics::unlikely is unstable since it's an intrinsic, but I only found one crate called likely stable (and all others are RFCs), and it implement likely as below:

pub const fn likely(b: bool) -> bool {
    #[allow(clippy::needless_bool)]
    if (1i32).checked_div(if b { 1 } else { 0 }).is_some() {
        true
    } else {
        false
    }
}

I don't understand how it works. Will it has performance issue? Any other way to use likely in Rust?

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.