diff --git a/Cargo.toml b/Cargo.toml index 5c0ffa3..2d06da0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,23 +1,26 @@ [package] -authors = ["Aaron Trent "] +authors = ["novacrazy "] name = "numeric-array" description = "Wrapper around generic-array that adds efficient numeric trait implementations" repository = "https://github.com/novacrazy/numeric-array" documentation = "https://docs.rs/numeric-array" -version = "0.5.2" +version = "0.6.1" readme = "README.md" keywords = ["generic", "array", "numeric", "simd"] -include = ["src/**/*", "Cargo.toml"] -license = "MIT" -categories = ["data-structures"] +include = ["src/**/*", "LICENSE-*", "README.md"] +license = "MIT OR Apache-2.0" +categories = ["data-structures", "no-std"] +edition = "2021" [dependencies] -generic-array = "0.14.4" -num-traits = "0.2" -serde = { version = "1.0", optional = true, default_features = false } +generic-array = { version = "1.1.0", default-features = false, features = ["internals"] } +num-traits = { version = "0.2", default-features = false } +serde = { version = "1.0", optional = true, default-features = false } [features] -serde1 = ["serde", "generic-array/serde"] +serde = ["dep:serde", "generic-array/serde"] +std = ["num-traits/std"] +default = ["std"] [dev-dependencies] -serde_json = "1.0" \ No newline at end of file +serde_json = "1.0" diff --git a/LICENSE-Apache b/LICENSE-Apache new file mode 100644 index 0000000..29a61b5 --- /dev/null +++ b/LICENSE-Apache @@ -0,0 +1,202 @@ + + 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 2022 Aaron Trent et al. + + 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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..b8e63a1 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2022 Aaron Trent et al. + +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. diff --git a/README.md b/README.md index 16c0ec4..d82abc8 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,11 @@ numeric-array ============= -`numeric-array` is a wrapper around [`generic-array`](https://github.com/fizyk20/generic-array) that adds efficient numeric trait implementations, often times making use of autovectorized SIMD instructions and compile-time evaluations (not const-eval, but LLVM optimizations). +[![crates.io](https://img.shields.io/crates/v/numeric-array.svg)](https://crates.io/crates/numeric-array) +[![Documentation](https://docs.rs/numeric-array/badge.svg)](https://docs.rs/numeric-array) +[![MIT/Apache-2 licensed](https://img.shields.io/crates/l/numeric-array.svg)](./LICENSE-Apache) + +`numeric-array` is a wrapper around [`generic-array`](https://github.com/fizyk20/generic-array) that adds efficient numeric trait implementations, designed to encourage LLVM to autovectorize expressions into SIMD instructions and perform compile-time evaluation. All stable `core::ops` traits are implemented for `NumericArray` itself, plus the thin `NumericConstant` type, which is required to differentiate constant values from `NumericArray` itself. @@ -10,14 +14,8 @@ Additionally, most of `num_traits` are implemented, including `Num` itself. So y Example: ```rust -extern crate num_traits; -#[macro_use] -extern crate generic_array; -#[macro_use] -extern crate numeric_array; - use num_traits::Float; -use numeric_array::NumericArray; +use numeric_array::{NumericArray, narr}; fn main() { let a = narr![f32; 1, 2, 3, 4]; @@ -31,6 +29,6 @@ fn main() { } ``` -When used with `RUSTFLAGS = "-C opt-level=3 -C target-cpu=native"`, then Rust and LLVM are smart enough to autovectorize almost all operations into SIMD instructions, or even just evaluate them at compile time. The above example is actually evaluated at compile time, so if you were to view the assembly it would show the result only. Rust is pretty smart. +When used with `RUSTFLAGS = "-C opt-level=3 -C target-cpu=native"`, then Rust and LLVM are smart enough to autovectorize almost all operations into SIMD instructions, or even just evaluate them at compile time. The above example is actually evaluated at compile time, so if you were to view the assembly it would show the result only. -Therefore, this is ideal for situations where simple component-wise operations are required for arrays. \ No newline at end of file +This is ideal for situations where simple component-wise operations are required for arrays. \ No newline at end of file diff --git a/src/geometry.rs b/src/geometry.rs index d174349..805187f 100644 --- a/src/geometry.rs +++ b/src/geometry.rs @@ -1,6 +1,6 @@ #![allow(missing_docs)] -use core::ops::{Add, Mul}; +use core::ops::Mul; use num_traits::{Signed, Zero}; @@ -16,15 +16,13 @@ pub trait Geometric { fn norm_squared(&self) -> T; } -impl> Geometric for NumericArray +impl Geometric for NumericArray where - T: Add + Mul + Zero + Copy, + T: Mul + Zero + Copy, { #[inline(always)] fn scalar_product(&self, other: &Self) -> T { - self.iter().zip(&other.0).fold(T::zero(), |sum, (l, r)| { - sum + (*l * *r) - }) + self.iter().zip(&other.0).fold(T::zero(), |sum, (l, r)| sum + (*l * *r)) } #[inline(always)] @@ -32,9 +30,7 @@ where where T: Signed, { - self.iter().zip(&other.0).fold(T::zero(), |sum, (l, r)| { - sum + (*l * *r).abs() - }) + self.iter().zip(&other.0).fold(T::zero(), |sum, (l, r)| sum + (*l * *r).abs()) } #[inline(always)] diff --git a/src/impl_serde.rs b/src/impl_serde.rs index a8e942e..41effb8 100644 --- a/src/impl_serde.rs +++ b/src/impl_serde.rs @@ -7,7 +7,7 @@ use generic_array::{ArrayLength, GenericArray}; use super::{NumericArray, NumericConstant}; -impl> Serialize for NumericArray { +impl Serialize for NumericArray { #[inline] fn serialize(&self, serializer: S) -> Result where @@ -17,7 +17,7 @@ impl> Serialize for NumericArray { } } -impl<'de, T: Deserialize<'de>, N: ArrayLength> Deserialize<'de> for NumericArray +impl<'de, T: Deserialize<'de>, N: ArrayLength> Deserialize<'de> for NumericArray where T: Default, { diff --git a/src/impls.rs b/src/impls.rs index 9834920..43f5c83 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -18,35 +18,36 @@ use super::*; +use core::mem::{self, ManuallyDrop}; use core::num::FpCategory; use core::ops::*; -use num_traits::*; +use num_traits::{float::FloatCore, *}; -use generic_array::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::{ArrayConsumer, IntrusiveArrayBuilder}; macro_rules! impl_unary_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl> $op_trait for NumericArray + impl $op_trait for NumericArray where T: $op_trait, - N: ArrayLength<::Output>, { type Output = NumericArray<::Output, N>; + #[inline(always)] fn $op(self) -> Self::Output { NumericArray(self.0.map($op_trait::$op)) } } - impl<'a, T: Clone, N: ArrayLength> $op_trait for &'a NumericArray + impl<'a, T: Clone, N: ArrayLength> $op_trait for &'a NumericArray where T: $op_trait, - N: ArrayLength<::Output>, { type Output = NumericArray<::Output, N>; + #[inline(always)] fn $op(self) -> Self::Output { NumericArray((&self.0).map(|x| $op_trait::$op(x.clone()))) } @@ -58,97 +59,97 @@ macro_rules! impl_unary_ops { macro_rules! impl_binary_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl + ArrayLength> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericArray) -> Self::Output { NumericArray(self.0.zip(rhs.0, $op_trait::$op)) } } - impl<'a, T, U: Clone, N: ArrayLength + ArrayLength> $op_trait<&'a NumericArray> for NumericArray + impl<'a, T, U: Clone, N: ArrayLength> $op_trait<&'a NumericArray> for NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: &'a NumericArray) -> Self::Output { NumericArray(self.0.zip(&rhs.0, |l, r| $op_trait::$op(l, r.clone()))) } } - impl<'a, T: Clone, U, N: ArrayLength + ArrayLength> $op_trait> for &'a NumericArray + impl<'a, T: Clone, U, N: ArrayLength> $op_trait> for &'a NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericArray) -> Self::Output { NumericArray((&self.0).zip(rhs.0, |l, r| $op_trait::$op(l.clone(), r))) } } - impl<'a, 'b, T: Clone, U: Clone, N: ArrayLength + ArrayLength> $op_trait<&'b NumericArray> for &'a NumericArray + impl<'a, 'b, T: Clone, U: Clone, N: ArrayLength> $op_trait<&'b NumericArray> for &'a NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: &'b NumericArray) -> Self::Output { NumericArray((&self.0).zip(&rhs.0, |l, r| $op_trait::$op(l.clone(), r.clone()))) } } - impl> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericConstant) -> Self::Output { NumericArray(self.0.map(|l| $op_trait::$op(l, rhs.0.clone()))) } } - impl<'a, T: Clone, U: Clone, N: ArrayLength> $op_trait> for &'a NumericArray + impl<'a, T: Clone, U: Clone, N: ArrayLength> $op_trait> for &'a NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericConstant) -> Self::Output { NumericArray((&self.0).map(|l| $op_trait::$op(l.clone(), rhs.0.clone()))) } } - impl> $op_trait> for NumericConstant + impl $op_trait> for NumericConstant where U: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericArray) -> Self::Output { NumericArray(rhs.0.map(|r| $op_trait::$op(self.0.clone(), r))) } } - impl<'a, T: Clone, U: Clone, N: ArrayLength> $op_trait<&'a NumericArray> for NumericConstant + impl<'a, T: Clone, U: Clone, N: ArrayLength> $op_trait<&'a NumericArray> for NumericConstant where U: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: &'a NumericArray) -> Self::Output { NumericArray((&rhs.0).map(|r| $op_trait::$op(self.0.clone(), r.clone()))) } @@ -160,26 +161,34 @@ macro_rules! impl_binary_ops { macro_rules! impl_assign_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl + ArrayLength> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, { fn $op(&mut self, rhs: NumericArray) { - unsafe { - let mut right = ArrayConsumer::new(rhs.0); + if mem::needs_drop::() { + unsafe { + let mut right = ArrayConsumer::new(rhs.0); - let (right_iter, right_position) = right.iter_position(); + let (right_iter, right_position) = right.iter_position(); - self.iter_mut().zip(right_iter).for_each(|(lhs, rhs)| { - $op_trait::$op(lhs, ptr::read(rhs)); + self.iter_mut().zip(right_iter).for_each(|(lhs, rhs)| { + $op_trait::$op(lhs, ptr::read(rhs)); + + *right_position += 1; + }); + } + } else { + let right = ManuallyDrop::new(rhs); - *right_position += 1; + self.iter_mut().zip(right.iter()).for_each(|(lhs, rhs)| unsafe { + $op_trait::$op(lhs, ptr::read(rhs)); }); } } } - impl<'a, T, U: Clone, N: ArrayLength + ArrayLength> $op_trait<&'a NumericArray> for NumericArray + impl<'a, T, U: Clone, N: ArrayLength> $op_trait<&'a NumericArray> for NumericArray where T: $op_trait, { @@ -190,7 +199,7 @@ macro_rules! impl_assign_ops { } } - impl> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, { @@ -207,7 +216,7 @@ macro_rules! impl_assign_ops { macro_rules! impl_wrapping_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl> num_traits::$op_trait for NumericArray + impl num_traits::$op_trait for NumericArray where T: num_traits::$op_trait, { @@ -222,21 +231,21 @@ macro_rules! impl_wrapping_ops { macro_rules! impl_checked_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl> $op_trait for NumericArray + impl $op_trait for NumericArray where T: $op_trait, { fn $op(&self, rhs: &Self) -> Option { unsafe { - let mut builder = ArrayBuilder::new(); + let mut array = GenericArray::uninit(); + let mut builder = IntrusiveArrayBuilder::new(&mut array); { let (array_iter, position) = builder.iter_position(); for (dst, (lhs, rhs)) in array_iter.zip(self.iter().zip(rhs.iter())) { if let Some(value) = $op_trait::$op(lhs, rhs) { - ptr::write(dst, value); - + dst.write(value); *position += 1; } else { return None; @@ -244,7 +253,10 @@ macro_rules! impl_checked_ops { } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } @@ -254,7 +266,7 @@ macro_rules! impl_checked_ops { macro_rules! impl_float_const { ($($f:ident),*) => { - impl> FloatConst for NumericArray + impl FloatConst for NumericArray where T: FloatConst, { @@ -313,22 +325,22 @@ impl_checked_ops! { CheckedDiv::checked_div } -impl> CheckedShl for NumericArray +impl CheckedShl for NumericArray where T: CheckedShl, Self: Shl, { fn checked_shl(&self, rhs: u32) -> Option { unsafe { - let mut builder = ArrayBuilder::new(); + let mut array = GenericArray::uninit(); + let mut builder = IntrusiveArrayBuilder::new(&mut array); { let (builder_iter, builder_position) = builder.iter_position(); for (dst, lhs) in builder_iter.zip(self.iter()) { if let Some(value) = CheckedShl::checked_shl(lhs, rhs) { - ptr::write(dst, value); - + dst.write(value); *builder_position += 1; } else { return None; @@ -336,27 +348,30 @@ where } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } -impl> CheckedShr for NumericArray +impl CheckedShr for NumericArray where T: CheckedShr, Self: Shr, { fn checked_shr(&self, rhs: u32) -> Option { unsafe { - let mut builder = ArrayBuilder::new(); + let mut array = GenericArray::uninit(); + let mut builder = IntrusiveArrayBuilder::new(&mut array); { let (builder_iter, builder_position) = builder.iter_position(); for (dst, lhs) in builder_iter.zip(self.iter()) { if let Some(value) = CheckedShr::checked_shr(lhs, rhs) { - ptr::write(dst, value); - + dst.write(value); *builder_position += 1; } else { return None; @@ -364,7 +379,10 @@ where } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } @@ -388,7 +406,7 @@ impl_float_const!( SQRT_2 ); -impl> Zero for NumericArray +impl Zero for NumericArray where T: Zero, { @@ -401,7 +419,7 @@ where } } -impl> One for NumericArray +impl One for NumericArray where T: One, { @@ -410,7 +428,7 @@ where } } -impl> Saturating for NumericArray +impl Saturating for NumericArray where T: Saturating, { @@ -423,7 +441,7 @@ where } } -impl> Num for NumericArray +impl Num for NumericArray where T: Num, { @@ -434,7 +452,7 @@ where } } -impl> Signed for NumericArray +impl Signed for NumericArray where T: Signed, { @@ -459,9 +477,9 @@ where } } -impl> Unsigned for NumericArray where T: Unsigned {} +impl Unsigned for NumericArray where T: Unsigned {} -impl> Bounded for NumericArray +impl Bounded for NumericArray where T: Bounded, { @@ -476,7 +494,7 @@ where macro_rules! impl_to_primitive { ($($to:ident => $prim:ty),*) => { - impl> ToPrimitive for NumericArray + impl ToPrimitive for NumericArray where T: ToPrimitive, { @@ -511,7 +529,7 @@ impl_to_primitive! { to_f64 => f64 } -impl> NumCast for NumericArray +impl NumCast for NumericArray where T: NumCast + Clone, { @@ -520,334 +538,430 @@ where } } -impl> Float for NumericArray -where - T: Float + Copy, - Self: Copy, -{ - #[inline] - fn nan() -> Self { - Self::splat(Float::nan()) - } - - #[inline] - fn infinity() -> Self { - Self::splat(Float::infinity()) - } +macro_rules! impl_float { + ($float:ident { $($extra:tt)* }) => { + impl $float for NumericArray + where + T: $float, + Self: Copy, + { + $($extra)* - #[inline] - fn neg_infinity() -> Self { - Self::splat(Float::neg_infinity()) - } + #[inline] + fn nan() -> Self { + Self::splat($float::nan()) + } - #[inline] - fn neg_zero() -> Self { - Self::splat(Float::neg_zero()) - } + #[inline] + fn infinity() -> Self { + Self::splat($float::infinity()) + } - #[inline] - fn min_value() -> Self { - Self::splat(Float::min_value()) - } + #[inline] + fn neg_infinity() -> Self { + Self::splat($float::neg_infinity()) + } - #[inline] - fn min_positive_value() -> Self { - Self::splat(Float::min_positive_value()) - } + #[inline] + fn neg_zero() -> Self { + Self::splat($float::neg_zero()) + } - #[inline] - fn max_value() -> Self { - Self::splat(Float::max_value()) - } + #[inline] + fn min_value() -> Self { + Self::splat($float::min_value()) + } - fn is_nan(self) -> bool { - self.iter().any(|x| Float::is_nan(*x)) - } + #[inline] + fn min_positive_value() -> Self { + Self::splat($float::min_positive_value()) + } - fn is_infinite(self) -> bool { - self.iter().any(|x| Float::is_infinite(*x)) - } + #[inline] + fn max_value() -> Self { + Self::splat($float::max_value()) + } - fn is_finite(self) -> bool { - self.iter().all(|x| Float::is_finite(*x)) - } + #[inline] + fn is_nan(self) -> bool { + self.iter().any(|x| $float::is_nan(*x)) + } - fn is_normal(self) -> bool { - self.iter().all(|x| Float::is_normal(*x)) - } + #[inline] + fn is_infinite(self) -> bool { + self.iter().any(|x| $float::is_infinite(*x)) + } - fn classify(self) -> FpCategory { - let mut ret = FpCategory::Zero; + #[inline] + fn is_finite(self) -> bool { + self.iter().all(|x| $float::is_finite(*x)) + } - for x in self.iter() { - match Float::classify(*x) { - // If NaN is found, return NaN immediately - FpCategory::Nan => return FpCategory::Nan, - // If infinite, set infinite - FpCategory::Infinite => ret = FpCategory::Infinite, - // If Subnormal and not infinite, set subnormal - FpCategory::Subnormal if ret != FpCategory::Infinite => { - ret = FpCategory::Subnormal; - } - // If normal and zero, upgrade to normal - FpCategory::Normal if ret == FpCategory::Zero => { - ret = FpCategory::Normal; - } - _ => {} + #[inline] + fn is_normal(self) -> bool { + self.iter().all(|x| $float::is_normal(*x)) } - } - ret - } + #[inline] + fn epsilon() -> Self { + Self::splat($float::epsilon()) + } - fn floor(self) -> Self { - self.0.map(Float::floor).into() - } + #[inline] + fn to_degrees(self) -> Self { + self.0.map($float::to_degrees).into() + } - fn ceil(self) -> Self { - self.0.map(Float::ceil).into() - } + #[inline] + fn to_radians(self) -> Self { + self.0.map($float::to_radians).into() + } - fn round(self) -> Self { - self.0.map(Float::round).into() - } + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + if N::to_usize() == 0 { + (0, 0, 0) + } else { + self.first().unwrap().integer_decode() + } + } - fn trunc(self) -> Self { - self.0.map(Float::trunc).into() - } + fn classify(self) -> FpCategory { + let mut ret = FpCategory::Zero; + + for x in self.iter() { + match $float::classify(*x) { + // If NaN is found, return NaN immediately + FpCategory::Nan => return FpCategory::Nan, + // If infinite, set infinite + FpCategory::Infinite => ret = FpCategory::Infinite, + // If Subnormal and not infinite, set subnormal + FpCategory::Subnormal if ret != FpCategory::Infinite => { + ret = FpCategory::Subnormal; + } + // If normal and zero, upgrade to normal + FpCategory::Normal if ret == FpCategory::Zero => { + ret = FpCategory::Normal; + } + _ => {} + } + } - fn fract(self) -> Self { - self.0.map(Float::fract).into() - } + ret + } - fn abs(self) -> Self { - self.0.map(Float::abs).into() - } + #[inline] + fn floor(self) -> Self { + self.0.map($float::floor).into() + } - fn signum(self) -> Self { - self.0.map(Float::signum).into() - } + #[inline] + fn ceil(self) -> Self { + self.0.map($float::ceil).into() + } - fn is_sign_positive(self) -> bool { - self.iter().all(|x| Float::is_sign_positive(*x)) - } + #[inline] + fn round(self) -> Self { + self.0.map($float::round).into() + } - fn is_sign_negative(self) -> bool { - self.iter().any(|x| Float::is_sign_negative(*x)) - } + #[inline] + fn trunc(self) -> Self { + self.0.map($float::trunc).into() + } - fn mul_add(self, a: Self, b: Self) -> Self { - unsafe { - let mut left = ArrayConsumer::new(self.0); - let mut a_arr = ArrayConsumer::new(a.0); - let mut b_arr = ArrayConsumer::new(b.0); + #[inline] + fn fract(self) -> Self { + self.0.map($float::fract).into() + } - let (left_iter, left_position) = left.iter_position(); - let (a_arr_iter, a_arr_position) = a_arr.iter_position(); - let (b_arr_iter, b_arr_position) = b_arr.iter_position(); + #[inline] + fn abs(self) -> Self { + self.0.map($float::abs).into() + } - let mut destination = ArrayBuilder::new(); + #[inline] + fn signum(self) -> Self { + self.0.map($float::signum).into() + } - { - let (destination_iter, destination_position) = destination.iter_position(); + #[inline] + fn is_sign_positive(self) -> bool { + self.iter().all(|x| $float::is_sign_positive(*x)) + } - destination_iter - .zip(left_iter.zip(a_arr_iter.zip(b_arr_iter))) - .for_each(|(dst, (l, (a, b)))| { - let l = ptr::read(l); - let a = ptr::read(a); - let b = ptr::read(b); + #[inline] + fn is_sign_negative(self) -> bool { + self.iter().any(|x| $float::is_sign_negative(*x)) + } - *left_position += 1; - *a_arr_position += 1; - *b_arr_position += 1; + #[inline] + fn max(self, other: Self) -> Self { + self.0.zip(other.0, $float::max).into() + } - ptr::write(dst, Float::mul_add(l, a, b)); + #[inline] + fn min(self, other: Self) -> Self { + self.0.zip(other.0, $float::min).into() + } - *destination_position += 1; - }); + #[inline] + fn recip(self) -> Self { + self.0.map($float::recip).into() } - NumericArray::new(destination.into_inner()) + #[inline] + fn powi(self, n: i32) -> Self { + self.0.map(|x| $float::powi(x, n)).into() + + // This was a prototype with the best performance that + // still fell short of whatever the compiler does, sadly. + // + // let mut e = n as i64; + // let mut x = self; + // let mut res = Self::one(); + // if e < 0 { + // x = x.recip(); + // e = -e; + // } + // while e != 0 { + // if e & 1 != 0 { + // res *= x; + // } + // e >>= 1; + // x *= x; + // } + // res + } } - } + }; +} - fn recip(self) -> Self { - self.0.map(Float::recip).into() - } +impl_float!(FloatCore {}); - fn powi(self, n: i32) -> Self { - self.0.map(|x| Float::powi(x, n)).into() +#[cfg(feature = "std")] +impl_float!(Float { + #[inline] + fn mul_add(self, a: Self, b: Self) -> Self { + if mem::needs_drop::() { + unsafe { + let mut left = ArrayConsumer::new(self.0); + let mut a_arr = ArrayConsumer::new(a.0); + let mut b_arr = ArrayConsumer::new(b.0); + + let (left_iter, left_position) = left.iter_position(); + let (a_arr_iter, a_arr_position) = a_arr.iter_position(); + let (b_arr_iter, b_arr_position) = b_arr.iter_position(); + + NumericArray::from_iter(left_iter.zip(a_arr_iter.zip(b_arr_iter)).map(|(l, (a, b))| { + let l = ptr::read(l); + let a = ptr::read(a); + let b = ptr::read(b); + + *left_position += 1; + *a_arr_position = *left_position; + *b_arr_position = *left_position; + + Float::mul_add(l, a, b) + })) + } + } else { + let left = ManuallyDrop::new(self); + let a = ManuallyDrop::new(a); + let b = ManuallyDrop::new(b); + + NumericArray::from_iter(left.iter().zip(a.iter()).zip(b.iter()).map(|((l, a), b)| unsafe { + Float::mul_add(ptr::read(l), ptr::read(a), ptr::read(b)) // + })) + } } + #[inline] fn powf(self, n: Self) -> Self { self.0.zip(n.0, Float::powf).into() } + #[inline] fn sqrt(self) -> Self { self.0.map(Float::sqrt).into() } + #[inline] fn exp(self) -> Self { self.0.map(Float::exp).into() } + #[inline] fn exp2(self) -> Self { self.0.map(Float::exp2).into() } + #[inline] fn ln(self) -> Self { self.0.map(Float::ln).into() } + #[inline] fn log(self, base: Self) -> Self { self.0.zip(base.0, Float::log).into() } + #[inline] fn log2(self) -> Self { self.0.map(Float::log2).into() } + #[inline] fn log10(self) -> Self { self.0.map(Float::log10).into() } - fn max(self, other: Self) -> Self { - self.0.zip(other.0, Float::max).into() - } - - fn min(self, other: Self) -> Self { - self.0.zip(other.0, Float::min).into() - } - + #[inline] fn abs_sub(self, other: Self) -> Self { self.0.zip(other.0, Float::abs_sub).into() } + #[inline] fn cbrt(self) -> Self { self.0.map(Float::cbrt).into() } + #[inline] fn hypot(self, other: Self) -> Self { self.0.zip(other.0, Float::hypot).into() } + #[inline] fn sin(self) -> Self { self.0.map(Float::sin).into() } + #[inline] fn cos(self) -> Self { self.0.map(Float::cos).into() } + #[inline] fn tan(self) -> Self { self.0.map(Float::tan).into() } + #[inline] fn asin(self) -> Self { self.0.map(Float::asin).into() } + #[inline] fn acos(self) -> Self { self.0.map(Float::acos).into() } + #[inline] fn atan(self) -> Self { self.0.map(Float::atan).into() } + #[inline] fn atan2(self, other: Self) -> Self { self.0.zip(other.0, Float::atan2).into() } + #[inline] fn sin_cos(self) -> (Self, Self) { - unsafe { - let mut source = ArrayConsumer::new(self.0); + let mut sin_array = GenericArray::uninit(); + let mut cos_array = GenericArray::uninit(); - let (source_iter, source_position) = source.iter_position(); + let mut sin_destination = IntrusiveArrayBuilder::new(&mut sin_array); + let mut cos_destination = IntrusiveArrayBuilder::new(&mut cos_array); - let mut sin_destination = ArrayBuilder::new(); - let mut cos_destination = ArrayBuilder::new(); + if mem::needs_drop::() { + unsafe { + let mut source = ArrayConsumer::new(self.0); - { - let (sin_destination_iter, sin_destination_position) = sin_destination.iter_position(); - let (cos_destination_iter, cos_destination_position) = cos_destination.iter_position(); + let (source_iter, source_position) = source.iter_position(); - sin_destination_iter - .zip(cos_destination_iter) - .zip(source_iter) - .for_each(|((sin, cos), src)| { - let x = ptr::read(src); + { + let (sin_destination_iter, sin_destination_position) = sin_destination.iter_position(); + let (cos_destination_iter, cos_destination_position) = cos_destination.iter_position(); - *source_position += 1; + sin_destination_iter + .zip(cos_destination_iter) + .zip(source_iter) + .for_each(|((sin, cos), src)| { + let x = ptr::read(src); - let (s, c) = Float::sin_cos(x); + *source_position += 1; - ptr::write(sin, s); - ptr::write(cos, c); + let (s, c) = Float::sin_cos(x); - *sin_destination_position += 1; - *cos_destination_position += 1; - }); + sin.write(s); + cos.write(c); + + *sin_destination_position = *source_position; + *cos_destination_position = *source_position; + }); + } } + } else { + unsafe { + let (sin_destination_iter, _) = sin_destination.iter_position(); + let (cos_destination_iter, _) = cos_destination.iter_position(); + + sin_destination_iter + .zip(cos_destination_iter) + .zip(self.iter()) + .for_each(|((sin, cos), src)| { + let (s, c) = Float::sin_cos(ptr::read(src)); - ( - NumericArray::new(sin_destination.into_inner()), - NumericArray::new(cos_destination.into_inner()), - ) + sin.write(s); + cos.write(c); + }); + } } + + ( + NumericArray::new(unsafe { sin_destination.finish(); IntrusiveArrayBuilder::array_assume_init(sin_array) }), + NumericArray::new(unsafe { cos_destination.finish(); IntrusiveArrayBuilder::array_assume_init(cos_array) }), + ) } + #[inline] fn exp_m1(self) -> Self { self.0.map(Float::exp_m1).into() } + #[inline] fn ln_1p(self) -> Self { self.0.map(Float::ln_1p).into() } + #[inline] fn sinh(self) -> Self { self.0.map(Float::sinh).into() } + #[inline] fn cosh(self) -> Self { self.0.map(Float::cosh).into() } + #[inline] fn tanh(self) -> Self { self.0.map(Float::tanh).into() } + #[inline] fn asinh(self) -> Self { self.0.map(Float::asinh).into() } + #[inline] fn acosh(self) -> Self { self.0.map(Float::acosh).into() } + #[inline] fn atanh(self) -> Self { self.0.map(Float::atanh).into() } - - fn integer_decode(self) -> (u64, i16, i8) { - if N::to_usize() == 0 { - (0, 0, 0) - } else { - self.first().unwrap().integer_decode() - } - } - - #[inline] - fn epsilon() -> Self { - Self::splat(Float::epsilon()) - } - - fn to_degrees(self) -> Self { - self.0.map(Float::to_degrees).into() - } - - fn to_radians(self) -> Self { - self.0.map(Float::to_radians).into() - } -} +}); diff --git a/src/lib.rs b/src/lib.rs index a3febe9..960b2d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,14 @@ +//! # `numeric-array` +//! +//! [![crates.io](https://img.shields.io/crates/v/numeric-array.svg)](https://crates.io/crates/numeric-array) +//! [![Documentation](https://docs.rs/numeric-array/badge.svg)](https://docs.rs/numeric-array) +//! [![MIT/Apache-2 licensed](https://img.shields.io/crates/l/numeric-array.svg)](./LICENSE-Apache) +//! //! `numeric-array` is a wrapper around -//! [`generic-array`](https://github.com/fizyk20/generic-array) that adds -//! efficient numeric trait implementations, often times making use of -//! SIMD instructions and compile-time evaluations. +//! [`generic-array`](https://github.com/fizyk20/generic-array) +//! that adds efficient numeric trait implementations, designed +//! to encourage LLVM to autovectorize expressions into SIMD +//! instructions and perform compile-time evaluation. //! //! All stable `core::ops` traits are implemented for `NumericArray` itself, //! plus the thin `NumericConstant` type, which is required to @@ -13,36 +20,31 @@ //! Example: //! //! ```rust -//! extern crate num_traits; -//! #[macro_use] -//! extern crate generic_array; -//! #[macro_use] -//! extern crate numeric_array; -//! //! use num_traits::Float; -//! use numeric_array::NumericArray; +//! use numeric_array::{NumericArray, narr}; //! +//! # #[cfg(feature = "std")] //! fn main() { -//! let a = narr![f32; 1, 2, 3, 4]; -//! let b = narr![f32; 5, 6, 7, 8]; -//! let c = narr![f32; 9, 1, 2, 3]; +//! let a = narr![1.0, 2.0, 3.0, 4.0]; +//! let b = narr![5.0, 6.0, 7.0, 8.0]; +//! let c = narr![9.0, 1.0, 2.0, 3.0]; //! //! // Compiles to a single vfmadd213ps instruction on my machine //! let d = a.mul_add(b, c); //! -//! assert_eq!(d, narr![f32; 14, 13, 23, 35]); +//! assert_eq!(d, narr![14.0, 13.0, 23.0, 35.0]); //! } +//! +//! # #[cfg(not(feature = "std"))] fn main() {} //! ``` //! //! When used with `RUSTFLAGS = "-C opt-level=3 -C target-cpu=native"`, -//! then Rust and LLVM are smart enough to turn almost all operations +//! then Rust and LLVM are smart enough to autovectorize almost all operations //! into SIMD instructions, or even just evaluate them at compile time. -//! The above example is actually evaluated at compile time, -//! so if you were to view the assembly it would show the result only. -//! Rust is pretty smart. +//! The above example is actually evaluated at compile time, so if you +//! were to view the assembly it would show the result only. //! -//! Therefore, this is ideal for situations where simple component-wise -//! operations are required for arrays. +//! This is ideal for situations where simple component-wise operations are required for arrays. //! #![deny(missing_docs)] @@ -50,8 +52,7 @@ extern crate num_traits; -#[cfg_attr(test, macro_use)] -extern crate generic_array; +pub extern crate generic_array; pub use generic_array::{typenum, ArrayLength}; @@ -88,7 +89,7 @@ pub mod simd; /// For example, adding together four-element `NumericArray`'s will result /// in a single SIMD instruction for all elements at once. #[repr(transparent)] -pub struct NumericArray>(GenericArray); +pub struct NumericArray(GenericArray); /// Sugar for `NumericArray::new(arr![...])` /// @@ -101,14 +102,15 @@ pub struct NumericArray>(GenericArray); #[macro_export] macro_rules! narr { ($($t:tt)*) => { - $crate::NumericArray::new(arr!($($t)*)) + $crate::NumericArray::new($crate::generic_array::arr!($($t)*)) } } -unsafe impl> GenericSequence for NumericArray { +unsafe impl GenericSequence for NumericArray { type Length = N; type Sequence = Self; + #[inline(always)] fn generate(f: F) -> Self where F: FnMut(usize) -> T, @@ -149,13 +151,13 @@ impl DerefMut for NumericConstant { } } -impl> Debug for NumericArray { +impl Debug for NumericArray { fn fmt(&self, f: &mut Formatter) -> FmtResult { f.debug_tuple("NumericArray").field(&self.0).finish() } } -impl> From for NumericArray +impl From for NumericArray where X: Into>, { @@ -164,15 +166,15 @@ where } } -impl> Clone for NumericArray { +impl Clone for NumericArray { fn clone(&self) -> NumericArray { NumericArray(self.0.clone()) } } -impl> Copy for NumericArray where N::ArrayType: Copy {} +impl Copy for NumericArray where N::ArrayType: Copy {} -impl> Deref for NumericArray { +impl Deref for NumericArray { type Target = [T]; fn deref(&self) -> &Self::Target { @@ -180,13 +182,13 @@ impl> Deref for NumericArray { } } -impl> DerefMut for NumericArray { +impl DerefMut for NumericArray { fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() } } -impl + ArrayLength> PartialEq> for NumericArray +impl PartialEq> for NumericArray where T: PartialEq, { @@ -195,7 +197,7 @@ where } } -impl + ArrayLength> PartialEq> for NumericArray +impl PartialEq> for NumericArray where T: PartialEq, { @@ -204,9 +206,9 @@ where } } -impl> cmp::Eq for NumericArray where T: cmp::Eq {} +impl cmp::Eq for NumericArray where T: cmp::Eq {} -impl> PartialOrd for NumericArray +impl PartialOrd for NumericArray where T: PartialOrd, { @@ -236,7 +238,7 @@ where } } -impl> PartialOrd> for NumericArray +impl PartialOrd> for NumericArray where T: PartialOrd, { @@ -266,7 +268,7 @@ where } } -impl> cmp::Ord for NumericArray +impl cmp::Ord for NumericArray where T: cmp::Ord, { @@ -276,7 +278,7 @@ where } } -impl> NumericArray { +impl NumericArray { /// Creates a new `NumericArray` instance from a `GenericArray` instance. /// /// Example: @@ -289,7 +291,7 @@ impl> NumericArray { /// use numeric_array::NumericArray; /// /// fn main() { - /// let arr = NumericArray::new(arr![i32; 1, 2, 3, 4]); + /// let arr = NumericArray::new(arr![1, 2, 3, 4]); /// /// println!("{:?}", arr); // Prints 'NumericArray([1, 2, 3, 4])' /// } @@ -304,7 +306,7 @@ impl> NumericArray { /// Example: /// /// ```ignore - /// let a = NumericArray::new(arr![i32; 5, 5, 5, 5]); + /// let a = NumericArray::new(arr![5, 5, 5, 5]); /// let b = NumericArray::splat(5); /// /// assert_eq!(a, b); @@ -318,10 +320,7 @@ impl> NumericArray { } /// Convert all elements of the `NumericArray` to another `NumericArray` using `From` - pub fn convert>(self) -> NumericArray - where - N: ArrayLength, - { + pub fn convert>(self) -> NumericArray { self.0.map(From::from).into() } @@ -338,19 +337,19 @@ impl> NumericArray { } /// Get mutable reference to underlying `GenericArray` instance. - #[inline] + #[inline(always)] pub fn as_mut_array(&mut self) -> &mut GenericArray { &mut self.0 } /// Extracts a slice containing the entire array. - #[inline] + #[inline(always)] pub fn as_slice(&self) -> &[T] { &self.0 } /// Extracts a mutable slice containing the entire array. - #[inline] + #[inline(always)] pub fn as_mut_slice(&mut self) -> &mut [T] { &mut self.0 } @@ -358,7 +357,7 @@ impl> NumericArray { /// Converts slice to a numeric array reference with inferred length; /// /// Length of the slice must be equal to the length of the array. - #[inline] + #[inline(always)] pub fn from_slice(slice: &[T]) -> &NumericArray { slice.into() } @@ -366,7 +365,7 @@ impl> NumericArray { /// Converts mutable slice to a mutable numeric array reference /// /// Length of the slice must be equal to the length of the array. - #[inline] + #[inline(always)] pub fn from_mut_slice(slice: &mut [T]) -> &mut NumericArray { slice.into() } @@ -375,10 +374,10 @@ impl> NumericArray { use core::ops::Sub; use typenum::{bit::B1 as True, Diff, IsGreaterOrEqual}; -impl> NumericArray { +impl NumericArray { /// Offset the numeric array and cast it into a shorter array #[inline(always)] - pub fn offset, O: ArrayLength>(&self) -> &NumericArray + pub fn offset(&self) -> &NumericArray where N: Sub, Diff: IsGreaterOrEqual, @@ -388,7 +387,7 @@ impl> NumericArray { /// Offset the numeric array and cast it into a shorter array #[inline(always)] - pub fn offset_mut, O: ArrayLength>(&mut self) -> &mut NumericArray + pub fn offset_mut(&mut self) -> &mut NumericArray where N: Sub, Diff: IsGreaterOrEqual, @@ -397,11 +396,11 @@ impl> NumericArray { } } -impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a NumericArray { +impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a NumericArray { /// Converts slice to a numeric array reference with inferred length; /// /// Length of the slice must be equal to the length of the array. - #[inline] + #[inline(always)] fn from(slice: &[T]) -> &NumericArray { debug_assert_eq!(slice.len(), N::to_usize()); @@ -409,11 +408,11 @@ impl<'a, T, N: ArrayLength> From<&'a [T]> for &'a NumericArray { } } -impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut NumericArray { +impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut NumericArray { /// Converts mutable slice to a mutable numeric array reference /// /// Length of the slice must be equal to the length of the array. - #[inline] + #[inline(always)] fn from(slice: &mut [T]) -> &mut NumericArray { debug_assert_eq!(slice.len(), N::to_usize()); @@ -421,31 +420,34 @@ impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut NumericArray } } -impl> AsRef<[T]> for NumericArray { +impl AsRef<[T]> for NumericArray { + #[inline(always)] fn as_ref(&self) -> &[T] { self } } -impl> Borrow<[T]> for NumericArray { +impl Borrow<[T]> for NumericArray { + #[inline(always)] fn borrow(&self) -> &[T] { self } } -impl> AsMut<[T]> for NumericArray { +impl AsMut<[T]> for NumericArray { + #[inline(always)] fn as_mut(&mut self) -> &mut [T] { self } } -impl> BorrowMut<[T]> for NumericArray { +impl BorrowMut<[T]> for NumericArray { fn borrow_mut(&mut self) -> &mut [T] { self } } -impl> Index for NumericArray { +impl Index for NumericArray { type Output = T; #[inline(always)] @@ -454,14 +456,14 @@ impl> Index for NumericArray { } } -impl> IndexMut for NumericArray { +impl IndexMut for NumericArray { #[inline(always)] fn index_mut(&mut self, index: usize) -> &mut T { self.0.index_mut(index) } } -impl> Index> for NumericArray { +impl Index> for NumericArray { type Output = [T]; #[inline(always)] @@ -470,14 +472,14 @@ impl> Index> for NumericArray { } } -impl> IndexMut> for NumericArray { +impl IndexMut> for NumericArray { #[inline(always)] fn index_mut(&mut self, index: Range) -> &mut [T] { self.0.index_mut(index) } } -impl> Index> for NumericArray { +impl Index> for NumericArray { type Output = [T]; #[inline(always)] @@ -486,14 +488,14 @@ impl> Index> for NumericArray { } } -impl> IndexMut> for NumericArray { +impl IndexMut> for NumericArray { #[inline(always)] fn index_mut(&mut self, index: RangeTo) -> &mut [T] { self.0.index_mut(index) } } -impl> Index> for NumericArray { +impl Index> for NumericArray { type Output = [T]; #[inline(always)] @@ -502,14 +504,14 @@ impl> Index> for NumericArray { } } -impl> IndexMut> for NumericArray { +impl IndexMut> for NumericArray { #[inline(always)] fn index_mut(&mut self, index: RangeFrom) -> &mut [T] { self.0.index_mut(index) } } -impl> Index for NumericArray { +impl Index for NumericArray { type Output = [T]; #[inline(always)] @@ -518,43 +520,45 @@ impl> Index for NumericArray { } } -impl> IndexMut for NumericArray { +impl IndexMut for NumericArray { #[inline(always)] fn index_mut(&mut self, _index: RangeFull) -> &mut [T] { self } } -impl<'a, T, N: ArrayLength> IntoIterator for &'a NumericArray { +impl<'a, T, N: ArrayLength> IntoIterator for &'a NumericArray { type Item = &'a T; type IntoIter = slice::Iter<'a, T>; - #[inline] + #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.iter() } } -impl<'a, T, N: ArrayLength> IntoIterator for &'a mut NumericArray { +impl<'a, T, N: ArrayLength> IntoIterator for &'a mut NumericArray { type Item = &'a mut T; type IntoIter = slice::IterMut<'a, T>; - #[inline] + #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } -impl> IntoIterator for NumericArray { +impl IntoIterator for NumericArray { type Item = T; type IntoIter = GenericArrayIter; + #[inline(always)] fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } -impl> FromIterator for NumericArray { +impl FromIterator for NumericArray { + #[inline(always)] fn from_iter(iter: I) -> Self where I: IntoIterator, @@ -563,10 +567,11 @@ impl> FromIterator for NumericArray { } } -impl> Default for NumericArray +impl Default for NumericArray where T: Default, { + #[inline(always)] fn default() -> Self { NumericArray(GenericArray::default()) } @@ -574,6 +579,8 @@ where #[cfg(test)] pub mod tests { + use num_traits::float::FloatCore; + // This stops the compiler from optimizing based on known data, only data types. #[inline(never)] pub fn black_box(val: T) -> T { @@ -586,30 +593,30 @@ pub mod tests { #[test] fn test_ops() { - let a = black_box(narr![i32; 1, 3, 5, 7]); - let b = black_box(narr![i32; 2, 4, 6, 8]); + let a = black_box(narr![1, 3, 5, 7]); + let b = black_box(narr![2, 4, 6, 8]); let c = a + b; let d = c * nconstant!(black_box(5)); let e = d << nconstant!(1_usize); - assert_eq!(e, narr![i32; 30, 70, 110, 150]) + assert_eq!(e, narr![30, 70, 110, 150]) } #[test] fn test_constants() { - let a = black_box(narr![i32; 1, 3, 5, 7]); - let b = black_box(narr![i32; 2, 4, 6, 8]); + let a = black_box(narr![1, 3, 5, 7]); + let b = black_box(narr![2, 4, 6, 8]); let c = a + b * nconstant!(2); - assert_eq!(c, narr![i32; 5, 11, 17, 23]); + assert_eq!(c, narr![5, 11, 17, 23]); } #[test] fn test_floats() { - let a = black_box(narr![f32; 1.0, 3.0, 5.0, 7.0]); - let b = black_box(narr![f32; 2.0, 4.0, 6.0, 8.0]); + let a = black_box(narr![1.0f32, 3.0, 5.0, 7.0]); + let b = black_box(narr![2.0f32, 4.0, 6.0, 8.0]); let c = a + b; @@ -620,41 +627,41 @@ pub mod tests { fn test_other() { use num_traits::Saturating; - let a = black_box(narr![i32; 1, 3, 5, 7]); - let b = black_box(narr![i32; 2, 4, 6, 8]); + let a = black_box(narr![1, 3, 5, 7]); + let b = black_box(narr![2, 4, 6, 8]); let c = a.saturating_add(b); black_box(c); } + #[cfg(feature = "std")] #[test] fn test_atan2() { use num_traits::Float; - let a = black_box(narr![f32; 1, 2, 3, 4]); - let b = black_box(narr![f32; 2, 3, 4, 5]); + let a = black_box(narr![1.0f32, 2.0, 3.0, 4.0]); + let b = black_box(narr![2.0f32, 3.0, 4.0, 5.0]); let c = a.atan2(b); - assert_eq!(c, narr![f32; 0.4636476, 0.5880026, 0.6435011, 0.67474097]); + assert_eq!(c, narr![0.4636476, 0.5880026, 0.6435011, 0.67474097]); } #[test] fn test_classify() { use core::num::FpCategory; - use num_traits::Float; let nan = f32::nan(); let infinity = f32::infinity(); - let any_nan = black_box(narr![f32; 1, 2, nan, 0]); - let any_infinite = black_box(narr![f32; 1, infinity, 2, 3]); - let any_mixed = black_box(narr![f32; 1, infinity, nan, 0]); - let all_normal = black_box(narr![f32; 1, 2, 3, 4]); - let all_zero = black_box(narr![f32; 0, 0, 0, 0]); + let any_nan = black_box(narr![1.0, 2.0, nan, 0.0]); + let any_infinite = black_box(narr![1.0, infinity, 2.0, 3.0]); + let any_mixed = black_box(narr![1.0, infinity, nan, 0.0]); + let all_normal = black_box(narr![1.0, 2.0, 3.0, 4.0]); + let all_zero = black_box(narr![0.0, 0.0, 0.0, 0.0]); - let non_zero = black_box(narr![f32; 0, 1, 0, 0]); + let non_zero = black_box(narr![0.0f32, 1.0, 0.0, 0.0]); assert_eq!(any_nan.classify(), FpCategory::Nan); assert_eq!(any_mixed.classify(), FpCategory::Nan); @@ -664,48 +671,50 @@ pub mod tests { assert_eq!(non_zero.classify(), FpCategory::Normal); - assert_eq!(any_nan.is_infinite(), false); - assert_eq!(any_mixed.is_infinite(), true); - assert_eq!(any_nan.is_nan(), true); - assert_eq!(any_mixed.is_nan(), true); - assert_eq!(any_infinite.is_nan(), false); + assert!(!any_nan.is_infinite()); + assert!(any_mixed.is_infinite()); + assert!(any_nan.is_nan()); + assert!(any_mixed.is_nan()); + assert!(!any_infinite.is_nan()); } + #[cfg(feature = "std")] #[test] fn test_tanh() { use num_traits::Float; - let a = black_box(narr![f32; 1, 2, 3, 4]); + let a = black_box(narr![1.0f32, 2.0, 3.0, 4.0]); black_box(a.tanh()); } + #[cfg(feature = "std")] #[test] pub fn test_madd() { use num_traits::Float; - let a = black_box(narr![f32; 1, 2, 3, 4]); - let b = black_box(narr![f32; 5, 6, 7, 8]); - let c = black_box(narr![f32; 9, 1, 2, 3]); + let a = black_box(narr![1.0f32, 2.0, 3.0, 4.0]); + let b = black_box(narr![5.0f32, 6.0, 7.0, 8.0]); + let c = black_box(narr![9.0f32, 1.0, 2.0, 3.0]); let d = a.mul_add(b, c); - assert_eq!(d, narr![f32; 14, 13, 23, 35]); + assert_eq!(d, narr![14.0, 13.0, 23.0, 35.0]); } #[test] #[no_mangle] pub fn test_select() { - use simd::Select; + use crate::simd::Select; - let mask = black_box(narr![bool; true, false, false, true]); + let mask = black_box(narr![true, false, false, true]); - let a = black_box(narr![i32; 1, 2, 3, 4]); - let b = black_box(narr![i32; 5, 6, 7, 8]); + let a = black_box(narr![1, 2, 3, 4]); + let b = black_box(narr![5, 6, 7, 8]); // Compiles to vblendvps let selected = mask.select(a, b); - assert_eq!(selected, narr![i32; 1, 6, 7, 4]); + assert_eq!(selected, narr![1, 6, 7, 4]); } } diff --git a/src/simd.rs b/src/simd.rs index d0311a6..2b5bd56 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -2,12 +2,14 @@ //! //! These aren't exactly numeric-specific, but they can make use of SIMD instructions. +use core::mem::ManuallyDrop; + use super::*; -use generic_array::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::ArrayConsumer; /// Selects elements from one array or another using `self` as a mask. -pub unsafe trait Select> { +pub unsafe trait Select { /// Selects elements from one array or another using `self` as a mask. /// /// Example: @@ -25,84 +27,67 @@ pub unsafe trait Select> { /// /// assert_eq!(selected, narr![i32; 1, 6, 7, 4]); /// ``` + /// + /// NOTE: The default implementation of this will clamp the index values to the length of the array. fn select(self, true_values: NumericArray, false_values: NumericArray) -> NumericArray; } /// Rearranges one numeric array into another using the supplied indices -pub unsafe trait Permute> { +pub unsafe trait Permute { /// Performs the permutation fn permute(self, values: &NumericArray) -> NumericArray; } -unsafe impl> Permute for NumericArray +unsafe impl Permute for NumericArray where - N: ArrayLength, T: Clone, + I: Copy + Into, { + #[inline] fn permute(self, values: &NumericArray) -> NumericArray { - unsafe { - let mut indices = ArrayConsumer::new(self.0); - - let (index_iter, index_position) = indices.iter_position(); - - let mut destination = ArrayBuilder::new(); - - { - let (destination_iter, destination_position) = destination.iter_position(); - - destination_iter.zip(index_iter).for_each(|(dst, index)| { - let value = values.get_unchecked(*index).clone(); + NumericArray::from_iter(self.iter().map(|index| unsafe { + let index: usize = (*index).into(); - *index_position += 1; - - ptr::write(dst, value); - - *destination_position += 1; - }); - } - - NumericArray::new(destination.into_inner()) - } + values.get_unchecked(index.min(N::to_usize())).clone() + })) } } -unsafe impl> Select for NumericArray -where - N: ArrayLength, -{ +unsafe impl Select for NumericArray { + #[inline] fn select(self, true_values: NumericArray, false_values: NumericArray) -> NumericArray { - unsafe { - let mut mask = ArrayConsumer::new(self.0); - let mut true_values = ArrayConsumer::new(true_values.0); - let mut false_values = ArrayConsumer::new(false_values.0); - - let (mask_iter, mask_position) = mask.iter_position(); - let (true_values_iter, true_values_position) = true_values.iter_position(); - let (false_values_iter, false_values_position) = false_values.iter_position(); - - let mut destination = ArrayBuilder::new(); - - { - let (destination_iter, destination_position) = destination.iter_position(); - - destination_iter - .zip(mask_iter.zip(true_values_iter.zip(false_values_iter))) - .for_each(|(dst, (m, (t, f)))| { - let t = ptr::read(t); - let f = ptr::read(f); - let m = ptr::read(m); - - *mask_position += 1; - *true_values_position += 1; - *false_values_position += 1; - - ptr::write(dst, if m { t } else { f }); - - *destination_position += 1; - }); + if core::mem::needs_drop::() { + unsafe { + let mut true_values = ArrayConsumer::new(true_values.0); + let mut false_values = ArrayConsumer::new(false_values.0); + + let (true_values_iter, true_values_position) = true_values.iter_position(); + let (false_values_iter, false_values_position) = false_values.iter_position(); + + NumericArray::from_iter(self.0.iter().zip(true_values_iter.zip(false_values_iter)).map(|(m, (t, f))| { + let t = ptr::read(t); + let f = ptr::read(f); + + *true_values_position += 1; + *false_values_position = *true_values_position; + + match *m { + true => t, + false => f, + } + })) + } + } else { + let true_values = ManuallyDrop::new(true_values); + let mut values = ManuallyDrop::new(false_values); + + for (mask, (v, t)) in self.iter().zip(values.iter_mut().zip(true_values.iter())) { + if *mask { + unsafe { ptr::copy_nonoverlapping(t, v, 1) }; + } } - NumericArray::new(destination.into_inner()) + ManuallyDrop::into_inner(values) } } }