nalgebra/base/
vec_storage.rs

1#[cfg(all(feature = "alloc", not(feature = "std")))]
2use alloc::vec::Vec;
3
4use crate::base::allocator::Allocator;
5use crate::base::constraint::{SameNumberOfRows, ShapeConstraint};
6use crate::base::default_allocator::DefaultAllocator;
7use crate::base::dimension::{Dim, DimName, Dyn, U1};
8use crate::base::storage::{IsContiguous, Owned, RawStorage, RawStorageMut, ReshapableStorage};
9use crate::base::{Scalar, Vector};
10
11#[cfg(feature = "serde-serialize-no-std")]
12use serde::{
13    de::{Deserialize, Deserializer, Error},
14    ser::{Serialize, Serializer},
15};
16
17use crate::Storage;
18use std::mem::MaybeUninit;
19
20/*
21 *
22 * RawStorage.
23 *
24 */
25/// A Vec-based matrix data storage. It may be dynamically-sized.
26#[repr(C)]
27#[derive(Eq, Debug, Clone, PartialEq)]
28pub struct VecStorage<T, R: Dim, C: Dim> {
29    data: Vec<T>,
30    nrows: R,
31    ncols: C,
32}
33
34impl<T> Default for VecStorage<T, Dyn, Dyn> {
35    fn default() -> Self {
36        Self {
37            data: Vec::new(),
38            nrows: Dyn::from_usize(0),
39            ncols: Dyn::from_usize(0),
40        }
41    }
42}
43
44impl<T, R: DimName> Default for VecStorage<T, R, Dyn> {
45    fn default() -> Self {
46        Self {
47            data: Vec::new(),
48            nrows: R::name(),
49            ncols: Dyn::from_usize(0),
50        }
51    }
52}
53
54impl<T, C: DimName> Default for VecStorage<T, Dyn, C> {
55    fn default() -> Self {
56        Self {
57            data: Vec::new(),
58            nrows: Dyn::from_usize(0),
59            ncols: C::name(),
60        }
61    }
62}
63
64impl<T: Default, R: DimName, C: DimName> Default for VecStorage<T, R, C> {
65    fn default() -> Self {
66        let nrows = R::name();
67        let ncols = C::name();
68        let mut data = Vec::new();
69        data.resize_with(nrows.value() * ncols.value(), Default::default);
70        Self { data, nrows, ncols }
71    }
72}
73
74#[cfg(feature = "serde-serialize")]
75impl<T, R: Dim, C: Dim> Serialize for VecStorage<T, R, C>
76where
77    T: Serialize,
78    R: Serialize,
79    C: Serialize,
80{
81    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
82    where
83        Ser: Serializer,
84    {
85        (&self.data, &self.nrows, &self.ncols).serialize(serializer)
86    }
87}
88
89#[cfg(feature = "serde-serialize")]
90impl<'a, T, R: Dim, C: Dim> Deserialize<'a> for VecStorage<T, R, C>
91where
92    T: Deserialize<'a>,
93    R: Deserialize<'a>,
94    C: Deserialize<'a>,
95{
96    fn deserialize<Des>(deserializer: Des) -> Result<Self, Des::Error>
97    where
98        Des: Deserializer<'a>,
99    {
100        let (data, nrows, ncols): (Vec<T>, R, C) = Deserialize::deserialize(deserializer)?;
101
102        // SAFETY: make sure the data we deserialize have the
103        //         correct number of elements.
104        if nrows.value() * ncols.value() != data.len() {
105            return Err(Des::Error::custom(format!(
106                "Expected {} components, found {}",
107                nrows.value() * ncols.value(),
108                data.len()
109            )));
110        }
111
112        Ok(Self { data, nrows, ncols })
113    }
114}
115
116#[deprecated(note = "renamed to `VecStorage`")]
117/// Renamed to [`VecStorage`].
118pub type MatrixVec<T, R, C> = VecStorage<T, R, C>;
119
120impl<T, R: Dim, C: Dim> VecStorage<T, R, C> {
121    /// Creates a new dynamic matrix data storage from the given vector and shape.
122    #[inline]
123    pub fn new(nrows: R, ncols: C, data: Vec<T>) -> Self {
124        assert!(
125            nrows.value() * ncols.value() == data.len(),
126            "Data storage buffer dimension mismatch."
127        );
128        Self { data, nrows, ncols }
129    }
130
131    /// The underlying data storage.
132    #[inline]
133    #[must_use]
134    pub const fn as_vec(&self) -> &Vec<T> {
135        &self.data
136    }
137
138    /// The underlying mutable data storage.
139    ///
140    /// # Safety
141    /// This is unsafe because this may cause UB if the size of the vector is changed
142    /// by the user.
143    #[inline]
144    pub const unsafe fn as_vec_mut(&mut self) -> &mut Vec<T> {
145        &mut self.data
146    }
147
148    /// Resizes the underlying mutable data storage and unwraps it.
149    ///
150    /// # Safety
151    /// - If `sz` is larger than the current size, additional elements are uninitialized.
152    /// - If `sz` is smaller than the current size, additional elements are truncated but **not** dropped.
153    ///   It is the responsibility of the caller of this method to drop these elements.
154    #[inline]
155    pub unsafe fn resize(mut self, sz: usize) -> Vec<MaybeUninit<T>> {
156        unsafe {
157            let len = self.len();
158
159            let new_data = if sz < len {
160                // Use `set_len` instead of `truncate` because we don’t want to
161                // drop the removed elements (it’s the caller’s responsibility).
162                self.data.set_len(sz);
163                self.data.shrink_to_fit();
164
165                // Safety:
166                // - MaybeUninit<T> has the same alignment and layout as T.
167                // - The length and capacity come from a valid vector.
168                Vec::from_raw_parts(
169                    self.data.as_mut_ptr() as *mut MaybeUninit<T>,
170                    self.data.len(),
171                    self.data.capacity(),
172                )
173            } else {
174                self.data.reserve_exact(sz - len);
175
176                // Safety:
177                // - MaybeUninit<T> has the same alignment and layout as T.
178                // - The length and capacity come from a valid vector.
179                let mut new_data = Vec::from_raw_parts(
180                    self.data.as_mut_ptr() as *mut MaybeUninit<T>,
181                    self.data.len(),
182                    self.data.capacity(),
183                );
184
185                // Safety: we can set the length here because MaybeUninit is always assumed
186                //         to be initialized.
187                new_data.set_len(sz);
188                new_data
189            };
190
191            // Avoid double-free by forgetting `self` because its data buffer has
192            // been transferred to `new_data`.
193            std::mem::forget(self);
194            new_data
195        }
196    }
197
198    /// The number of elements on the underlying vector.
199    #[inline]
200    #[must_use]
201    pub const fn len(&self) -> usize {
202        self.data.len()
203    }
204
205    /// Returns true if the underlying vector contains no elements.
206    #[inline]
207    #[must_use]
208    pub const fn is_empty(&self) -> bool {
209        self.len() == 0
210    }
211
212    /// A slice containing all the components stored in this storage in column-major order.
213    #[inline]
214    pub fn as_slice(&self) -> &[T] {
215        &self.data[..]
216    }
217
218    /// A mutable slice containing all the components stored in this storage in column-major order.
219    #[inline]
220    pub fn as_mut_slice(&mut self) -> &mut [T] {
221        &mut self.data[..]
222    }
223}
224
225impl<T, R: Dim, C: Dim> From<VecStorage<T, R, C>> for Vec<T> {
226    fn from(vec: VecStorage<T, R, C>) -> Self {
227        vec.data
228    }
229}
230
231/*
232 *
233 * Dyn − Static
234 * Dyn − Dyn
235 *
236 */
237unsafe impl<T, C: Dim> RawStorage<T, Dyn, C> for VecStorage<T, Dyn, C> {
238    type RStride = U1;
239    type CStride = Dyn;
240
241    #[inline]
242    fn ptr(&self) -> *const T {
243        self.data.as_ptr()
244    }
245
246    #[inline]
247    fn shape(&self) -> (Dyn, C) {
248        (self.nrows, self.ncols)
249    }
250
251    #[inline]
252    fn strides(&self) -> (Self::RStride, Self::CStride) {
253        (Self::RStride::name(), self.nrows)
254    }
255
256    #[inline]
257    fn is_contiguous(&self) -> bool {
258        true
259    }
260
261    #[inline]
262    unsafe fn as_slice_unchecked(&self) -> &[T] {
263        &self.data
264    }
265}
266
267unsafe impl<T: Scalar, C: Dim> Storage<T, Dyn, C> for VecStorage<T, Dyn, C>
268where
269    DefaultAllocator: Allocator<Dyn, C, Buffer<T> = Self>,
270{
271    #[inline]
272    fn into_owned(self) -> Owned<T, Dyn, C>
273    where
274        DefaultAllocator: Allocator<Dyn, C>,
275    {
276        self
277    }
278
279    #[inline]
280    fn clone_owned(&self) -> Owned<T, Dyn, C>
281    where
282        DefaultAllocator: Allocator<Dyn, C>,
283    {
284        self.clone()
285    }
286
287    #[inline]
288    fn forget_elements(mut self) {
289        // SAFETY: setting the length to zero is always sound, as it does not
290        // cause any memory to be deemed initialized. If the previous length was
291        // non-zero, it is equivalent to using mem::forget to leak each element.
292        // Then, when this function returns, self.data is dropped, freeing the
293        // allocated memory, but the elements are not dropped because they are
294        // now considered uninitialized.
295        unsafe { self.data.set_len(0) };
296    }
297}
298
299unsafe impl<T, R: DimName> RawStorage<T, R, Dyn> for VecStorage<T, R, Dyn> {
300    type RStride = U1;
301    type CStride = R;
302
303    #[inline]
304    fn ptr(&self) -> *const T {
305        self.data.as_ptr()
306    }
307
308    #[inline]
309    fn shape(&self) -> (R, Dyn) {
310        (self.nrows, self.ncols)
311    }
312
313    #[inline]
314    fn strides(&self) -> (Self::RStride, Self::CStride) {
315        (Self::RStride::name(), self.nrows)
316    }
317
318    #[inline]
319    fn is_contiguous(&self) -> bool {
320        true
321    }
322
323    #[inline]
324    unsafe fn as_slice_unchecked(&self) -> &[T] {
325        &self.data
326    }
327}
328
329unsafe impl<T: Scalar, R: DimName> Storage<T, R, Dyn> for VecStorage<T, R, Dyn>
330where
331    DefaultAllocator: Allocator<R, Dyn, Buffer<T> = Self>,
332{
333    #[inline]
334    fn into_owned(self) -> Owned<T, R, Dyn>
335    where
336        DefaultAllocator: Allocator<R, Dyn>,
337    {
338        self
339    }
340
341    #[inline]
342    fn clone_owned(&self) -> Owned<T, R, Dyn>
343    where
344        DefaultAllocator: Allocator<R, Dyn>,
345    {
346        self.clone()
347    }
348
349    #[inline]
350    fn forget_elements(mut self) {
351        // SAFETY: setting the length to zero is always sound, as it does not
352        // cause any memory to be deemed initialized. If the previous length was
353        // non-zero, it is equivalent to using mem::forget to leak each element.
354        // Then, when this function returns, self.data is dropped, freeing the
355        // allocated memory, but the elements are not dropped because they are
356        // now considered uninitialized.
357        unsafe { self.data.set_len(0) };
358    }
359}
360
361/*
362 *
363 * RawStorageMut, ContiguousStorage.
364 *
365 */
366unsafe impl<T, C: Dim> RawStorageMut<T, Dyn, C> for VecStorage<T, Dyn, C> {
367    #[inline]
368    fn ptr_mut(&mut self) -> *mut T {
369        self.data.as_mut_ptr()
370    }
371
372    #[inline]
373    unsafe fn as_mut_slice_unchecked(&mut self) -> &mut [T] {
374        &mut self.data[..]
375    }
376}
377
378unsafe impl<T, R: Dim, C: Dim> IsContiguous for VecStorage<T, R, C> {}
379
380impl<T, C1, C2> ReshapableStorage<T, Dyn, C1, Dyn, C2> for VecStorage<T, Dyn, C1>
381where
382    T: Scalar,
383    C1: Dim,
384    C2: Dim,
385{
386    type Output = VecStorage<T, Dyn, C2>;
387
388    fn reshape_generic(self, nrows: Dyn, ncols: C2) -> Self::Output {
389        assert_eq!(nrows.value() * ncols.value(), self.data.len());
390        VecStorage {
391            data: self.data,
392            nrows,
393            ncols,
394        }
395    }
396}
397
398impl<T, C1, R2> ReshapableStorage<T, Dyn, C1, R2, Dyn> for VecStorage<T, Dyn, C1>
399where
400    T: Scalar,
401    C1: Dim,
402    R2: DimName,
403{
404    type Output = VecStorage<T, R2, Dyn>;
405
406    fn reshape_generic(self, nrows: R2, ncols: Dyn) -> Self::Output {
407        assert_eq!(nrows.value() * ncols.value(), self.data.len());
408        VecStorage {
409            data: self.data,
410            nrows,
411            ncols,
412        }
413    }
414}
415
416unsafe impl<T, R: DimName> RawStorageMut<T, R, Dyn> for VecStorage<T, R, Dyn> {
417    #[inline]
418    fn ptr_mut(&mut self) -> *mut T {
419        self.data.as_mut_ptr()
420    }
421
422    #[inline]
423    unsafe fn as_mut_slice_unchecked(&mut self) -> &mut [T] {
424        &mut self.data[..]
425    }
426}
427
428impl<T, R1, C2> ReshapableStorage<T, R1, Dyn, Dyn, C2> for VecStorage<T, R1, Dyn>
429where
430    T: Scalar,
431    R1: DimName,
432    C2: Dim,
433{
434    type Output = VecStorage<T, Dyn, C2>;
435
436    fn reshape_generic(self, nrows: Dyn, ncols: C2) -> Self::Output {
437        assert_eq!(nrows.value() * ncols.value(), self.data.len());
438        VecStorage {
439            data: self.data,
440            nrows,
441            ncols,
442        }
443    }
444}
445
446impl<T, R1, R2> ReshapableStorage<T, R1, Dyn, R2, Dyn> for VecStorage<T, R1, Dyn>
447where
448    T: Scalar,
449    R1: DimName,
450    R2: DimName,
451{
452    type Output = VecStorage<T, R2, Dyn>;
453
454    fn reshape_generic(self, nrows: R2, ncols: Dyn) -> Self::Output {
455        assert_eq!(nrows.value() * ncols.value(), self.data.len());
456        VecStorage {
457            data: self.data,
458            nrows,
459            ncols,
460        }
461    }
462}
463
464impl<T, R: Dim> Extend<T> for VecStorage<T, R, Dyn> {
465    /// Extends the number of columns of the `VecStorage` with elements
466    /// from the given iterator.
467    ///
468    /// # Panics
469    /// This function panics if the number of elements yielded by the
470    /// given iterator is not a multiple of the number of rows of the
471    /// `VecStorage`.
472    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
473        self.data.extend(iter);
474        self.ncols = Dyn(self.data.len() / self.nrows.value());
475        assert!(
476            self.data.len() % self.nrows.value() == 0,
477            "The number of elements produced by the given iterator was not a multiple of the number of rows."
478        );
479    }
480}
481
482impl<'a, T: 'a + Copy, R: Dim> Extend<&'a T> for VecStorage<T, R, Dyn> {
483    /// Extends the number of columns of the `VecStorage` with elements
484    /// from the given iterator.
485    ///
486    /// # Panics
487    /// This function panics if the number of elements yielded by the
488    /// given iterator is not a multiple of the number of rows of the
489    /// `VecStorage`.
490    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
491        self.extend(iter.into_iter().copied())
492    }
493}
494
495impl<T, R, RV, SV> Extend<Vector<T, RV, SV>> for VecStorage<T, R, Dyn>
496where
497    T: Scalar,
498    R: Dim,
499    RV: Dim,
500    SV: RawStorage<T, RV>,
501    ShapeConstraint: SameNumberOfRows<R, RV>,
502{
503    /// Extends the number of columns of the `VecStorage` with vectors
504    /// from the given iterator.
505    ///
506    /// # Panics
507    /// This function panics if the number of rows of each `Vector`
508    /// yielded by the iterator is not equal to the number of rows
509    /// of this `VecStorage`.
510    fn extend<I: IntoIterator<Item = Vector<T, RV, SV>>>(&mut self, iter: I) {
511        let nrows = self.nrows.value();
512        let iter = iter.into_iter();
513        let (lower, _upper) = iter.size_hint();
514        self.data.reserve(nrows * lower);
515        for vector in iter {
516            assert_eq!(nrows, vector.shape().0);
517            self.data.extend(vector.iter().cloned());
518        }
519        self.ncols = Dyn(self.data.len() / nrows);
520    }
521}
522
523impl<T> Extend<T> for VecStorage<T, Dyn, U1> {
524    /// Extends the number of rows of the `VecStorage` with elements
525    /// from the given iterator.
526    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
527        self.data.extend(iter);
528        self.nrows = Dyn(self.data.len());
529    }
530}