From 9142dc8f84fa466114c8e784f05b8f6d5f961242 Mon Sep 17 00:00:00 2001 From: Andreas Longva Date: Sat, 17 Apr 2021 16:41:52 +0200 Subject: [PATCH] Implement SMatrix::from_array_storage and use it in matriX! impl This allows us to avoid injecting unsafe code into every macro invocation, which seems desirable. --- nalgebra-macros/src/lib.rs | 5 +---- src/base/array_storage.rs | 12 ++++++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/nalgebra-macros/src/lib.rs b/nalgebra-macros/src/lib.rs index 06f6a2cc..a18162ab 100644 --- a/nalgebra-macros/src/lib.rs +++ b/nalgebra-macros/src/lib.rs @@ -90,12 +90,9 @@ pub fn matrix(stream: TokenStream) -> TokenStream { let array_tokens = matrix.col_major_array_tokens(); // TODO: Use quote_spanned instead?? - // TODO: Avoid use of unsafe here let output = quote! { - unsafe { nalgebra::SMatrix::<_, #row_dim, #col_dim> - ::from_data_statically_unchecked(nalgebra::ArrayStorage(#array_tokens)) - } + ::from_array_storage(nalgebra::ArrayStorage(#array_tokens)) }; proc_macro::TokenStream::from(output) diff --git a/src/base/array_storage.rs b/src/base/array_storage.rs index 68da4c51..dc6b22ce 100644 --- a/src/base/array_storage.rs +++ b/src/base/array_storage.rs @@ -25,6 +25,7 @@ use crate::base::storage::{ ContiguousStorage, ContiguousStorageMut, Owned, ReshapableStorage, Storage, StorageMut, }; use crate::base::Scalar; +use crate::SMatrix; /* * @@ -299,3 +300,14 @@ where self.as_slice().iter().fold(0, |acc, e| acc + e.extent()) } } + +// TODO: Where to put this impl block? +impl SMatrix { + /// Creates a new statically-allocated matrix from the given [ArrayStorage]. + #[inline(always)] + pub const fn from_array_storage(storage: ArrayStorage) -> Self { + // This is sound because the row and column types are exactly the same as that of the + // storage, so there can be no mismatch + unsafe { Self::from_data_statically_unchecked(storage) } + } +}