mdarray 0.7.2

Multidimensional array for Rust
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
use core::borrow::{Borrow, BorrowMut};
use core::fmt::{self, Debug, Formatter};
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut, Index, IndexMut};
use core::slice;

use crate::dim::{Const, Dim, Dyn};
use crate::expr::{Apply, Expression, IntoExpression, Iter, Map, Zip};
use crate::index::{self, Axis, DimIndex, Permutation, Resize, SliceIndex, Split, ViewIndex};
use crate::layout::{Dense, Layout, Strided};
use crate::mapping::{DenseMapping, Mapping, StridedMapping};
use crate::raw_slice::RawSlice;
use crate::shape::{DynRank, IntoShape, Rank, Shape};
use crate::slice::Slice;

/// Multidimensional array view.
pub struct View<'a, T, S: Shape = DynRank, L: Layout = Dense> {
    slice: RawSlice<T, S, L>,
    phantom: PhantomData<&'a T>,
}

/// Mutable multidimensional array view.
pub struct ViewMut<'a, T, S: Shape = DynRank, L: Layout = Dense> {
    slice: RawSlice<T, S, L>,
    phantom: PhantomData<&'a mut T>,
}

/// Multidimensional array view with dynamically-sized dimensions.
pub type DView<'a, T, const N: usize, L = Dense> = View<'a, T, Rank<N>, L>;

/// Mutable multidimensional array view with dynamically-sized dimensions.
pub type DViewMut<'a, T, const N: usize, L = Dense> = ViewMut<'a, T, Rank<N>, L>;

