3 releases
0.1.2 | Jul 23, 2023 |
---|---|
0.1.1 | Jul 22, 2023 |
0.1.0 | Jul 21, 2023 |
#308 in No standard library
8KB
76 lines
With Closure
Ensure that the noalias
optimization takes effect by expanding to closure call.
Implementation
This library only contains one macro definition, but the first 12 items have been expanded to ensure parameter transfer.
#[doc(hidden)]
#[inline(always)]
pub fn with<A, F: FnOnce(A) -> R, R>(a: A, f: F) -> R {
f(a)
}
#[macro_export]
macro_rules! with {
($($a:pat = $va:expr,)* $f:block) => {
$crate::with(($($va,)*), |($($a,)*)| $f)
};
}
Reason and usage
Due to compiler limitations, some code cannot achieve complete alias optimization.
pub fn foo(mut x: Vec<i32>) {
x[0] = 1;
println!("do something");
if x[0] != 1 {
println!("branch");
}
}
The compiler cannot delete the branch.
After passing a function, the compiler learned about this.
pub fn foo(mut x: Vec<i32>) {
with!(x = x.as_mut_slice(), {
x[0] = 1;
println!("do something");
if x[0] != 1 {
println!("branch");
}
});
}
Branch deleted.