generic_array_storage/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#![doc = include_str!("../README.md")]
#![no_std] // <-- yeah, in case you wondered - there you are, feel free to use it

use core::fmt::Debug;

use generic_array::{functional::FunctionalSequence, ArrayLength, GenericArray, IntoArrayLength};
use nalgebra::{
    allocator::Allocator, DefaultAllocator, IsContiguous, Matrix, OMatrix, Owned, RawStorage,
    RawStorageMut, Scalar, Storage,
};

mod conv;
pub use conv::Conv;

/// A stack-allocated storage, of [`typenum`]-backed col-major two dimensional array
///
/// This struct is transparent and completely public, since it has nothing to hide! Note that [`GenericArray`] is transparent itself, so this struct effectively has the same layout as a two-dimensional array of the corresponding size.
#[repr(transparent)]
pub struct GenericArrayStorage<T, R: Conv, C: Conv>(
    pub GenericArray<GenericArray<T, R::TNum>, C::TNum>,
);

impl<T: Debug, R: Conv, C: Conv> Debug for GenericArrayStorage<T, R, C> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        <GenericArray<GenericArray<T, R::TNum>, C::TNum> as Debug>::fmt(&self.0, f)
    }
}

impl<T, R: Conv, C: Conv> Clone for GenericArrayStorage<T, R, C>
where
    T: Clone,
    GenericArray<GenericArray<T, R::TNum>, C::TNum>: Clone,
{
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T, R: Conv, C: Conv> Copy for GenericArrayStorage<T, R, C>
where
    T: Copy,
    <R::TNum as ArrayLength>::ArrayType<T>: Copy,
    <C::TNum as ArrayLength>::ArrayType<GenericArray<T, R::TNum>>: Copy,
{
}

impl<T, R: Conv, C: Conv> AsRef<[T]> for GenericArrayStorage<T, R, C> {
    fn as_ref(&self) -> &[T] {
        GenericArray::slice_from_chunks(&self.0)
    }
}

impl<T, R: Conv, C: Conv> AsMut<[T]> for GenericArrayStorage<T, R, C> {
    fn as_mut(&mut self) -> &mut [T] {
        GenericArray::slice_from_chunks_mut(&mut self.0)
    }
}

#[allow(unsafe_code, reason = "nalgebra storage traits are unsafe")]
unsafe impl<T, R: Conv, C: Conv> RawStorage<T, R::Nalg, C::Nalg> for GenericArrayStorage<T, R, C> {
    type RStride = nalgebra::U1;

    type CStride = R::Nalg;

    fn ptr(&self) -> *const T {
        if self.0.is_empty() {
            core::ptr::NonNull::<T>::dangling().as_ptr()
        } else {
            self.0.as_ptr().cast()
        }
    }

    fn shape(&self) -> (R::Nalg, C::Nalg) {
        (R::new_nalg(), C::new_nalg())
    }

    fn strides(&self) -> (Self::RStride, Self::CStride) {
        (nalgebra::U1, R::new_nalg())
    }

    fn is_contiguous(&self) -> bool {
        true
    }

    unsafe fn as_slice_unchecked(&self) -> &[T] {
        self.as_ref()
    }
}

#[allow(unsafe_code, reason = "nalgebra storage traits are unsafe")]
unsafe impl<T, R: Conv, C: Conv> RawStorageMut<T, R::Nalg, C::Nalg>
    for GenericArrayStorage<T, R, C>
{
    fn ptr_mut(&mut self) -> *mut T {
        if self.0.is_empty() {
            core::ptr::NonNull::<T>::dangling().as_ptr()
        } else {
            self.0.as_mut_ptr().cast()
        }
    }

    unsafe fn as_mut_slice_unchecked(&mut self) -> &mut [T] {
        // SAFETY: see struct's doc - it's layout is guaranteed to be like that of a two-dimensional array
        self.as_mut()
    }
}

#[allow(unsafe_code, reason = "nalgebra storage traits are unsafe")]
unsafe impl<T: Scalar, R: Conv, C: Conv> Storage<T, R::Nalg, C::Nalg>
    for GenericArrayStorage<T, R, C>
where
    nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<R::Nalg, C::Nalg>,
{
    fn into_owned(self) -> Owned<T, R::Nalg, C::Nalg>
    where
        nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<R::Nalg, C::Nalg>,
    {
        nalgebra::DefaultAllocator::allocate_from_iterator(
            R::new_nalg(),
            C::new_nalg(),
            self.0.into_iter().flatten(),
        )
    }

    fn clone_owned(&self) -> Owned<T, R::Nalg, C::Nalg>
    where
        nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<R::Nalg, C::Nalg>,
    {
        self.clone().into_owned()
    }

    fn forget_elements(self) {
        core::mem::forget(self);
    }
}

#[allow(unsafe_code, reason = "nalgebra storage traits are unsafe")]
unsafe impl<R: Conv, C: Conv, T: nalgebra::Scalar> IsContiguous for GenericArrayStorage<T, R, C> {}

/// Alias to [`nalgebra::Matrix`], completely "hiding" `const usize`s away. See crate's documentation on how this is possible.
pub type GenericMatrix<T, R, C> =
    nalgebra::Matrix<T, <R as Conv>::Nalg, <C as Conv>::Nalg, GenericArrayStorage<T, R, C>>;

type TNum<const N: usize> = typenum::Const<N>;

impl<T, const AR: usize, const AC: usize, R, C> From<[[T; AR]; AC]> for GenericArrayStorage<T, R, C>
where
    TNum<AR>: IntoArrayLength,
    TNum<AC>: IntoArrayLength,
    R: Conv<TNum = <TNum<AR> as IntoArrayLength>::ArrayLength>,
    C: Conv<TNum = <TNum<AC> as IntoArrayLength>::ArrayLength>,
{
    fn from(value: [[T; AR]; AC]) -> Self {
        let tnum_array: GenericArray<
            GenericArray<T, <TNum<AR> as IntoArrayLength>::ArrayLength>,
            <TNum<AC> as IntoArrayLength>::ArrayLength,
        > = GenericArray::from_array(value.map(GenericArray::from_array));
        Self(tnum_array)
    }
}

impl<T, const AR: usize, const AC: usize, R, C> From<GenericArrayStorage<T, R, C>> for [[T; AR]; AC]
where
    TNum<AR>: IntoArrayLength,
    TNum<AC>: IntoArrayLength,
    R: Conv<TNum = <TNum<AR> as IntoArrayLength>::ArrayLength>,
    C: Conv<TNum = <TNum<AC> as IntoArrayLength>::ArrayLength>,
{
    fn from(GenericArrayStorage(data): GenericArrayStorage<T, R, C>) -> Self {
        data.map(GenericArray::into_array).into_array()
    }
}

/// [`GenericMatrix`]-conversion trait intended for core arrays and regular [`nalgebra`] matrices
pub trait GenericMatrixFromExt<R: Conv, C: Conv> {
    /// Type of the elements.
    ///
    /// This an associated type for the simple reason that is can be such.
    type T;

    /// Creates [`GenericMatrix`] from core Rust array.
    fn into_generic_matrix(self) -> GenericMatrix<Self::T, R, C>;
}

impl<T, const AR: usize, const AC: usize, R, C> GenericMatrixFromExt<R, C> for [[T; AR]; AC]
where
    TNum<AR>: IntoArrayLength,
    TNum<AC>: IntoArrayLength,
    R: Conv<TNum = <TNum<AR> as IntoArrayLength>::ArrayLength>,
    C: Conv<TNum = <TNum<AC> as IntoArrayLength>::ArrayLength>,
{
    type T = T;

    fn into_generic_matrix(self) -> GenericMatrix<Self::T, R, C> {
        GenericMatrix::from_data(self.into())
    }
}

impl<T, R, C> GenericMatrixFromExt<R, C> for OMatrix<T, R::Nalg, C::Nalg>
where
    T: Scalar,
    R: Conv,
    C: Conv,
    DefaultAllocator: Allocator<R::Nalg, C::Nalg>,
{
    type T = T;

    fn into_generic_matrix(self) -> GenericMatrix<Self::T, R, C> {
        let (rows, rest) = GenericArray::<_, R::TNum>::chunks_from_slice(self.as_slice());
        debug_assert!(rest.is_empty(), "Should be no leftover");
        let arr = GenericArray::<_, C::TNum>::from_slice(rows);
        let storage = GenericArrayStorage(arr.clone());
        GenericMatrix::from_data(storage)
    }
}

/// Conv trait defining [`GenericMatrix`] conversions.
pub trait GenericMatrixExt {
    /// Type of the elements.
    ///
    /// This an associated type for the simple reason that is can be such.
    type T: Scalar;

    /// Type defining rows count
    type R: Conv;

    /// Type defining column count
    type C: Conv;

    /// Converts [`GenericMatrix`] into regular [`nalgebra`] matrix, backed by core array (it's opaque about that though)
    fn into_regular_matrix(
        self,
    ) -> OMatrix<Self::T, <Self::R as Conv>::Nalg, <Self::C as Conv>::Nalg>
    where
        nalgebra::DefaultAllocator:
            nalgebra::allocator::Allocator<<Self::R as Conv>::Nalg, <Self::C as Conv>::Nalg>;

    /// Changes type of [`GenericMatrix`] to a different row and column count descriptors.
    fn conv<
        NewR: Conv<TNum = <Self::R as Conv>::TNum>,
        NewC: Conv<TNum = <Self::C as Conv>::TNum>,
    >(
        self,
    ) -> GenericMatrix<Self::T, NewR, NewC>;
}

impl<T: Scalar, R: Conv, C: Conv> GenericMatrixExt for GenericMatrix<T, R, C> {
    type T = T;

    type R = R;

    type C = C;

    fn into_regular_matrix(
        self,
    ) -> OMatrix<Self::T, <Self::R as Conv>::Nalg, <Self::C as Conv>::Nalg>
    where
        DefaultAllocator: Allocator<<Self::R as Conv>::Nalg, <Self::C as Conv>::Nalg>,
    {
        Matrix::from_data(DefaultAllocator::allocate_from_iterator(
            <Self::R as Conv>::new_nalg(),
            <Self::C as Conv>::new_nalg(),
            self.data.0.into_iter().flatten(),
        ))
    }

    fn conv<
        NewR: Conv<TNum = <Self::R as Conv>::TNum>,
        NewC: Conv<TNum = <Self::C as Conv>::TNum>,
    >(
        self,
    ) -> GenericMatrix<Self::T, NewR, NewC> {
        GenericMatrix::from_data(GenericArrayStorage(self.data.0))
    }
}

#[cfg(test)]
mod tests;