macro_rules! impl_view {
    ($name:tt, $as_ptr:tt, $from_raw_parts:tt, $raw_mut:tt, {$($mut:tt)?}, $repeatable:tt) => {
        impl<'a, T, S: Shape, L: Layout> $name<'a, T, S, L> {
            /// Converts the array view into a new array view indexing the first dimension.
            ///
            /// # Panics
            ///
            /// Panics if the index is out of bounds, or if the rank is not at least 1.
            #[inline]
            pub fn into_at(
                self,
                index: usize,
            ) -> $name<'a, T, S::Tail, L> {
                self.into_axis_at(Const::<0>, index)
            }

            /// Converts the array view into a new array view indexing the specified dimension.
            ///
            /// If the dimension to be indexed is know at compile time, the resulting array shape
            /// will maintain constant-sized dimensions. Furthermore, if it is the first dimension
            /// the resulting array view has the same layout as the input.
            ///
            /// # Panics
            ///
            /// Panics if the dimension or the index is out of bounds.
            #[inline]
            pub fn into_axis_at<A: Axis>(
                $($mut)? self,
                axis: A,
                index: usize,
            ) -> $name<'a, T, A::Remove<S>, Split<A, S, L>> {
                unsafe { Self::axis_at(self.$as_ptr(), self.mapping(), axis, index) }
            }

            /// Converts the array view into a new array view for the specified column.
            ///
            /// # Panics
            ///
            /// Panics if the rank is not equal to 2, or if the index is out of bounds.
            #[inline]
            pub fn into_col(self, index: usize) -> $name<'a, T, (S::Head,), Strided> {
                let shape = self.shape().with_dims(<(_, <S::Tail as Shape>::Head)>::from_dims);

                self.into_shape(shape).into_view(.., index)
            }

            /// Converts the array view into a new array view for the given diagonal,
            /// where `index` > 0 is above and `index` < 0 is below the main diagonal.
            ///
            /// # Panics
            ///
            /// Panics if the rank is not equal to 2, or if the absolute index is larger
            /// than the number of columns or rows.
            #[inline]
            pub fn into_diag($($mut)? self, index: isize) -> $name<'a, T, (Dyn,), Strided> {
                assert!(self.rank() == 2, "invalid rank");

                let (offset, len) = if index >= 0 {
                    assert!(index as usize <= self.dim(1), "invalid diagonal");

                    (index * self.stride(1), self.dim(0).min(self.dim(1) - (index as usize)))
                } else {
                    assert!(-index as usize <= self.dim(0), "invalid diagonal");

                    (-index * self.stride(0), self.dim(1).min(self.dim(0) - (-index as usize)))
                };

                let count = if len > 0 { offset } else { 0 }; // Offset pointer if non-empty.
                let mapping = StridedMapping::new((len,), &[self.stride(0) + self.stride(1)]);

                unsafe { $name::new_unchecked(self.$as_ptr().offset(count), mapping) }
            }

            /// Converts the array view into an array view with dynamic rank.
            #[inline]
            pub fn into_dyn(self) -> $name<'a, T, DynRank, L> {
                self.into_mapping()
            }

            /// Converts the array view into a one-dimensional array view.
            ///
            /// # Panics
            ///
            /// Panics if the array layout is not uniformly strided.
            #[inline]
            pub fn into_flat(self) -> $name<'a, T, (Dyn,), L> {
                let len = self.len();

                self.into_shape([len])
            }

            /// Converts the array view into a remapped array view.
            ///
            /// # Panics
            ///
            /// Panics if the shape is not matching static rank or constant-sized dimensions,
            /// or if the memory layout is not compatible with the new array layout.
            #[inline]
            pub fn into_mapping<R: Shape, K: Layout>($($mut)? self) -> $name<'a, T, R, K> {
                let mapping = Mapping::remap(self.mapping());

                unsafe { $name::new_unchecked(self.$as_ptr(), mapping) }
            }

            /// Converts the array view into a new array view with the dimensions permuted.
            ///
            /// If the permutation is an identity permutation and known at compile time, the
            /// resulting array view has the same layout as the input. For example, permuting
            /// with `(Const::<0>, Const::<1>)` will maintain the layout while permuting with
            /// `[0, 1]` gives strided layout.
            ///
            /// # Panics
            ///
            /// Panics if the permutation is not valid.
            #[inline]
            pub fn into_permuted<I: IntoShape<IntoShape: Permutation>>(
                $($mut)? self,
                perm: I,
            ) -> $name<
                'a,
                T,
                <I::IntoShape as Permutation>::Shape<S>,
                <I::IntoShape as Permutation>::Layout<L>,
            > {
                let mapping = perm.into_dims(|dims| Mapping::permute(self.mapping(), dims));

                unsafe { $name::new_unchecked(self.$as_ptr(), mapping) }
            }

            /// Converts the array view into a reordered array view.
            ///
            /// This method is deprecated, use `into_transposed` instead.
            #[deprecated]
            #[inline]
            pub fn into_reordered(
                $($mut)? self
            ) -> $name<'a, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
                let mapping = Mapping::transpose(self.mapping());

                unsafe { $name::new_unchecked(self.$as_ptr(), mapping) }
            }

            /// Converts the array view into a new array view for the specified row.
            ///
            /// # Panics
            ///
            /// Panics if the rank is not equal to 2, or if the index is out of bounds.
            #[inline]
            pub fn into_row(self, index: usize) -> $name<'a, T, (<S::Tail as Shape>::Head,), L> {
                let shape = self.shape().with_dims(<(S::Head, _)>::from_dims);

                self.into_shape(shape).into_view(index, ..)
            }

            /// Converts the array view into a reshaped array view.
            ///
            /// At most one dimension can have dynamic size `usize::MAX`, and is then inferred
            /// from the other dimensions and the array length.
            ///
            /// # Examples
            ///
            /// ```
            /// use mdarray::view;
            ///
            /// let v = view![[1, 2, 3], [4, 5, 6]];
            ///
            /// assert_eq!(v.into_shape([!0, 2]), view![[1, 2], [3, 4], [5, 6]]);
            /// ```
            ///
            /// # Panics
            ///
            /// Panics if the array length is changed, or if the memory layout is not compatible.
            #[inline]
            pub fn into_shape<I: IntoShape>(
                $($mut)? self,
                shape: I
            ) -> $name<'a, T, I::IntoShape, L> {
                let mapping = self.mapping().reshape(shape.into_shape());

                unsafe { $name::new_unchecked(self.$as_ptr(), mapping) }
            }

            /// Divides the array view into two at an index along the first dimension.
            ///
            /// # Panics
            ///
            /// Panics if the split point is larger than the number of elements in that dimension,
            /// or if the rank is not at least 1.
            #[inline]
            pub fn into_split_at(
                self,
                mid: usize,
            ) -> ($name<'a, T, Resize<Const<0>, S>, L>, $name<'a, T, Resize<Const<0>, S>, L>) {
                self.into_split_axis_at(Const::<0>, mid)
            }

            /// Divides the array view into two at an index along the specified dimension.
            ///
            /// If the dimension to be divided is know at compile time, the resulting array
            /// shape will maintain constant-sized dimensions. Furthermore, if it is the first
            /// dimension the resulting array views have the same layout as the input.
            ///
            /// # Panics
            ///
            /// Panics if the split point is larger than the number of elements in that dimension,
            /// or if the dimension is out of bounds.
            #[inline]
            pub fn into_split_axis_at<A: Axis>(
                $($mut)? self,
                axis: A,
                mid: usize,
            ) -> (
                $name<'a, T, Resize<A, S>, Split<A, S, L>>,
                $name<'a, T, Resize<A, S>, Split<A, S, L>>,
            ) {
                unsafe { Self::split_axis_at(self.$as_ptr(), self.mapping(), axis, mid) }
            }

            /// Converts the array view into a transposed array view, where the dimensions
            /// are reversed.
            #[inline]
            pub fn into_transposed(
                $($mut)? self
            ) -> $name<'a, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
                let mapping = Mapping::transpose(self.mapping());

                unsafe { $name::new_unchecked(self.$as_ptr(), mapping) }
            }

            /// Creates an array view from a raw pointer and layout.
            ///
            /// # Safety
            ///
            /// The pointer must be non-null and a valid array view for the given layout.
            #[inline]
            pub unsafe fn new_unchecked(ptr: *$raw_mut T, mapping: L::Mapping<S>) -> Self {
                let slice = unsafe { RawSlice::new_unchecked(ptr as *mut T, mapping) };

                Self { slice, phantom: PhantomData }
            }

            #[inline]
            pub(crate) unsafe fn axis_at<A: Axis>(
                ptr: *$raw_mut T,
                mapping: &L::Mapping<S>,
                axis: A,
                index: usize,
            ) -> $name<'a, T, A::Remove<S>, Split<A, S, L>> {
                let size = mapping.dim(axis.index(mapping.rank()));

                if index >= size {
                    index::panic_bounds_check(index, size);
                }

                let new_mapping = axis.remove(mapping);

                // Calculate offset for the new view if non-empty.
                let offset = mapping.stride(axis.index(mapping.rank())) * index as isize;
                let count = if new_mapping.is_empty() { 0 } else { offset };

                unsafe { $name::new_unchecked(ptr.offset(count), new_mapping) }
            }

            #[inline]
            pub(crate) unsafe fn split_axis_at<A: Axis>(
                ptr: *$raw_mut T,
                mapping: &L::Mapping<S>,
                axis: A,
                mid: usize,
            ) -> (
                $name<'a, T, Resize<A, S>, Split<A, S, L>>,
                $name<'a, T, Resize<A, S>, Split<A, S, L>>,
            ) {
                let index = axis.index(mapping.rank());
                let size = mapping.dim(index);

                if mid > size {
                    index::panic_bounds_check(mid, size);
                }

                let first_mapping = axis.resize(mapping, mid);
                let second_mapping = axis.resize(mapping, size - mid);

                // Calculate offset for the second view if non-empty.
                let offset = mapping.stride(index) * mid as isize;
                let count = if second_mapping.is_empty() { 0 } else { offset };

                unsafe {
                    let first = $name::new_unchecked(ptr, first_mapping);
                    let second = $name::new_unchecked(ptr.offset(count), second_mapping);

                    (first, second)
                }
            }
        }

        impl<'a, T, U, S: Shape, L: Layout> Apply<U> for &'a $name<'_, T, S, L> {
            type Output<F: FnMut(&'a T) -> U> = Map<Self::IntoExpr, F>;
            type ZippedWith<I: IntoExpression, F: FnMut((&'a T, I::Item)) -> U> =
                Map<Zip<Self::IntoExpr, I::IntoExpr>, F>;

            #[inline]
            fn apply<F: FnMut(&'a T) -> U>(self, f: F) -> Self::Output<F> {
                self.expr().map(f)
            }

            #[inline]
            fn zip_with<I: IntoExpression, F>(self, expr: I, f: F) -> Self::ZippedWith<I, F>
            where
                F: FnMut((&'a T, I::Item)) -> U,
            {
                self.expr().zip(expr).map(f)
            }
        }

        impl<T, U: ?Sized, S: Shape, L: Layout> AsRef<U> for $name<'_, T, S, L>
        where
            Slice<T, S, L>: AsRef<U>,
        {
            #[inline]
            fn as_ref(&self) -> &U {
                (**self).as_ref()
            }
        }

        impl<T, S: Shape, L: Layout> Borrow<Slice<T, S, L>> for $name<'_, T, S, L> {
            #[inline]
            fn borrow(&self) -> &Slice<T, S, L> {
                self
            }
        }

        impl<T: Debug, S: Shape, L: Layout> Debug for $name<'_, T, S, L> {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                (**self).fmt(f)
            }
        }

        impl<T, S: Shape, L: Layout> Deref for $name<'_, T, S, L> {
            type Target = Slice<T, S, L>;

            #[inline]
            fn deref(&self) -> &Self::Target {
                self.slice.as_slice()
            }
        }

        impl<'a, T, S: Shape, L: Layout> Expression for $name<'a, T, S, L> {
            type Shape = S;

            const IS_REPEATABLE: bool = $repeatable;

            #[inline]
            fn shape(&self) -> &S {
                (**self).shape()
            }

            #[inline]
            unsafe fn get_unchecked(&mut self, index: usize) -> &'a $($mut)? T {
                let count = self.slice.mapping().inner_stride() * index as isize;

                unsafe { &$($mut)? *self.slice.$as_ptr().offset(count) }
            }

            #[inline]
            fn inner_rank(&self) -> usize {
                if L::IS_DENSE {
                    // For static rank 0, the inner stride is 0 so we allow inner rank >0.
                    if S::RANK == Some(0) { usize::MAX } else { self.rank() }
                } else {
                    // For rank 0, the inner stride is always 0 so we can allow inner rank >0.
                    if self.rank() > 0 { 1 } else { usize::MAX }
                }
            }

            #[inline]
            unsafe fn reset_dim(&mut self, index: usize, count: usize) {
                let count = -self.stride(index) * count as isize;
                let ptr = self.slice.as_mut_ptr();

                unsafe {
                    self.slice.set_ptr(ptr.offset(count));
                }
            }

            #[inline]
            unsafe fn step_dim(&mut self, index: usize) {
                let ptr = self.slice.as_mut_ptr();

                unsafe {
                    self.slice.set_ptr(ptr.offset(self.stride(index)));
                }
            }
        }

        impl<'a, T, S: Shape, L: Layout, I> From<&'a $($mut)? I> for $name<'a, T, S, L>
        where
            &'a $($mut)? I: IntoExpression<IntoExpr = $name<'a, T, S, L>>
        {
            #[inline]
            fn from(value: &'a $($mut)? I) -> Self {
                value.into_expr()
            }
        }

        impl<'a, T> From<&'a $($mut)? [T]> for $name<'a, T, (Dyn,)> {
            #[inline]
            fn from(value: &'a $($mut)? [T]) -> Self {
                let mapping = DenseMapping::new((value.len(),));

                unsafe { Self::new_unchecked(value.$as_ptr(), mapping) }
            }
        }

        impl<'a, T, D: Dim> From<$name<'a, T, (D,)>> for &'a $($mut)? [T] {
            #[inline]
            fn from($($mut)? value: $name<T, (D,)>) -> Self {
                unsafe { slice::$from_raw_parts(value.$as_ptr(), value.len()) }
            }
        }

        impl<T: Hash, S: Shape, L: Layout> Hash for $name<'_, T, S, L> {
            #[inline]
            fn hash<H: Hasher>(&self, state: &mut H) {
                (**self).hash(state)
            }
        }

        impl<T, S: Shape, L: Layout, I: SliceIndex<T, S, L>> Index<I> for $name<'_, T, S, L> {
            type Output = I::Output;

            #[inline]
            fn index(&self, index: I) -> &I::Output {
                index.index(self)
            }
        }

        impl<'a, T, S: Shape, L: Layout> IntoExpression for &'a $name<'_, T, S, L> {
            type Shape = S;
            type IntoExpr = View<'a, T, S, L>;

            #[inline]
            fn into_expr(self) -> Self::IntoExpr {
                self.expr()
            }
        }

        impl<'a, T, S: Shape, L: Layout> IntoIterator for &'a $name<'_, T, S, L> {
            type Item = &'a T;
            type IntoIter = Iter<View<'a, T, S, L>>;

            #[inline]
            fn into_iter(self) -> Self::IntoIter {
                self.expr().into_iter()
            }
        }

        impl<'a, T, S: Shape, L: Layout> IntoIterator for $name<'a, T, S, L> {
            type Item = &'a $($mut)? T;
            type IntoIter = Iter<Self>;

            #[inline]
            fn into_iter(self) -> Iter<Self> {
                Iter::new(self)
            }
        }
    };
}

