From 516e6a120cdbb027106996180066559ef0265902 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Sun, 26 Mar 2023 18:04:26 -0500 Subject: [PATCH 01/10] Prepare for generic-array 1.0 --- Cargo.toml | 4 +-- src/geometry.rs | 10 ++---- src/impl_serde.rs | 4 +-- src/impls.rs | 66 ++++++++++++++++--------------------- src/lib.rs | 83 +++++++++++++++++++++++------------------------ src/simd.rs | 12 +++---- 6 files changed, 79 insertions(+), 100 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5c0ffa3..8219482 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT" categories = ["data-structures"] [dependencies] -generic-array = "0.14.4" +generic-array = "1.0" num-traits = "0.2" serde = { version = "1.0", optional = true, default_features = false } @@ -20,4 +20,4 @@ serde = { version = "1.0", optional = true, default_features = false } serde1 = ["serde", "generic-array/serde"] [dev-dependencies] -serde_json = "1.0" \ No newline at end of file +serde_json = "1.0" diff --git a/src/geometry.rs b/src/geometry.rs index d174349..102cdb4 100644 --- a/src/geometry.rs +++ b/src/geometry.rs @@ -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, { #[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..f767191 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -28,10 +28,9 @@ use generic_array::{ArrayBuilder, ArrayConsumer}; 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>; @@ -40,10 +39,9 @@ macro_rules! impl_unary_ops { } } - 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>; @@ -58,10 +56,9 @@ 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>; @@ -70,10 +67,9 @@ macro_rules! impl_binary_ops { } } - 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>; @@ -82,10 +78,9 @@ macro_rules! impl_binary_ops { } } - 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>; @@ -94,10 +89,9 @@ macro_rules! impl_binary_ops { } } - 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>; @@ -106,10 +100,9 @@ macro_rules! impl_binary_ops { } } - impl> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; @@ -118,10 +111,9 @@ macro_rules! impl_binary_ops { } } - 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>; @@ -130,10 +122,9 @@ macro_rules! impl_binary_ops { } } - impl> $op_trait> for NumericConstant + impl $op_trait> for NumericConstant where U: $op_trait, - N: ArrayLength<>::Output>, { type Output = NumericArray<>::Output, N>; @@ -142,10 +133,9 @@ macro_rules! impl_binary_ops { } } - 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>; @@ -160,7 +150,7 @@ 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, { @@ -179,7 +169,7 @@ macro_rules! impl_assign_ops { } } - impl<'a, T, U: Clone, N: ArrayLength + ArrayLength> $op_trait<&'a NumericArray> for NumericArray + impl<'a, T, U: Clone, N: ArrayLength + ArrayLength> $op_trait<&'a NumericArray> for NumericArray where T: $op_trait, { @@ -190,7 +180,7 @@ macro_rules! impl_assign_ops { } } - impl> $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, { @@ -207,7 +197,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,7 +212,7 @@ 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, { @@ -254,7 +244,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,7 +303,7 @@ impl_checked_ops! { CheckedDiv::checked_div } -impl> CheckedShl for NumericArray +impl CheckedShl for NumericArray where T: CheckedShl, Self: Shl, @@ -341,7 +331,7 @@ where } } -impl> CheckedShr for NumericArray +impl CheckedShr for NumericArray where T: CheckedShr, Self: Shr, @@ -388,7 +378,7 @@ impl_float_const!( SQRT_2 ); -impl> Zero for NumericArray +impl Zero for NumericArray where T: Zero, { @@ -401,7 +391,7 @@ where } } -impl> One for NumericArray +impl One for NumericArray where T: One, { @@ -410,7 +400,7 @@ where } } -impl> Saturating for NumericArray +impl Saturating for NumericArray where T: Saturating, { @@ -423,7 +413,7 @@ where } } -impl> Num for NumericArray +impl Num for NumericArray where T: Num, { @@ -434,7 +424,7 @@ where } } -impl> Signed for NumericArray +impl Signed for NumericArray where T: Signed, { @@ -459,9 +449,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 +466,7 @@ where macro_rules! impl_to_primitive { ($($to:ident => $prim:ty),*) => { - impl> ToPrimitive for NumericArray + impl ToPrimitive for NumericArray where T: ToPrimitive, { @@ -511,7 +501,7 @@ impl_to_primitive! { to_f64 => f64 } -impl> NumCast for NumericArray +impl NumCast for NumericArray where T: NumCast + Clone, { @@ -520,7 +510,7 @@ where } } -impl> Float for NumericArray +impl Float for NumericArray where T: Float + Copy, Self: Copy, diff --git a/src/lib.rs b/src/lib.rs index a3febe9..253b722 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,7 +88,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![...])` /// @@ -105,7 +105,7 @@ macro_rules! narr { } } -unsafe impl> GenericSequence for NumericArray { +unsafe impl GenericSequence for NumericArray { type Length = N; type Sequence = Self; @@ -149,13 +149,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 +164,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 +180,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 +195,7 @@ where } } -impl + ArrayLength> PartialEq> for NumericArray +impl PartialEq> for NumericArray where T: PartialEq, { @@ -204,9 +204,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 +236,7 @@ where } } -impl> PartialOrd> for NumericArray +impl PartialOrd> for NumericArray where T: PartialOrd, { @@ -266,7 +266,7 @@ where } } -impl> cmp::Ord for NumericArray +impl cmp::Ord for NumericArray where T: cmp::Ord, { @@ -276,7 +276,7 @@ where } } -impl> NumericArray { +impl NumericArray { /// Creates a new `NumericArray` instance from a `GenericArray` instance. /// /// Example: @@ -318,10 +318,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() } @@ -375,10 +372,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 +385,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,7 +394,7 @@ 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. @@ -409,7 +406,7 @@ 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. @@ -421,31 +418,31 @@ impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut NumericArray } } -impl> AsRef<[T]> for NumericArray { +impl AsRef<[T]> for NumericArray { fn as_ref(&self) -> &[T] { self } } -impl> Borrow<[T]> for NumericArray { +impl Borrow<[T]> for NumericArray { fn borrow(&self) -> &[T] { self } } -impl> AsMut<[T]> for NumericArray { +impl AsMut<[T]> for NumericArray { 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 +451,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 +467,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 +483,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 +499,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,14 +515,14 @@ 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>; @@ -535,7 +532,7 @@ impl<'a, T, N: ArrayLength> IntoIterator for &'a NumericArray { } } -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>; @@ -545,7 +542,7 @@ impl<'a, T, N: ArrayLength> IntoIterator for &'a mut NumericArray { } } -impl> IntoIterator for NumericArray { +impl IntoIterator for NumericArray { type Item = T; type IntoIter = GenericArrayIter; @@ -554,7 +551,7 @@ impl> IntoIterator for NumericArray { } } -impl> FromIterator for NumericArray { +impl FromIterator for NumericArray { fn from_iter(iter: I) -> Self where I: IntoIterator, @@ -563,7 +560,7 @@ impl> FromIterator for NumericArray { } } -impl> Default for NumericArray +impl Default for NumericArray where T: Default, { diff --git a/src/simd.rs b/src/simd.rs index d0311a6..e97c6c2 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -7,7 +7,7 @@ use super::*; use generic_array::{ArrayBuilder, 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: @@ -29,14 +29,13 @@ pub unsafe trait Select> { } /// 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, { fn permute(self, values: &NumericArray) -> NumericArray { @@ -66,10 +65,7 @@ where } } -unsafe impl> Select for NumericArray -where - N: ArrayLength, -{ +unsafe impl Select for NumericArray { fn select(self, true_values: NumericArray, false_values: NumericArray) -> NumericArray { unsafe { let mut mask = ArrayConsumer::new(self.0); From 8f5dfcf81ccaf817c6fac2917ad1f3569d6957f4 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Sun, 26 Mar 2023 18:05:55 -0500 Subject: [PATCH 02/10] Cleanup --- src/impls.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/impls.rs b/src/impls.rs index f767191..cd8d2b9 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -150,7 +150,7 @@ macro_rules! impl_binary_ops { macro_rules! impl_assign_ops { ($($op_trait:ident::$op:ident),*) => { $( - impl $op_trait> for NumericArray + impl $op_trait> for NumericArray where T: $op_trait, { @@ -169,7 +169,7 @@ macro_rules! impl_assign_ops { } } - 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, { From e0ff9393c61085eaa76e6f0daa99177f94e2051e Mon Sep 17 00:00:00 2001 From: novacrazy Date: Fri, 31 Mar 2023 02:37:25 -0500 Subject: [PATCH 03/10] Update generic-array --- Cargo.toml | 2 +- src/impls.rs | 17 +++++++---------- src/simd.rs | 8 +++----- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8219482..5efceed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ license = "MIT" categories = ["data-structures"] [dependencies] -generic-array = "1.0" +generic-array = { git = "https://github.com/fizyk20/generic-array", branch = "1.0", features = ["internals"] } num-traits = "0.2" serde = { version = "1.0", optional = true, default_features = false } diff --git a/src/impls.rs b/src/impls.rs index cd8d2b9..2597b65 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -23,7 +23,7 @@ use core::ops::*; use num_traits::*; -use generic_array::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::{ArrayBuilder, ArrayConsumer}; macro_rules! impl_unary_ops { ($($op_trait:ident::$op:ident),*) => { @@ -225,8 +225,7 @@ macro_rules! impl_checked_ops { 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; @@ -317,8 +316,7 @@ where 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; @@ -345,8 +343,7 @@ where 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; @@ -652,7 +649,7 @@ where *a_arr_position += 1; *b_arr_position += 1; - ptr::write(dst, Float::mul_add(l, a, b)); + dst.write(Float::mul_add(l, a, b)); *destination_position += 1; }); @@ -773,8 +770,8 @@ where let (s, c) = Float::sin_cos(x); - ptr::write(sin, s); - ptr::write(cos, c); + sin.write(s); + cos.write(c); *sin_destination_position += 1; *cos_destination_position += 1; diff --git a/src/simd.rs b/src/simd.rs index e97c6c2..586d7ac 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -4,7 +4,7 @@ use super::*; -use generic_array::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::{ArrayBuilder, ArrayConsumer}; /// Selects elements from one array or another using `self` as a mask. pub unsafe trait Select { @@ -53,9 +53,7 @@ where let value = values.get_unchecked(*index).clone(); *index_position += 1; - - ptr::write(dst, value); - + dst.write(value); *destination_position += 1; }); } @@ -92,7 +90,7 @@ unsafe impl Select for NumericArray { *true_values_position += 1; *false_values_position += 1; - ptr::write(dst, if m { t } else { f }); + dst.write(if m { t } else { f }); *destination_position += 1; }); From 961322c4550f305ead8824cf99b7b1ecf4f8d5f8 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Wed, 13 Sep 2023 02:37:59 -0500 Subject: [PATCH 04/10] WIP 1.0 --- Cargo.toml | 7 +++-- src/impls.rs | 42 +++++++++++---------------- src/lib.rs | 80 ++++++++++++++++++++++++++-------------------------- src/simd.rs | 51 ++++++++++----------------------- 4 files changed, 76 insertions(+), 104 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5efceed..f3f2928 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,20 +4,21 @@ 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.0" readme = "README.md" keywords = ["generic", "array", "numeric", "simd"] include = ["src/**/*", "Cargo.toml"] license = "MIT" categories = ["data-structures"] +edition = "2021" [dependencies] -generic-array = { git = "https://github.com/fizyk20/generic-array", branch = "1.0", features = ["internals"] } +generic-array = { version = "1.0", features = ["internals"] } num-traits = "0.2" serde = { version = "1.0", optional = true, default_features = false } [features] -serde1 = ["serde", "generic-array/serde"] +serde = ["dep:serde", "generic-array/serde"] [dev-dependencies] serde_json = "1.0" diff --git a/src/impls.rs b/src/impls.rs index 2597b65..2650cce 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -233,7 +233,7 @@ macro_rules! impl_checked_ops { } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray(builder.assume_init())) } } } @@ -324,7 +324,7 @@ where } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray(builder.assume_init())) } } } @@ -351,7 +351,7 @@ where } } - Some(NumericArray(builder.into_inner())) + Some(NumericArray(builder.assume_init())) } } } @@ -635,27 +635,19 @@ where let mut destination = ArrayBuilder::new(); - { - let (destination_iter, destination_position) = destination.iter_position(); - - 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); - - *left_position += 1; - *a_arr_position += 1; - *b_arr_position += 1; + destination.extend(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); - dst.write(Float::mul_add(l, a, b)); + *left_position += 1; + *a_arr_position = *left_position; + *b_arr_position = *left_position; - *destination_position += 1; - }); - } + Float::mul_add(l, a, b) + })); - NumericArray::new(destination.into_inner()) + NumericArray::new(destination.assume_init()) } } @@ -773,14 +765,14 @@ where sin.write(s); cos.write(c); - *sin_destination_position += 1; - *cos_destination_position += 1; + *sin_destination_position = *source_position; + *cos_destination_position = *source_position; }); } ( - NumericArray::new(sin_destination.into_inner()), - NumericArray::new(cos_destination.into_inner()), + NumericArray::new(sin_destination.assume_init()), + NumericArray::new(cos_destination.assume_init()), ) } } diff --git a/src/lib.rs b/src/lib.rs index 253b722..90ed538 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,14 +23,14 @@ //! use numeric_array::NumericArray; //! //! 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]); //! } //! ``` //! @@ -289,7 +289,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 +304,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); @@ -583,30 +583,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; @@ -617,8 +617,8 @@ 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); @@ -629,12 +629,12 @@ pub mod tests { 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] @@ -645,13 +645,13 @@ pub mod tests { 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); @@ -661,18 +661,18 @@ 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()); } #[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()); } @@ -681,28 +681,28 @@ pub mod tests { 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 586d7ac..7d97c3b 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -38,65 +38,44 @@ unsafe impl Permute for NumericArray where T: Clone, { + #[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(); + destination.extend(self.0.iter().map(|index| values.get_unchecked(*index).clone())); - *index_position += 1; - dst.write(value); - *destination_position += 1; - }); - } - - NumericArray::new(destination.into_inner()) + NumericArray::new(destination.assume_init()) } } } 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; + destination.extend(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); - dst.write(if m { t } else { f }); + *true_values_position += 1; + *false_values_position = *true_values_position; - *destination_position += 1; - }); - } + match *m { + true => t, + false => f, + } + })); - NumericArray::new(destination.into_inner()) + NumericArray::new(destination.assume_init()) } } } From 68d6915d71237183eca2733388db6de40c1c9f77 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Sat, 16 Sep 2023 21:06:47 -0500 Subject: [PATCH 05/10] Improve codegen --- src/impls.rs | 144 +++++++++++++++++++++++++++++++++------------------ src/lib.rs | 24 +++++---- src/simd.rs | 54 ++++++++++--------- 3 files changed, 138 insertions(+), 84 deletions(-) diff --git a/src/impls.rs b/src/impls.rs index 2650cce..d3b238c 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -18,6 +18,7 @@ use super::*; +use core::mem::{self, ManuallyDrop}; use core::num::FpCategory; use core::ops::*; @@ -34,6 +35,7 @@ macro_rules! impl_unary_ops { { type Output = NumericArray<::Output, N>; + #[inline(always)] fn $op(self) -> Self::Output { NumericArray(self.0.map($op_trait::$op)) } @@ -45,6 +47,7 @@ macro_rules! impl_unary_ops { { type Output = NumericArray<::Output, N>; + #[inline(always)] fn $op(self) -> Self::Output { NumericArray((&self.0).map(|x| $op_trait::$op(x.clone()))) } @@ -62,6 +65,7 @@ macro_rules! impl_binary_ops { { type Output = NumericArray<>::Output, N>; + #[inline(always)] fn $op(self, rhs: NumericArray) -> Self::Output { NumericArray(self.0.zip(rhs.0, $op_trait::$op)) } @@ -73,6 +77,7 @@ macro_rules! impl_binary_ops { { 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()))) } @@ -84,6 +89,7 @@ macro_rules! impl_binary_ops { { 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))) } @@ -95,6 +101,7 @@ macro_rules! impl_binary_ops { { 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()))) } @@ -106,6 +113,7 @@ macro_rules! impl_binary_ops { { 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()))) } @@ -117,6 +125,7 @@ macro_rules! impl_binary_ops { { 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()))) } @@ -128,6 +137,7 @@ macro_rules! impl_binary_ops { { 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))) } @@ -139,6 +149,7 @@ macro_rules! impl_binary_ops { { 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()))) } @@ -155,15 +166,23 @@ macro_rules! impl_assign_ops { 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)); }); } } @@ -624,30 +643,36 @@ where } 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); - - 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(); - - let mut destination = ArrayBuilder::new(); - - destination.extend(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) - })); + 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::new(destination.assume_init()) + 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)) // + })) } } @@ -740,41 +765,58 @@ where } fn sin_cos(self) -> (Self, Self) { - unsafe { - let mut source = ArrayConsumer::new(self.0); + let mut sin_destination = ArrayBuilder::new(); + let mut cos_destination = ArrayBuilder::new(); - let (source_iter, source_position) = source.iter_position(); + if mem::needs_drop::() { + unsafe { + let mut source = ArrayConsumer::new(self.0); - let mut sin_destination = ArrayBuilder::new(); - let mut cos_destination = ArrayBuilder::new(); + let (source_iter, source_position) = source.iter_position(); - { - let (sin_destination_iter, sin_destination_position) = sin_destination.iter_position(); - let (cos_destination_iter, cos_destination_position) = cos_destination.iter_position(); + { + let (sin_destination_iter, sin_destination_position) = sin_destination.iter_position(); + let (cos_destination_iter, cos_destination_position) = cos_destination.iter_position(); + + sin_destination_iter + .zip(cos_destination_iter) + .zip(source_iter) + .for_each(|((sin, cos), src)| { + let x = ptr::read(src); + + *source_position += 1; + + let (s, c) = Float::sin_cos(x); + + 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(source_iter) + .zip(self.iter()) .for_each(|((sin, cos), src)| { - let x = ptr::read(src); - - *source_position += 1; - - let (s, c) = Float::sin_cos(x); + let (s, c) = Float::sin_cos(ptr::read(src)); sin.write(s); cos.write(c); - - *sin_destination_position = *source_position; - *cos_destination_position = *source_position; }); } - - ( - NumericArray::new(sin_destination.assume_init()), - NumericArray::new(cos_destination.assume_init()), - ) } + + ( + NumericArray::new(unsafe { sin_destination.assume_init() }), + NumericArray::new(unsafe { cos_destination.assume_init() }), + ) } fn exp_m1(self) -> Self { diff --git a/src/lib.rs b/src/lib.rs index 90ed538..c62ea04 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -335,19 +335,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 } @@ -355,7 +355,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() } @@ -363,7 +363,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() } @@ -398,7 +398,7 @@ 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()); @@ -410,7 +410,7 @@ 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()); @@ -419,18 +419,21 @@ impl<'a, T, N: ArrayLength> From<&'a mut [T]> for &'a mut NumericArray { } impl AsRef<[T]> for NumericArray { + #[inline(always)] fn as_ref(&self) -> &[T] { self } } impl Borrow<[T]> for NumericArray { + #[inline(always)] fn borrow(&self) -> &[T] { self } } impl AsMut<[T]> for NumericArray { + #[inline(always)] fn as_mut(&mut self) -> &mut [T] { self } @@ -526,7 +529,7 @@ 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() } @@ -536,7 +539,7 @@ 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() } @@ -546,12 +549,14 @@ 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 { + #[inline(always)] fn from_iter(iter: I) -> Self where I: IntoIterator, @@ -564,6 +569,7 @@ impl Default for NumericArray where T: Default, { + #[inline(always)] fn default() -> Self { NumericArray(GenericArray::default()) } diff --git a/src/simd.rs b/src/simd.rs index 7d97c3b..abd2746 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -2,6 +2,8 @@ //! //! These aren't exactly numeric-specific, but they can make use of SIMD instructions. +use core::mem::ManuallyDrop; + use super::*; use generic_array::internals::{ArrayBuilder, ArrayConsumer}; @@ -40,42 +42,46 @@ where { #[inline] fn permute(self, values: &NumericArray) -> NumericArray { - unsafe { - let mut destination = ArrayBuilder::new(); - - destination.extend(self.0.iter().map(|index| values.get_unchecked(*index).clone())); - - NumericArray::new(destination.assume_init()) - } + NumericArray::from_iter(self.iter().map(|index| unsafe { + values.get_unchecked(*index).clone() // + })) } } unsafe impl Select for NumericArray { #[inline] fn select(self, true_values: NumericArray, false_values: NumericArray) -> NumericArray { - unsafe { - let mut true_values = ArrayConsumer::new(true_values.0); - let mut false_values = ArrayConsumer::new(false_values.0); + 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(); + 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(); + 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); - destination.extend(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; - *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 false_values = ManuallyDrop::new(false_values); - match *m { - true => t, - false => f, + NumericArray::from_iter(self.iter().zip(true_values.iter().zip(false_values.iter())).map(|(mask, (t, f))| unsafe { + match *mask { + true => ptr::read(t), + false => ptr::read(f), } - })); - - NumericArray::new(destination.assume_init()) + })) } } } From 4db0b410cc2e62280ae4febb347c283e620d3b52 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Wed, 3 Jul 2024 20:00:54 -0500 Subject: [PATCH 06/10] no_std fixes --- Cargo.toml | 10 +- src/impls.rs | 336 +++++++++++++++++++++++++++++++-------------------- src/lib.rs | 14 ++- 3 files changed, 223 insertions(+), 137 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f3f2928..46904bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ 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.6.0" +version = "0.6.1" readme = "README.md" keywords = ["generic", "array", "numeric", "simd"] include = ["src/**/*", "Cargo.toml"] @@ -13,12 +13,14 @@ categories = ["data-structures"] edition = "2021" [dependencies] -generic-array = { version = "1.0", features = ["internals"] } -num-traits = "0.2" -serde = { version = "1.0", optional = true, default_features = false } +generic-array = { version = "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] serde = ["dep:serde", "generic-array/serde"] +std = ["num-traits/std"] +default = ["std"] [dev-dependencies] serde_json = "1.0" diff --git a/src/impls.rs b/src/impls.rs index d3b238c..aa648ce 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -22,7 +22,7 @@ use core::mem::{self, ManuallyDrop}; use core::num::FpCategory; use core::ops::*; -use num_traits::*; +use num_traits::{float::FloatCore, *}; use generic_array::internals::{ArrayBuilder, ArrayConsumer}; @@ -526,122 +526,210 @@ where } } -impl Float for NumericArray -where - T: Float + Copy, - Self: Copy, -{ - #[inline] - fn nan() -> Self { - Self::splat(Float::nan()) - } +macro_rules! impl_float { + ($float:ident { $($extra:tt)* }) => { + impl $float for NumericArray + where + T: $float, + Self: Copy, + { + $($extra)* - #[inline] - fn infinity() -> Self { - Self::splat(Float::infinity()) - } + #[inline] + fn nan() -> Self { + Self::splat($float::nan()) + } - #[inline] - fn neg_infinity() -> Self { - Self::splat(Float::neg_infinity()) - } + #[inline] + fn infinity() -> Self { + Self::splat($float::infinity()) + } - #[inline] - fn neg_zero() -> Self { - Self::splat(Float::neg_zero()) - } + #[inline] + fn neg_infinity() -> Self { + Self::splat($float::neg_infinity()) + } - #[inline] - fn min_value() -> Self { - Self::splat(Float::min_value()) - } + #[inline] + fn neg_zero() -> Self { + Self::splat($float::neg_zero()) + } - #[inline] - fn min_positive_value() -> Self { - Self::splat(Float::min_positive_value()) - } + #[inline] + fn min_value() -> Self { + Self::splat($float::min_value()) + } - #[inline] - fn max_value() -> Self { - Self::splat(Float::max_value()) - } + #[inline] + fn min_positive_value() -> Self { + Self::splat($float::min_positive_value()) + } - fn is_nan(self) -> bool { - self.iter().any(|x| Float::is_nan(*x)) - } + #[inline] + fn max_value() -> Self { + Self::splat($float::max_value()) + } - fn is_infinite(self) -> bool { - self.iter().any(|x| Float::is_infinite(*x)) - } + #[inline] + fn is_nan(self) -> bool { + self.iter().any(|x| $float::is_nan(*x)) + } - fn is_finite(self) -> bool { - self.iter().all(|x| Float::is_finite(*x)) - } + #[inline] + fn is_infinite(self) -> bool { + self.iter().any(|x| $float::is_infinite(*x)) + } - fn is_normal(self) -> bool { - self.iter().all(|x| Float::is_normal(*x)) - } + #[inline] + fn is_finite(self) -> bool { + self.iter().all(|x| $float::is_finite(*x)) + } + + #[inline] + fn is_normal(self) -> bool { + self.iter().all(|x| $float::is_normal(*x)) + } + + #[inline] + fn epsilon() -> Self { + Self::splat($float::epsilon()) + } + + #[inline] + fn to_degrees(self) -> Self { + self.0.map($float::to_degrees).into() + } - fn classify(self) -> FpCategory { - let mut ret = FpCategory::Zero; + #[inline] + fn to_radians(self) -> Self { + self.0.map($float::to_radians).into() + } - 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; + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + if N::to_usize() == 0 { + (0, 0, 0) + } else { + self.first().unwrap().integer_decode() } - // If normal and zero, upgrade to normal - FpCategory::Normal if ret == FpCategory::Zero => { - ret = FpCategory::Normal; + } + + 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; + } + _ => {} + } } - _ => {} + + ret } - } - ret - } + #[inline] + fn floor(self) -> Self { + self.0.map($float::floor).into() + } - fn floor(self) -> Self { - self.0.map(Float::floor).into() - } + #[inline] + fn ceil(self) -> Self { + self.0.map($float::ceil).into() + } - fn ceil(self) -> Self { - self.0.map(Float::ceil).into() - } + #[inline] + fn round(self) -> Self { + self.0.map($float::round).into() + } - fn round(self) -> Self { - self.0.map(Float::round).into() - } + #[inline] + fn trunc(self) -> Self { + self.0.map($float::trunc).into() + } - fn trunc(self) -> Self { - self.0.map(Float::trunc).into() - } + #[inline] + fn fract(self) -> Self { + self.0.map($float::fract).into() + } - fn fract(self) -> Self { - self.0.map(Float::fract).into() - } + #[inline] + fn abs(self) -> Self { + self.0.map($float::abs).into() + } - fn abs(self) -> Self { - self.0.map(Float::abs).into() - } + #[inline] + fn signum(self) -> Self { + self.0.map($float::signum).into() + } - fn signum(self) -> Self { - self.0.map(Float::signum).into() - } + #[inline] + fn is_sign_positive(self) -> bool { + self.iter().all(|x| $float::is_sign_positive(*x)) + } - fn is_sign_positive(self) -> bool { - self.iter().all(|x| Float::is_sign_positive(*x)) - } + #[inline] + fn is_sign_negative(self) -> bool { + self.iter().any(|x| $float::is_sign_negative(*x)) + } - fn is_sign_negative(self) -> bool { - self.iter().any(|x| Float::is_sign_negative(*x)) - } + #[inline] + fn max(self, other: Self) -> Self { + self.0.zip(other.0, $float::max).into() + } + + #[inline] + fn min(self, other: Self) -> Self { + self.0.zip(other.0, $float::min).into() + } + + #[inline] + fn recip(self) -> Self { + self.0.map($float::recip).into() + } + + #[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 + } + } + }; +} + +impl_float!(FloatCore {}); +#[cfg(feature = "std")] +impl_float!(Float { + #[inline] fn mul_add(self, a: Self, b: Self) -> Self { if mem::needs_drop::() { unsafe { @@ -676,94 +764,97 @@ where } } - fn recip(self) -> Self { - self.0.map(Float::recip).into() - } - - fn powi(self, n: i32) -> Self { - self.0.map(|x| Float::powi(x, n)).into() - } - + #[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) { let mut sin_destination = ArrayBuilder::new(); let mut cos_destination = ArrayBuilder::new(); @@ -819,56 +910,43 @@ where ) } + #[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 c62ea04..85b4885 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,7 @@ //! use num_traits::Float; //! use numeric_array::NumericArray; //! +//! # #[cfg(feature = "std")] //! fn main() { //! let a = narr![1.0, 2.0, 3.0, 4.0]; //! let b = narr![5.0, 6.0, 7.0, 8.0]; @@ -32,6 +33,8 @@ //! //! 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"`, @@ -50,8 +53,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}; @@ -101,7 +103,7 @@ pub struct NumericArray(GenericArray); #[macro_export] macro_rules! narr { ($($t:tt)*) => { - $crate::NumericArray::new(arr!($($t)*)) + $crate::NumericArray::new($crate::generic_array::arr!($($t)*)) } } @@ -577,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 { @@ -631,6 +635,7 @@ pub mod tests { black_box(c); } + #[cfg(feature = "std")] #[test] fn test_atan2() { use num_traits::Float; @@ -646,7 +651,6 @@ pub mod tests { #[test] fn test_classify() { use core::num::FpCategory; - use num_traits::Float; let nan = f32::nan(); let infinity = f32::infinity(); @@ -674,6 +678,7 @@ pub mod tests { assert!(!any_infinite.is_nan()); } + #[cfg(feature = "std")] #[test] fn test_tanh() { use num_traits::Float; @@ -683,6 +688,7 @@ pub mod tests { black_box(a.tanh()); } + #[cfg(feature = "std")] #[test] pub fn test_madd() { use num_traits::Float; From c159b5c22507d415c213938a80185b6e24598ed0 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Wed, 3 Jul 2024 20:01:03 -0500 Subject: [PATCH 07/10] Misc fixes --- src/simd.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/simd.rs b/src/simd.rs index abd2746..2b5bd56 100644 --- a/src/simd.rs +++ b/src/simd.rs @@ -6,7 +6,7 @@ use core::mem::ManuallyDrop; use super::*; -use generic_array::internals::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::ArrayConsumer; /// Selects elements from one array or another using `self` as a mask. pub unsafe trait Select { @@ -27,6 +27,8 @@ 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; } @@ -36,14 +38,17 @@ pub unsafe trait Permute { fn permute(self, values: &NumericArray) -> NumericArray; } -unsafe impl Permute for NumericArray +unsafe impl Permute for NumericArray where T: Clone, + I: Copy + Into, { #[inline] fn permute(self, values: &NumericArray) -> NumericArray { NumericArray::from_iter(self.iter().map(|index| unsafe { - values.get_unchecked(*index).clone() // + let index: usize = (*index).into(); + + values.get_unchecked(index.min(N::to_usize())).clone() })) } } @@ -74,14 +79,15 @@ unsafe impl Select for NumericArray { } } else { let true_values = ManuallyDrop::new(true_values); - let false_values = ManuallyDrop::new(false_values); + let mut values = ManuallyDrop::new(false_values); - NumericArray::from_iter(self.iter().zip(true_values.iter().zip(false_values.iter())).map(|(mask, (t, f))| unsafe { - match *mask { - true => ptr::read(t), - false => ptr::read(f), + for (mask, (v, t)) in self.iter().zip(values.iter_mut().zip(true_values.iter())) { + if *mask { + unsafe { ptr::copy_nonoverlapping(t, v, 1) }; } - })) + } + + ManuallyDrop::into_inner(values) } } } From bb1d5e48215b5c28aaebd10a232a68401793e01c Mon Sep 17 00:00:00 2001 From: novacrazy Date: Wed, 3 Jul 2024 22:09:16 -0500 Subject: [PATCH 08/10] Docs and cleanup --- Cargo.toml | 8 +- LICENSE-Apache | 202 ++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 19 +++++ README.md | 18 ++--- src/geometry.rs | 2 +- src/lib.rs | 31 ++++---- 6 files changed, 249 insertions(+), 31 deletions(-) create mode 100644 LICENSE-Apache create mode 100644 LICENSE-MIT diff --git a/Cargo.toml b/Cargo.toml index 46904bf..cbb9892 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [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" @@ -7,9 +7,9 @@ documentation = "https://docs.rs/numeric-array" 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] 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 102cdb4..c00f0a0 100644 --- a/src/geometry.rs +++ b/src/geometry.rs @@ -18,7 +18,7 @@ pub trait Geometric { impl Geometric for NumericArray where - T: Add + Mul + Zero + Copy, + T: Mul + Zero + Copy, { #[inline(always)] fn scalar_product(&self, other: &Self) -> T { diff --git a/src/lib.rs b/src/lib.rs index 85b4885..b949a5b 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,14 +20,8 @@ //! 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() { @@ -38,14 +39,12 @@ //! ``` //! //! 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)] From b08a7ae2d58283da6d46d5604b78234c5adb6b77 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Thu, 4 Jul 2024 22:19:11 -0500 Subject: [PATCH 09/10] generic-array updates --- src/geometry.rs | 2 +- src/impls.rs | 37 ++++++++++++++++++++++++++----------- src/lib.rs | 1 + 3 files changed, 28 insertions(+), 12 deletions(-) diff --git a/src/geometry.rs b/src/geometry.rs index c00f0a0..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}; diff --git a/src/impls.rs b/src/impls.rs index aa648ce..43f5c83 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -24,7 +24,7 @@ use core::ops::*; use num_traits::{float::FloatCore, *}; -use generic_array::internals::{ArrayBuilder, ArrayConsumer}; +use generic_array::internals::{ArrayConsumer, IntrusiveArrayBuilder}; macro_rules! impl_unary_ops { ($($op_trait:ident::$op:ident),*) => { @@ -237,7 +237,8 @@ macro_rules! impl_checked_ops { { 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(); @@ -252,7 +253,10 @@ macro_rules! impl_checked_ops { } } - Some(NumericArray(builder.assume_init())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } @@ -328,7 +332,8 @@ where { 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(); @@ -343,7 +348,10 @@ where } } - Some(NumericArray(builder.assume_init())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } @@ -355,7 +363,8 @@ where { 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(); @@ -370,7 +379,10 @@ where } } - Some(NumericArray(builder.assume_init())) + Some(NumericArray({ + builder.finish(); + IntrusiveArrayBuilder::array_assume_init(array) + })) } } } @@ -856,8 +868,11 @@ impl_float!(Float { #[inline] fn sin_cos(self) -> (Self, Self) { - let mut sin_destination = ArrayBuilder::new(); - let mut cos_destination = ArrayBuilder::new(); + let mut sin_array = GenericArray::uninit(); + let mut cos_array = GenericArray::uninit(); + + let mut sin_destination = IntrusiveArrayBuilder::new(&mut sin_array); + let mut cos_destination = IntrusiveArrayBuilder::new(&mut cos_array); if mem::needs_drop::() { unsafe { @@ -905,8 +920,8 @@ impl_float!(Float { } ( - NumericArray::new(unsafe { sin_destination.assume_init() }), - NumericArray::new(unsafe { cos_destination.assume_init() }), + NumericArray::new(unsafe { sin_destination.finish(); IntrusiveArrayBuilder::array_assume_init(sin_array) }), + NumericArray::new(unsafe { cos_destination.finish(); IntrusiveArrayBuilder::array_assume_init(cos_array) }), ) } diff --git a/src/lib.rs b/src/lib.rs index b949a5b..960b2d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,6 +110,7 @@ unsafe impl GenericSequence for NumericArray { type Length = N; type Sequence = Self; + #[inline(always)] fn generate(f: F) -> Self where F: FnMut(usize) -> T, From edc59de924a7c7c82136098400203e1bb8d85221 Mon Sep 17 00:00:00 2001 From: novacrazy Date: Fri, 5 Jul 2024 00:52:56 -0500 Subject: [PATCH 10/10] Use generic-array 1.1.0 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index cbb9892..2d06da0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ categories = ["data-structures", "no-std"] edition = "2021" [dependencies] -generic-array = { version = "1.0", default-features = false, features = ["internals"] } +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 }