Runtime detection of target features
To safely use an optional target feature, the program must detect it at runtime. Once a feature is detected, it can be safely used:
#[target_feature(enable = "avx")] unsafe fn use_avx() { println!("This function uses AVX!") } fn main() { if is_x86_feature_detected!("avx") { unsafe { use_avx() } } else { println!("We can't use AVX."); } }
In this example, the target_feature
attribute enables the avx
feature.
Unlike setting the target features with RUSTFLAGS
, this limits the features to particular functions.
The is_*_feature_detected
macros can then be used to check if the feature is supported, and safely handle the situation where the feature is not present.