impl_view!(View, as_ptr, from_raw_parts, const, {}, true);
impl_view!(ViewMut, as_mut_ptr, from_raw_parts_mut, mut, {mut}, false);

macro_rules! impl_into_view {
    ($n:tt, ($($xyz:tt),+), ($($abc:tt),+), ($($idx:tt),+)) => {
        impl<'a, T, $($xyz: Dim,)+ L: Layout> View<'a, T, ($($xyz,)+), L> {
            /// Converts the array view into a new array view for the specified subarray.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn into_view<$($abc: DimIndex),+>(
                self,
                $($idx: $abc),+
            ) -> View<
                'a,
                T,
                <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>,
                <($($abc,)+) as ViewIndex>::Layout<L>,
            > {
                let (offset, mapping) = ($($idx,)+).view_index(self.mapping());

                // If the view is empty, we must not offset the pointer.
                let count = if mapping.is_empty() { 0 } else { offset };

                unsafe { View::new_unchecked(self.as_ptr().offset(count), mapping) }
            }
        }

        impl<'a, T, $($xyz: Dim,)+ L: Layout> ViewMut<'a, T, ($($xyz,)+), L> {
            /// Converts the array view into a new array view for the specified subarray.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn into_view<$($abc: DimIndex),+>(
                mut self,
                $($idx: $abc),+
            ) -> ViewMut<
                'a,
                T,
                <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>,
                <($($abc,)+) as ViewIndex>::Layout<L>,
            > {
                let (offset, mapping) = ($($idx,)+).view_index(self.mapping());

                // If the view is empty, we must not offset the pointer.
                let count = if mapping.is_empty() { 0 } else { offset };

                unsafe { ViewMut::new_unchecked(self.as_mut_ptr().offset(count), mapping) }
            }
        }
    };
}

