Skip to content

Instantly share code, notes, and snippets.

@sug0
Created April 26, 2025 10:48
Show Gist options
  • Save sug0/316596367aeb052334c89a55e9d69625 to your computer and use it in GitHub Desktop.
Save sug0/316596367aeb052334c89a55e9d69625 to your computer and use it in GitHub Desktop.
Cond Rust macro with likely/unlikely branch optimizations
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