Skip to content

823984418/with_closure

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Ensure that the `noalias` optimization takes effect by expanding to closure call

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages