Skip to content

Commit

Permalink
Add UninitScalar newtype for defining traits on a MaybeUninit<Scalar>.
Browse files Browse the repository at this point in the history
  • Loading branch information
aweinstock314 committed Nov 19, 2019
1 parent 4d38537 commit 7d040b7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/base/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::any::Any;
use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint};
use crate::base::dimension::{Dim, U1};
use crate::base::storage::ContiguousStorageMut;
use crate::base::{DefaultAllocator, Scalar};
use crate::base::{DefaultAllocator, Scalar, UninitScalar};

/// A matrix allocator of a memory buffer that may contain `R::to_usize() * C::to_usize()`
/// elements of type `N`.
Expand All @@ -21,6 +21,7 @@ pub trait Allocator<N: Scalar + Copy, R: Dim, C: Dim = U1>: Any + Sized {
type Buffer: ContiguousStorageMut<N, R, C> + Clone;

/// Allocates a buffer with the given number of rows and columns without initializing its content.
//unsafe fn allocate_uninitialized(nrows: R, ncols: C) -> <Self as Allocator<UninitScalar<N>, R, C>>::Buffer;
unsafe fn allocate_uninitialized(nrows: R, ncols: C) -> Self::Buffer;

/// Allocates a buffer initialized with the content of the given iterator.
Expand Down
25 changes: 24 additions & 1 deletion src/base/scalar.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::any::Any;
use std::any::TypeId;
use std::fmt::Debug;
use std::fmt::{self, Debug, Formatter};
use std::mem::MaybeUninit;

/// The basic scalar type for all structures of `nalgebra`.
///
Expand All @@ -15,3 +16,25 @@ pub trait Scalar: PartialEq + Debug + Any {
}
}
impl<T: Copy + PartialEq + Debug + Any> Scalar for T {}

/// A newtype wrapper that provides the necessary trait implementations for MaybeUninit
/// This is needed because MaybeUninit does not pass through implementations on uninitialized data (for good reason)
pub struct UninitScalar<S: Scalar>(MaybeUninit<S>);

impl<S: Scalar> Clone for UninitScalar<S> {
fn clone(&self) -> Self {
panic!("Clone::clone called on potentially uninitialized data")
}
}

impl<S: Scalar> PartialEq for UninitScalar<S> {
fn eq(&self, _: &Self) -> bool {
panic!("PartialEq::eq called on potentially uninitalized data")
}
}
impl<S: Scalar> Debug for UninitScalar<S> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "UninitScalar")
}
}
impl<S: Scalar> Scalar for UninitScalar<S> {}

0 comments on commit 7d040b7

Please sign in to comment.