with_closure

Crates.iowith_closure
lib.rswith_closure
version0.1.2
sourcesrc
created_at2023-07-21 04:27:29.909185
updated_at2023-07-23 06:35:50.786083
descriptionEnsure that the `noalias` optimization takes effect by expanding to closure call
homepage
repositoryhttps://github.com/823984418/with_closure
max_upload_size
id922077
size7,700
(823984418)

documentation

README

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.

Commit count: 2

cargo fmt