impl_into_view!(1, (X), (A), (a));
impl_into_view!(2, (X, Y), (A, B), (a, b));
impl_into_view!(3, (X, Y, Z), (A, B, C), (a, b, c));
impl_into_view!(4, (X, Y, Z, W), (A, B, C, D), (a, b, c, d));
impl_into_view!(5, (X, Y, Z, W, U), (A, B, C, D, E), (a, b, c, d, e));
impl_into_view!(6, (X, Y, Z, W, U, V), (A, B, C, D, E, F), (a, b, c, d, e, f));

impl<'a, T, U, S: Shape, L: Layout> Apply<U> for &'a mut ViewMut<'_, T, S, L> {
    type Output<F: FnMut(&'a mut T) -> U> = Map<Self::IntoExpr, F>;
    type ZippedWith<I: IntoExpression, F: FnMut((&'a mut T, I::Item)) -> U> =
        Map<Zip<Self::IntoExpr, I::IntoExpr>, F>;

    #[inline]
    fn apply<F: FnMut(&'a mut T) -> U>(self, f: F) -> Self::Output<F> {
        self.expr_mut().map(f)
    }

    #[inline]
    fn zip_with<I: IntoExpression, F>(self, expr: I, f: F) -> Self::ZippedWith<I, F>
    where
        F: FnMut((&'a mut T, I::Item)) -> U,
    {
        self.expr_mut().zip(expr).map(f)
    }
}

impl<T, U: ?Sized, S: Shape, L: Layout> AsMut<U> for ViewMut<'_, T, S, L>
where
    Slice<T, S, L>: AsMut<U>,
{
    #[inline]
    fn as_mut(&mut self) -> &mut U {
        (**self).as_mut()
    }
}

impl<T, S: Shape, L: Layout> BorrowMut<Slice<T, S, L>> for ViewMut<'_, T, S, L> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut Slice<T, S, L> {
        self
    }
}

impl<T, S: Shape, L: Layout> Clone for View<'_, T, S, L> {
    #[inline]
    fn clone(&self) -> Self {
        Self { slice: self.slice.clone(), phantom: PhantomData }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        self.slice.clone_from(&source.slice);
    }
}

impl<T, S: Shape, L: Layout<Mapping<S>: Copy>> Copy for View<'_, T, S, L> {}

impl<T, S: Shape, L: Layout> DerefMut for ViewMut<'_, T, S, L> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.slice.as_mut_slice()
    }
}

