Created
April 26, 2025 10:48
-
-
Save sug0/316596367aeb052334c89a55e9d69625 to your computer and use it in GitHub Desktop.
Cond Rust macro with likely/unlikely branch optimizations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
macro_rules! cold { | |
($expr:expr) => {{ | |
#[cold] | |
#[inline(always)] | |
fn __cold() {} | |
__cold(); | |
$expr | |
}} | |
} | |
macro_rules! cond { | |
(unlikely default => $body:expr $(,)?) => { | |
cold!($body) | |
}; | |
(default => $body:expr $(,)?) => { | |
$body | |
}; | |
(unlikely $cond:expr => $body:expr , $($else:tt)*) => { | |
if $cond { cold!($body) } else { cond!($($else)*) } | |
}; | |
(likely $cond:expr => $body:expr , $($else:tt)*) => { | |
if $cond { $body } else { cold!(cond!($($else)*)) } | |
}; | |
($cond:expr => $body:expr , $($else:tt)*) => { | |
if $cond { $body } else { cond!($($else)*) } | |
}; | |
} | |
fn main() { | |
let x = cond! { | |
likely 3 == 3 => { | |
3 + 3 | |
}, | |
unlikely 2 == 1 => 2, | |
unlikely default => 1, | |
}; | |
println!("{x}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment