#closures #ensure #optimization #call #effect #with #noalias

no-std with_closure

通过展开为闭包调用,确保 noalias 优化生效

3 个版本

0.1.2 2023 年 7 月 23 日
0.1.1 2023 年 7 月 22 日
0.1.0 2023 年 7 月 21 日

#238 in 无标准库

MIT/Apache

8KB
76

With Closure

通过展开为闭包调用,确保 noalias 优化生效。

实现

此库只包含一个宏定义,但前 12 个项目已展开以确保参数传递。

#[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)
    };
}

原因和用法

由于编译器限制,某些代码无法实现完全的别名优化。

pub fn foo(mut x: Vec<i32>) {
    x[0] = 1;
    println!("do something");
    if x[0] != 1 {
        println!("branch");
    }
}

编译器无法删除分支。

在传递函数之后,编译器了解到了这一点。

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");
        }
    });
}

已删除分支。

无运行时依赖