macro_rules! impl_from_array_ref {
    (($($xyz:tt),+), ($($abc:tt),+), $array:tt) => {
        impl<'a, T $(,$xyz: Dim + From<Const<$abc>>)+ $(,const $abc: usize)+> From<&'a $array>
            for View<'a, T, ($($xyz,)+)>
        {
            #[inline]
            fn from(value: &'a $array) -> Self {
                let mapping = DenseMapping::new(($($xyz::from(Const::<$abc>),)+));

                _ = mapping.shape().checked_len().expect("invalid length");

                unsafe { Self::new_unchecked(value.as_ptr().cast(), mapping) }
            }
        }

        impl<'a, T $(,$xyz: Dim + From<Const<$abc>>)+ $(,const $abc: usize)+> From<&'a mut $array>
            for ViewMut<'a, T, ($($xyz,)+)>
        {
            #[inline]
            fn from(value: &'a mut $array) -> Self {
                let mapping = DenseMapping::new(($($xyz::from(Const::<$abc>),)+));

                _ = mapping.shape().checked_len().expect("invalid length");

                unsafe { Self::new_unchecked(value.as_mut_ptr().cast(), mapping) }
            }
        }
    };
}

impl_from_array_ref!((X), (A), [T; A]);
impl_from_array_ref!((X, Y), (A, B), [[T; B]; A]);
impl_from_array_ref!((X, Y, Z), (A, B, C), [[[T; C]; B]; A]);
impl_from_array_ref!((X, Y, Z, W), (A, B, C, D), [[[[T; D]; C]; B]; A]);
impl_from_array_ref!((X, Y, Z, W, U), (A, B, C, D, E), [[[[[T; E]; D]; C]; B]; A]);
impl_from_array_ref!((X, Y, Z, W, U, V), (A, B, C, D, E, F), [[[[[[T; F]; E]; D]; C]; B]; A]);

