nalgebra/base/
allocator.rs

1//! Abstract definition of a matrix data storage allocator.
2
3use std::any::Any;
4
5use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint};
6use crate::base::dimension::{Dim, U1};
7use crate::base::{DefaultAllocator, Scalar};
8use crate::storage::{IsContiguous, RawStorageMut};
9use crate::StorageMut;
10use std::fmt::Debug;
11use std::mem::MaybeUninit;
12
13/// A matrix allocator of a memory buffer that may contain `R::to_usize() * C::to_usize()`
14/// elements of type `T`.
15///
16/// An allocator is said to be:
17///   − static:  if `R` and `C` both implement `DimName`.
18///   − dynamic: if either one (or both) of `R` or `C` is equal to `Dyn`.
19///
20/// Every allocator must be both static and dynamic. Though not all implementations may share the
21/// same `Buffer` type.
22pub trait Allocator<R: Dim, C: Dim = U1>: Any + Sized {
23    /// The type of buffer this allocator can instantiate.
24    type Buffer<T: Scalar>: StorageMut<T, R, C> + IsContiguous + Clone + Debug;
25    /// The type of buffer with uninitialized components this allocator can instantiate.
26    type BufferUninit<T: Scalar>: RawStorageMut<MaybeUninit<T>, R, C> + IsContiguous;
27
28    /// Allocates a buffer with the given number of rows and columns without initializing its content.
29    fn allocate_uninit<T: Scalar>(nrows: R, ncols: C) -> Self::BufferUninit<T>;
30
31    /// Assumes a data buffer to be initialized.
32    ///
33    /// # Safety
34    /// The user must make sure that every single entry of the buffer has been initialized,
35    /// or Undefined Behavior will immediately occur.    
36    unsafe fn assume_init<T: Scalar>(uninit: Self::BufferUninit<T>) -> Self::Buffer<T>;
37
38    /// Allocates a buffer initialized with the content of the given iterator.
39    fn allocate_from_iterator<T: Scalar, I: IntoIterator<Item = T>>(
40        nrows: R,
41        ncols: C,
42        iter: I,
43    ) -> Self::Buffer<T>;
44
45    #[inline]
46    /// Allocates a buffer initialized with the content of the given row-major order iterator.
47    fn allocate_from_row_iterator<T: Scalar, I: IntoIterator<Item = T>>(
48        nrows: R,
49        ncols: C,
50        iter: I,
51    ) -> Self::Buffer<T> {
52        let mut res = Self::allocate_uninit(nrows, ncols);
53        let mut count = 0;
54
55        unsafe {
56            // OK because the allocated buffer is guaranteed to be contiguous.
57            let res_ptr = res.as_mut_slice_unchecked();
58
59            for (k, e) in iter
60                .into_iter()
61                .take(ncols.value() * nrows.value())
62                .enumerate()
63            {
64                let i = k / ncols.value();
65                let j = k % ncols.value();
66                // result[(i, j)] = e;
67                *res_ptr.get_unchecked_mut(i + j * nrows.value()) = MaybeUninit::new(e);
68                count += 1;
69            }
70
71            assert!(
72                count == nrows.value() * ncols.value(),
73                "Matrix init. from row iterator: iterator not long enough."
74            );
75
76            <Self as Allocator<R, C>>::assume_init(res)
77        }
78    }
79}
80
81/// A matrix reallocator. Changes the size of the memory buffer that initially contains (`RFrom` ×
82/// `CFrom`) elements to a smaller or larger size (`RTo`, `CTo`).
83pub trait Reallocator<T: Scalar, RFrom: Dim, CFrom: Dim, RTo: Dim, CTo: Dim>:
84    Allocator<RFrom, CFrom> + Allocator<RTo, CTo>
85{
86    /// Reallocates a buffer of shape `(RTo, CTo)`, possibly reusing a previously allocated buffer
87    /// `buf`. Data stored by `buf` are linearly copied to the output:
88    ///
89    /// # Safety
90    /// The following invariants must be respected by the implementors of this method:
91    /// * The copy is performed as if both were just arrays (without taking into account the matrix structure).
92    /// * If the underlying buffer is being shrunk, the removed elements must **not** be dropped
93    ///   by this method. Dropping them is the responsibility of the caller.
94    unsafe fn reallocate_copy(
95        nrows: RTo,
96        ncols: CTo,
97        buf: <Self as Allocator<RFrom, CFrom>>::Buffer<T>,
98    ) -> <Self as Allocator<RTo, CTo>>::BufferUninit<T>;
99}
100
101/// The number of rows of the result of a componentwise operation on two matrices.
102pub type SameShapeR<R1, R2> = <ShapeConstraint as SameNumberOfRows<R1, R2>>::Representative;
103
104/// The number of columns of the result of a componentwise operation on two matrices.
105pub type SameShapeC<C1, C2> = <ShapeConstraint as SameNumberOfColumns<C1, C2>>::Representative;
106
107// TODO: Bad name.
108/// Restricts the given number of rows and columns to be respectively the same.
109pub trait SameShapeAllocator<R1, C1, R2, C2>:
110    Allocator<R1, C1> + Allocator<SameShapeR<R1, R2>, SameShapeC<C1, C2>>
111where
112    R1: Dim,
113    R2: Dim,
114    C1: Dim,
115    C2: Dim,
116    ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>,
117{
118}
119
120impl<R1, R2, C1, C2> SameShapeAllocator<R1, C1, R2, C2> for DefaultAllocator
121where
122    R1: Dim,
123    R2: Dim,
124    C1: Dim,
125    C2: Dim,
126    DefaultAllocator: Allocator<R1, C1> + Allocator<SameShapeR<R1, R2>, SameShapeC<C1, C2>>,
127    ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>,
128{
129}
130
131// XXX: Bad name.
132/// Restricts the given number of rows to be equal.
133pub trait SameShapeVectorAllocator<R1, R2>:
134    Allocator<R1> + Allocator<SameShapeR<R1, R2>> + SameShapeAllocator<R1, U1, R2, U1>
135where
136    R1: Dim,
137    R2: Dim,
138    ShapeConstraint: SameNumberOfRows<R1, R2>,
139{
140}
141
142impl<R1, R2> SameShapeVectorAllocator<R1, R2> for DefaultAllocator
143where
144    R1: Dim,
145    R2: Dim,
146    DefaultAllocator: Allocator<R1, U1> + Allocator<SameShapeR<R1, R2>>,
147    ShapeConstraint: SameNumberOfRows<R1, R2>,
148{
149}