multiversion-0.8.0/.cargo_vcs_info.json0000644000000001520000000000100135770ustar { "git": { "sha1": "c1a7c68a2c7e3c70b57b05f251c0ade189fe5057" }, "path_in_vcs": "multiversion" }multiversion-0.8.0/Cargo.toml0000644000000037120000000000100116020ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "multiversion" version = "0.8.0" authors = ["Caleb Zulawski "] build = false include = [ "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**", "/benches/**", ] autobins = false autoexamples = false autotests = false autobenches = false description = "Easy function multiversioning" readme = "README.md" categories = [ "hardware-support", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/calebzulawski/multiversion" [lib] name = "multiversion" path = "src/lib.rs" [[test]] name = "async_fn" path = "tests/async_fn.rs" [[test]] name = "attrs" path = "tests/attrs.rs" [[test]] name = "cfg" path = "tests/cfg.rs" [[test]] name = "choose_dispatcher" path = "tests/choose_dispatcher.rs" [[test]] name = "clones" path = "tests/clones.rs" [[test]] name = "destructure" path = "tests/destructure.rs" [[test]] name = "generics" path = "tests/generics.rs" [[test]] name = "helpers" path = "tests/helpers.rs" [[test]] name = "impl_trait" path = "tests/impl_trait.rs" [[test]] name = "simd" path = "tests/simd.rs" [[bench]] name = "benchmark" path = "benches/benchmark.rs" harness = false [dependencies.multiversion-macros] version = "0.8.0" default-features = false [dependencies.target-features] version = "0.1" [dev-dependencies.criterion] version = "0.4" [dev-dependencies.rustversion] version = "1" [features] default = ["std"] std = ["multiversion-macros/std"] multiversion-0.8.0/Cargo.toml.orig000064400000000000000000000014131046102023000152570ustar 00000000000000[package] name = "multiversion" version = "0.8.0" authors = ["Caleb Zulawski "] license = "MIT OR Apache-2.0" description = "Easy function multiversioning" repository = "https://github.com/calebzulawski/multiversion" categories = ["hardware-support", "no-std"] readme = "README.md" include = [ "/Cargo.toml", "/LICENSE-APACHE", "/LICENSE-MIT", "/README.md", "/src/**", "/tests/**", "/benches/**", ] edition = "2021" [features] default = ["std"] std = ["multiversion-macros/std"] [dependencies] multiversion-macros = { version = "0.8.0", path = "../multiversion-macros", default-features = false } target-features = "0.1" [dev-dependencies] rustversion = "1" criterion = "0.4" [[bench]] name = "benchmark" harness = false multiversion-0.8.0/LICENSE-APACHE000064400000000000000000000261361046102023000143250ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. multiversion-0.8.0/LICENSE-MIT000064400000000000000000000020361046102023000140260ustar 00000000000000Copyright 2019 Caleb Zulawski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. multiversion-0.8.0/README.md000064400000000000000000000031531046102023000136520ustar 00000000000000Multiversion ============ [![Crates.io](https://img.shields.io/crates/v/multiversion)](https://crates.io/crates/multiversion) [![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/multiversion) ![Rustc Version 1.61+](https://img.shields.io/badge/rustc-1.61+-lightgray.svg) [![License](https://img.shields.io/crates/l/multiversion)](https://crates.io/crates/multiversion) Function multiversioning attribute macros for Rust. ## What is function multiversioning? Many CPU architectures have a variety of instruction set extensions that provide additional functionality. Common examples are single instruction, multiple data (SIMD) extensions such as SSE and AVX on x86/x86-64 and NEON on ARM/AArch64. When available, these extended features can provide significant speed improvements to some functions. These optional features cannot be haphazardly compiled into programs--executing an unsupported instruction will result in a crash. **Function multiversioning** is the practice of compiling multiple versions of a function with various features enabled and safely detecting which version to use at runtime. ## Example The `multiversion` macro compiles a function for multiple possible targets, and selects the optimal one at runtime: ```rust use multiversion::multiversion; #[multiversion(targets("x86_64+avx", "aarch64+neon"))] fn square(x: &mut [f32]) { for v in x { *v *= *v; } } ``` ## License Multiversion is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) for details. multiversion-0.8.0/benches/benchmark.rs000064400000000000000000000031121046102023000162750ustar 00000000000000use criterion::{black_box, criterion_group, criterion_main, Criterion}; use multiversion::multiversion; #[cfg(feature = "std")] #[multiversion(targets = "simd", dispatcher = "indirect")] fn indirect_fn(values: &mut [f32]) { for v in values { *v *= *v; } } #[cfg(feature = "std")] #[multiversion(targets = "simd", dispatcher = "direct")] fn direct_fn(values: &mut [f32]) { for v in values { *v *= *v; } } #[multiversion(targets = "simd", dispatcher = "static")] fn static_fn(values: &mut [f32]) { for v in values { *v *= *v; } } fn base_fn(values: &mut [f32]) { for v in values { *v *= *v; } } pub fn benchmark_dispatcher(c: &mut Criterion) { // Don't profile initial feature detection #[cfg(feature = "std")] { indirect_fn(&mut []); direct_fn(&mut []); } for len in &[0, 16, 1000] { let mut g = c.benchmark_group(format!("{len} elements")); let mut i = vec![0f32; *len]; #[cfg(feature = "std")] g.bench_function("indirect dispatcher", |b| { b.iter(|| indirect_fn(black_box(i.as_mut()))) }) .bench_function("direct dispatcher", |b| { b.iter(|| direct_fn(black_box(i.as_mut()))) }); g.bench_function("static dispatcher", |b| { b.iter(|| static_fn(black_box(i.as_mut()))) }) .bench_function("no multiversioning", |b| { b.iter(|| base_fn(black_box(i.as_mut()))) }); g.finish(); } } criterion_group!(benches, benchmark_dispatcher); criterion_main!(benches); multiversion-0.8.0/src/lib.rs000064400000000000000000000227371046102023000143070ustar 00000000000000#![allow(clippy::needless_doctest_main)] //! This crate provides the [`multiversion`] attribute for implementing function multiversioning. //! //! Many CPU architectures have a variety of instruction set extensions that provide additional //! functionality. Common examples are single instruction, multiple data (SIMD) extensions such as //! SSE and AVX on x86/x86-64 and NEON on ARM/AArch64. When available, these extended features can //! provide significant speed improvements to some functions. These optional features cannot be //! haphazardly compiled into programs–executing an unsupported instruction will result in a //! crash. //! //! **Function multiversioning** is the practice of compiling multiple versions of a function //! with various features enabled and safely detecting which version to use at runtime. //! //! # Cargo features //! There is one cargo feature, `std`, enabled by default. When enabled, [`multiversion`] will //! use CPU feature detection at runtime to dispatch the appropriate function. Disabling this //! feature will only allow compile-time function dispatch using `#[cfg(target_feature)]` and can //! be used in `#[no_std]` crates. //! //! # Capabilities //! The intention of this crate is to allow nearly any function to be multiversioned. //! The following cases are not supported: //! * functions that use `self` or `Self` //! * `impl Trait` return types (arguments are fine) //! //! If any other functions do not work please file an issue on GitHub. //! //! # Target specification strings //! Targets are specified as a combination of architecture (as specified in [`target_arch`]) and //! feature (as specified in [`target_feature`]). //! //! A target can be specified as: //! * `"arch"` //! * `"arch+feature"` //! * `"arch+feature1+feature2"` //! //! A particular CPU can also be specified with a slash: //! * `"arch/cpu"` //! * `"arch/cpu+feature"` //! //! The following are some valid target specification strings: //! * `"x86"` (matches the `"x86"` architecture) //! * `"x86_64+avx+avx2"` (matches the `"x86_64"` architecture with the `"avx"` and `"avx2"` //! features) //! * `"x86_64/x86-64-v2"` (matches the `"x86_64"` architecture with the `"x86-64-v2"` CPU) //! * `"x86/i686+avx"` (matches the `"x86"` architecture with the `"i686"` CPU and `"avx"` //! feature) //! * `"arm+neon"` (matches the `arm` architecture with the `"neon"` feature //! //! A complete list of available target features and CPUs is available in the [`target-features` //! crate documentation](target_features::docs). //! //! [`target`]: attr.target.html //! [`multiversion`]: attr.multiversion.html //! [`target_arch`]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_arch //! [`target_feature`]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature /// Provides function multiversioning. /// /// The annotated function is compiled multiple times, once for each target, and the /// best target is selected at runtime. /// /// Options: /// * `targets` /// * Takes a list of targets, such as `targets("x86_64+avx2", "x86_64+sse4.1")`. /// * Target priority is first to last. The first matching target is used. /// * May also take a special value `targets = "simd"` to automatically multiversion for common /// SIMD target features. /// * `attrs` /// * Takes a list of attributes to attach to each target clone function. /// * `dispatcher` /// * Selects the preferred dispatcher. Defaults to `default`. /// * `default`: If the `std` feature is enabled, uses either `direct` or `indirect`, /// attempting to choose the fastest choice. If the `std` feature is not enabled, uses `static`. /// * `static`: Detects features at compile time from the enabled target features. /// * `indirect`: Detect features at runtime, and dispatches with an indirect function call. /// Cannot be used for generic functions, `async` functions, or functions that take or return an /// `impl Trait`. This is usually the default. /// * `direct`: Detects features at runtime, and dispatches with direct function calls. This is /// the default on functions that do not support indirect dispatch, or in the presence of /// indirect branch exploit mitigations such as retpolines. /// /// # Example /// This function is a good candidate for optimization using SIMD. /// The following compiles `square` three times, once for each target and once for the generic /// target. Calling `square` selects the appropriate version at runtime. /// /// ``` /// use multiversion::multiversion; /// /// #[multiversion(targets("x86_64+avx", "x86+sse"))] /// fn square(x: &mut [f32]) { /// for v in x { /// *v *= *v /// } /// } /// ``` /// /// This example is similar, but targets all supported SIMD instruction sets (not just the two shown above): /// /// ``` /// use multiversion::multiversion; /// /// #[multiversion(targets = "simd")] /// fn square(x: &mut [f32]) { /// for v in x { /// *v *= *v /// } /// } /// ``` /// /// # Notes on dispatcher performance /// /// ### Feature detection is performed only once /// The `direct` and `indirect` dispatchers perform function selection on the first invocation. /// This is implemented with a static atomic variable containing the selected function. /// /// This implementation has a few benefits: /// * The function selector is typically only invoked once. Subsequent calls are reduced to an /// atomic load. /// * If called in multiple threads, there is no contention. Both threads may perform feature /// detection, but the atomic ensures these are synchronized correctly. /// /// ### Dispatcher elision /// If the optimal set of features is already known to exist at compile time, the entire dispatcher /// is elided. For example, if the highest priority target requires `avx512f` and the function is /// compiled with `RUSTFLAGS=-Ctarget-cpu=skylake-avx512`, the function is not multiversioned and /// the highest priority target is used. /// /// [`target`]: attr.target.html /// [`multiversion`]: attr.multiversion.html pub use multiversion_macros::multiversion; /// Provides a less verbose equivalent to the `cfg(target_arch)` and `target_feature` attributes. /// /// A function tagged with `#[target("x86_64+avx+avx2")]`, for example, is equivalent to a /// function tagged with each of: /// * `#[cfg(target_arch = "x86_64")]` /// * `#[target_feature(enable = "avx")]` /// * `#[target_feature(enable = "avx2")]` /// /// The [`target`] attribute is intended to be used in tandem with the [`multiversion`] attribute /// to produce hand-written multiversioned functions. /// /// [`target`]: attr.target.html /// [`multiversion`]: attr.multiversion.html pub use multiversion_macros::target; /// Inherit the `target_feature` attributes of the selected target in a multiversioned function. /// /// # Example /// ``` /// use multiversion::{multiversion, inherit_target}; /// #[multiversion(targets = "simd")] /// fn select_sum() -> unsafe fn(x: &mut[f32]) -> f32 { /// #[inherit_target] /// unsafe fn sum(x: &mut[f32]) -> f32 { /// x.iter().sum() /// } /// sum as unsafe fn(&mut[f32]) -> f32 /// } pub use multiversion_macros::inherit_target; /// Information related to the current target. pub mod target { // used by docs #[allow(unused)] use super::*; /// Get the selected target in a multiversioned function. /// /// Returns the selected target as a [`Target`]. /// /// This macro only works in a function marked with [`multiversion`]. /// /// # Example /// ``` /// use multiversion::{multiversion, target::selected_target}; /// /// #[multiversion(targets = "simd")] /// fn foo() { /// if selected_target!().supports_feature_str("avx") { /// println!("AVX detected"); /// } else { /// println!("AVX not detected"); /// } /// } pub use multiversion_macros::selected_target; /// Equivalent to `#[cfg]`, but considers `target_feature`s detected at runtime. /// /// This macro only works in a function marked with [`multiversion`]. pub use multiversion_macros::target_cfg; /// Equivalent to `#[cfg_attr]`, but considers `target_feature`s detected at runtime. /// /// This macro only works in a function marked with [`multiversion`]. pub use multiversion_macros::target_cfg_attr; /// Match the selected target. /// /// Matching is done at compile time, as if by `#[cfg]`. Target matching considers both /// detected features and statically-enabled features. Arms that do not match are not /// compiled. /// /// This macro only works in a function marked with [`multiversion`]. /// /// # Example /// ``` /// use multiversion::{multiversion, target::match_target}; /// /// #[multiversion(targets = "simd")] /// fn foo() { /// match_target! { /// "x86_64+avx" => println!("x86-64 with AVX"), /// "aarch64+neon" => println!("AArch64 with Neon"), /// _ => println!("another architecture"), /// } /// } /// ``` pub use multiversion_macros::match_target; /// Equivalent to `cfg!`, but considers `target_feature`s detected at runtime. /// /// This macro only works in a function marked with [`multiversion`]. pub use multiversion_macros::target_cfg_f; #[doc(hidden)] pub use multiversion_macros::{ match_target_impl, target_cfg_attr_impl, target_cfg_f_impl, target_cfg_impl, }; #[doc(no_inline)] pub use target_features::Target; } #[doc(hidden)] pub use target_features; multiversion-0.8.0/tests/async_fn.rs000064400000000000000000000032371046102023000157060ustar 00000000000000#[rustversion::since(1.39)] #[multiversion::multiversion(targets("x86_64+avx", "x86_64+sse", "aarch64+neon",))] async fn async_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } mod test { // Adapted from David Tolnay's async-trait. // Provided under Apache License, Version 2.0 or MIT license. #[rustversion::since(1.39)] pub fn block_on(mut fut: F) -> F::Output { use std::pin::Pin; use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; unsafe fn clone(_null: *const ()) -> RawWaker { unimplemented!() } unsafe fn wake(_null: *const ()) { unimplemented!() } unsafe fn wake_by_ref(_null: *const ()) { unimplemented!() } unsafe fn drop(_null: *const ()) {} let data = std::ptr::null(); let vtable = &RawWakerVTable::new(clone, wake, wake_by_ref, drop); let raw_waker = RawWaker::new(data, vtable); let waker = unsafe { Waker::from_raw(raw_waker) }; let mut cx = Context::from_waker(&waker); // fut does not move until it gets dropped. let fut = unsafe { Pin::new_unchecked(&mut fut) }; match fut.poll(&mut cx) { Poll::Ready(output) => output, Poll::Pending => panic!("future did not resolve immediately"), } } #[rustversion::since(1.39)] #[test] fn async_fn() { let mut a = vec![0f32, 2f32, 4f32]; let b = vec![1f32, 1f32, 1f32]; let fut = super::async_add(&mut a, &b); block_on(fut); assert_eq!(a, vec![1f32, 3f32, 5f32]); } } multiversion-0.8.0/tests/attrs.rs000064400000000000000000000003711046102023000152370ustar 00000000000000#[multiversion::multiversion(targets("x86_64+avx"), attrs(track_caller, inline(never)))] #[allow(dead_code)] // this attribute should only be attached to the multiversioned `inner_attrs` function, and none of the function clones fn inner_attrs() {} multiversion-0.8.0/tests/cfg.rs000064400000000000000000000042651046102023000146470ustar 00000000000000use multiversion::{ multiversion, target::{match_target, selected_target, target_cfg, target_cfg_attr, target_cfg_f}, }; #[test] fn cfg() { #[multiversion(targets = "simd")] fn foo() { #[target_cfg(all(target_arch = "x86_64", target_feature = "avx"))] fn test_avx(has_avx: bool) { assert!(has_avx); } #[target_cfg(not(all(target_arch = "x86_64", target_feature = "avx")))] fn test_avx(has_avx: bool) { assert!(!has_avx); } let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); test_avx(has_avx); } foo(); } #[test] fn cfg_attr() { #[multiversion(targets = "simd")] fn foo() { #[target_cfg_attr(all(target_arch = "x86_64", target_feature = "avx"), cfg(all()))] #[target_cfg_attr(not(all(target_arch = "x86_64", target_feature = "avx")), cfg(any()))] fn test_avx(has_avx: bool) { assert!(has_avx); } #[target_cfg_attr(all(target_arch = "x86_64", target_feature = "avx"), cfg(any()))] #[target_cfg_attr(not(all(target_arch = "x86_64", target_feature = "avx")), cfg(all()))] fn test_avx(has_avx: bool) { assert!(!has_avx); } let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); test_avx(has_avx); } foo(); } #[test] fn cfg_f() { #[multiversion(targets = "simd")] fn foo() { let cfg_avx = target_cfg_f!(all(target_arch = "x86_64", target_feature = "avx")); let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); assert_eq!(cfg_avx, has_avx); } foo(); } #[test] fn match_target() { #[multiversion(targets = "simd")] fn foo() { let match_avx = match_target! { "x86_64+avx" => true, "aarch64+neon" | "x86_64+sse" => false, _ => false, }; let has_avx = std::env::consts::ARCH == "x86_64" && selected_target!().supports_feature_str("avx"); assert_eq!(match_avx, has_avx); } foo(); } multiversion-0.8.0/tests/choose_dispatcher.rs000064400000000000000000000022371046102023000175730ustar 00000000000000use multiversion::multiversion; #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "default" )] fn default_dispatch() {} #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "static" )] fn static_dispatch() {} #[cfg(feature = "std")] #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "direct" )] fn direct_dispatch() {} #[cfg(feature = "std")] #[multiversion( targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon"), dispatcher = "indirect" )] fn indirect_dispatch() {} // Since x86_64 always has sse, this should never result in runtime dispatch #[multiversion(targets("x86_64+sse"), dispatcher = "default")] fn skip_dispatch() {} // Since aarch64 always has neon, this should never result in runtime dispatch #[multiversion(targets("aarch64+neon"), dispatcher = "default")] fn skip_dispatch_2() {} #[test] fn dispatchers() { default_dispatch(); static_dispatch(); #[cfg(feature = "std")] direct_dispatch(); #[cfg(feature = "std")] indirect_dispatch(); skip_dispatch(); skip_dispatch_2(); } multiversion-0.8.0/tests/clones.rs000064400000000000000000000024531046102023000153700ustar 00000000000000use multiversion::multiversion; #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] pub fn pub_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] fn priv_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] pub unsafe fn pub_unsafe_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } #[multiversion(targets("x86_64+avx", "x86+avx", "x86+sse", "aarch64+neon",))] unsafe fn priv_unsafe_add(a: &mut [f32], b: &[f32]) { a.iter_mut().zip(b.iter()).for_each(|(a, b)| *a += b); } mod test { use super::*; #[test] fn test_add() { let mut a = vec![0f32, 2f32, 4f32]; let b = vec![1f32, 1f32, 1f32]; pub_add(&mut a, &b); assert_eq!(a, vec![1f32, 3f32, 5f32]); priv_add(&mut a, &b); assert_eq!(a, vec![2f32, 4f32, 6f32]); unsafe { pub_unsafe_add(&mut a, &b); } assert_eq!(a, vec![3f32, 5f32, 7f32]); unsafe { priv_unsafe_add(&mut a, &b); } assert_eq!(a, vec![4f32, 6f32, 8f32]); } } multiversion-0.8.0/tests/destructure.rs000064400000000000000000000022541046102023000164550ustar 00000000000000struct Foo { x: i64, y: i64, } #[multiversion::multiversion(targets("x86_64+avx", "aarch64+neon"))] fn destructure_tuple_multiversion((x, y): (i64, i64)) -> (i64, i64) { (x, y) } #[multiversion::multiversion(targets("x86_64+avx", "aarch64+neon"))] fn destructure_struct_multiversion(Foo { x, y }: Foo) -> (i64, i64) { (x, y) } #[multiversion::multiversion(targets("x86_64+avx", "aarch64+neon"))] fn destructure_tuple((x, y): (i64, i64)) -> (i64, i64) { (x, y) } #[multiversion::multiversion(targets("x86_64+avx", "aarch64+neon"))] fn destructure_struct(Foo { x, y }: Foo) -> (i64, i64) { (x, y) } #[multiversion::multiversion(targets("x86_64+avx", "aarch64+neon"))] fn destructure_tuple_generic((x, y): (T, T)) -> (T, T) { (x, y) } #[cfg(test)] mod test { use super::*; #[test] fn destructure() { assert_eq!(destructure_tuple((1, 2)), (1, 2)); assert_eq!(destructure_tuple_multiversion((3, 4)), (3, 4)); assert_eq!(destructure_struct(Foo { x: 1, y: 2 }), (1, 2)); assert_eq!(destructure_struct_multiversion(Foo { x: 3, y: 4 }), (3, 4)); assert_eq!(destructure_tuple_generic((1i64, 2i64)), (1, 2)); } } multiversion-0.8.0/tests/generics.rs000064400000000000000000000020331046102023000156760ustar 00000000000000#![allow(clippy::needless_lifetimes)] #[rustversion::since(1.51)] #[multiversion::multiversion(targets( "x86_64+avx2+avx", "x86_64+avx", "x86+avx2+avx", "x86+avx", "x86+sse" ))] fn pass<'a>(x: &'a i32) -> &'a i32 { x } #[rustversion::since(1.51)] #[multiversion::multiversion(targets( "x86_64+avx2+avx", "x86_64+avx", "x86+avx2+avx", "x86+avx", "x86+sse" ))] fn double<'a, T: Copy + std::ops::AddAssign, const N: usize>(x: &'a mut [T; N]) -> &'a mut T { assert!(!x.is_empty()); for v in x.iter_mut() { *v += *v; } &mut x[0] } mod test { #[rustversion::since(1.51)] #[test] fn generics() { let mut x = [0u32, 2u32, 4u32]; let mut y = [0u64, 2u64, 4u64]; *super::double(&mut x) = 1; *super::double(&mut y) = 2; assert_eq!(x, [1u32, 4u32, 8u32]); assert_eq!(y, [2u64, 4u64, 8u64]); } #[rustversion::since(1.51)] #[test] fn lifetimes() { let a = 42; assert_eq!(super::pass(&a), &a); } } multiversion-0.8.0/tests/helpers.rs000064400000000000000000000005041046102023000155420ustar 00000000000000#[multiversion::multiversion(targets = "simd")] fn foo() { const WIDTH: Option = multiversion::target::selected_target!().suggested_simd_width::(); println!("{WIDTH:?}"); #[allow(unused)] #[multiversion::inherit_target] unsafe fn inherited() {} } #[test] fn helpers() { foo() } multiversion-0.8.0/tests/impl_trait.rs000064400000000000000000000005701046102023000162470ustar 00000000000000#[multiversion::multiversion(targets("x86_64+avx2"))] fn sum(input: impl AsRef<[i64]>) -> i64 { input.as_ref().iter().sum() } #[multiversion::multiversion(targets("x86_64+avx2"))] fn sum_ref(input: &impl AsRef<[i64]>) -> i64 { input.as_ref().iter().sum() } #[test] fn impl_trait() { assert_eq!(sum([0, 1, 2, 3]), 6); assert_eq!(sum_ref(&[0, 1, 2, 3]), 6); } multiversion-0.8.0/tests/simd.rs000064400000000000000000000001211046102023000150270ustar 00000000000000#[multiversion::multiversion(targets = "simd")] #[allow(dead_code)] fn simd() {}