impl<T, S: Shape, L: Layout, I: SliceIndex<T, S, L>> IndexMut<I> for ViewMut<'_, T, S, L> {
    #[inline]
    fn index_mut(&mut self, index: I) -> &mut I::Output {
        index.index_mut(self)
    }
}

impl<'a, T, S: Shape, L: Layout> IntoExpression for &'a mut ViewMut<'_, T, S, L> {
    type Shape = S;
    type IntoExpr = ViewMut<'a, T, S, L>;

    #[inline]
    fn into_expr(self) -> Self::IntoExpr {
        self.expr_mut()
    }
}

impl<'a, T, S: Shape, L: Layout> IntoIterator for &'a mut ViewMut<'_, T, S, L> {
    type Item = &'a mut T;
    type IntoIter = Iter<ViewMut<'a, T, S, L>>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.expr_mut().into_iter()
    }
}

unsafe impl<T: Sync, S: Shape, L: Layout> Send for View<'_, T, S, L> {}
unsafe impl<T: Sync, S: Shape, L: Layout> Sync for View<'_, T, S, L> {}

unsafe impl<T: Send, S: Shape, L: Layout> Send for ViewMut<'_, T, S, L> {}
unsafe impl<T: Sync, S: Shape, L: Layout> Sync for ViewMut<'_, T, S, L> {}

macro_rules! impl_try_from_array_ref {
    (($($xyz:tt),+), ($($abc:tt),+), $array:tt) => {
        impl<'a, T $(,$xyz: Dim)+ $(,const $abc: usize)+> TryFrom<View<'a, T, ($($xyz,)+)>>
            for &'a $array
        {
            type Error = View<'a, T, ($($xyz,)+)>;

            #[inline]
            fn try_from(value: View<'a, T, ($($xyz,)+)>) -> Result<Self, Self::Error> {
                if value.shape().with_dims(|dims| dims == &[$($abc),+]) {
                    Ok(unsafe { &*value.as_ptr().cast() })
                } else {
                    Err(value)
                }
            }
        }

        impl<'a, T $(,$xyz: Dim)+ $(,const $abc: usize)+> TryFrom<ViewMut<'a, T, ($($xyz,)+)>>
            for &'a mut $array
        {
            type Error = ViewMut<'a, T, ($($xyz,)+)>;

            #[inline]
            fn try_from(mut value: ViewMut<'a, T, ($($xyz,)+)>) -> Result<Self, Self::Error> {
                if value.shape().with_dims(|dims| dims == &[$($abc),+]) {
                    Ok(unsafe { &mut *value.as_mut_ptr().cast() })
                } else {
                    Err(value)
                }
            }
        }
    };
}

impl_try_from_array_ref!((X), (A), [T; A]);
impl_try_from_array_ref!((X, Y), (A, B), [[T; B]; A]);
impl_try_from_array_ref!((X, Y, Z), (A, B, C), [[[T; C]; B]; A]);
impl_try_from_array_ref!((X, Y, Z, W), (A, B, C, D), [[[[T; D]; C]; B]; A]);
impl_try_from_array_ref!((X, Y, Z, W, U), (A, B, C, D, E), [[[[[T; E]; D]; C]; B]; A]);
impl_try_from_array_ref!((X, Y, Z, W, U, V), (A, B, C, D, E, F), [[[[[[T; F]; E]; D]; C]; B]; A]);