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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
#[cfg(feature = "nightly")]
use alloc::alloc::Allocator;
#[cfg(not(feature = "std"))]
use alloc::borrow::ToOwned;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use core::fmt::{Debug, Formatter, Result};
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::mem;
use core::ops::{Index, IndexMut};
use core::ptr::{self, NonNull};

use crate::array::Array;
use crate::dim::{Const, Dim, Dyn};
use crate::expr::{Apply, Expression, FromExpression, IntoExpression};
use crate::expr::{AxisExpr, AxisExprMut, Iter, Lanes, LanesMut, Map, Zip};
use crate::index::{self, Axis, Cols, Resize, Rows, Split};
use crate::index::{DimIndex, Permutation, SliceIndex, ViewIndex};
use crate::layout::{Dense, Layout, Strided};
use crate::mapping::Mapping;
use crate::raw_slice::RawSlice;
use crate::shape::{ConstShape, DynRank, IntoShape, Rank, Shape};
use crate::tensor::Tensor;
use crate::traits::{IntoCloned, Owned};
use crate::view::{View, ViewMut};

/// Multidimensional array slice.
pub struct Slice<T, S: Shape = DynRank, L: Layout = Dense> {
    phantom: PhantomData<(T, S, L)>,
}

/// Multidimensional array slice with dynamically-sized dimensions.
pub type DSlice<T, const N: usize, L = Dense> = Slice<T, Rank<N>, L>;

impl<T, S: Shape, L: Layout> Slice<T, S, L> {
    /// Returns a mutable pointer to the array buffer.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        if mem::size_of::<L::Mapping<S>>() > 0 {
            RawSlice::from_mut_slice(self).as_mut_ptr()
        } else {
            self as *mut Self as *mut T
        }
    }

    /// Returns a raw pointer to the array buffer.
    #[inline]
    pub fn as_ptr(&self) -> *const T {
        if mem::size_of::<L::Mapping<S>>() > 0 {
            RawSlice::from_slice(self).as_ptr()
        } else {
            self as *const Self as *const T
        }
    }

    /// Assigns an expression to the array slice with broadcasting, cloning elements if needed.
    ///
    /// # Panics
    ///
    /// Panics if the expression cannot be broadcast to the shape of the array slice.
    #[inline]
    pub fn assign<I: IntoExpression<Item: IntoCloned<T>>>(&mut self, expr: I) {
        self.expr_mut().zip(expr).for_each(|(x, y)| y.clone_to(x));
    }

    /// Returns an array view after 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 at(&self, index: usize) -> View<'_, T, S::Tail, L> {
        self.axis_at(Const::<0>, index)
    }

    /// Returns a mutable array view after 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 at_mut(&mut self, index: usize) -> ViewMut<'_, T, S::Tail, L> {
        self.axis_at_mut(Const::<0>, index)
    }

    /// Returns an array view after 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 axis_at<A: Axis>(
        &self,
        axis: A,
        index: usize,
    ) -> View<'_, T, A::Remove<S>, Split<A, S, L>> {
        unsafe { View::axis_at(self.as_ptr(), self.mapping(), axis, index) }
    }

    /// Returns a mutable array view after 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 axis_at_mut<A: Axis>(
        &mut self,
        axis: A,
        index: usize,
    ) -> ViewMut<'_, T, A::Remove<S>, Split<A, S, L>> {
        unsafe { ViewMut::axis_at(self.as_mut_ptr(), self.mapping(), axis, index) }
    }

    /// Returns an expression that gives array views iterating over the specified dimension.
    ///
    /// If the dimension to be iterated over 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 dimension is out of bounds.
    #[inline]
    pub fn axis_expr<A: Axis>(&self, axis: A) -> AxisExpr<'_, T, S, L, A> {
        AxisExpr::new(self, axis)
    }

    /// Returns a mutable expression that gives array views iterating over the specified dimension.
    ///
    /// If the dimension to be iterated over 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 dimension is out of bounds.
    #[inline]
    pub fn axis_expr_mut<A: Axis>(&mut self, axis: A) -> AxisExprMut<'_, T, S, L, A> {
        AxisExprMut::new(self, axis)
    }

    /// Returns an 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 col(&self, index: usize) -> View<'_, T, (S::Head,), Strided> {
        let shape = self.shape().with_dims(<(_, <S::Tail as Shape>::Head)>::from_dims);

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

    /// Returns a mutable 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 col_mut(&mut self, index: usize) -> ViewMut<'_, T, (S::Head,), Strided> {
        let shape = self.shape().with_dims(<(_, <S::Tail as Shape>::Head)>::from_dims);

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

    /// Returns an expression that gives column views iterating over the other dimensions.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 2.
    #[inline]
    pub fn cols(&self) -> Lanes<'_, T, S, L, Cols> {
        self.lanes(Cols)
    }

    /// Returns a mutable expression that gives column views iterating over the other dimensions.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 2.
    #[inline]
    pub fn cols_mut(&mut self) -> LanesMut<'_, T, S, L, Cols> {
        self.lanes_mut(Cols)
    }

    /// Returns `true` if the array slice contains an element with the given value.
    #[inline]
    pub fn contains(&self, x: &T) -> bool
    where
        T: PartialEq,
    {
        contains(self, x)
    }

    /// Returns an array view for the given diagonal of the array slice,
    /// 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 diag(&self, index: isize) -> View<'_, T, (Dyn,), Strided> {
        let shape = self.shape().with_dims(<(S::Head, <S::Tail as Shape>::Head)>::from_dims);

        self.reshape(shape).into_diag(index)
    }

    /// Returns a mutable array view for the given diagonal of the array slice,
    /// 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 diag_mut(&mut self, index: isize) -> ViewMut<'_, T, (Dyn,), Strided> {
        let shape = self.shape().with_dims(<(S::Head, <S::Tail as Shape>::Head)>::from_dims);

        self.reshape_mut(shape).into_diag(index)
    }

    /// Returns the number of elements in the specified dimension.
    ///
    /// # Panics
    ///
    /// Panics if the dimension is out of bounds.
    #[inline]
    pub fn dim(&self, index: usize) -> usize {
        self.mapping().dim(index)
    }

    /// Returns an expression over the array slice.
    #[inline]
    pub fn expr(&self) -> View<'_, T, S, L> {
        unsafe { View::new_unchecked(self.as_ptr(), self.mapping().clone()) }
    }

    /// Returns a mutable expression over the array slice.
    #[inline]
    pub fn expr_mut(&mut self) -> ViewMut<'_, T, S, L> {
        unsafe { ViewMut::new_unchecked(self.as_mut_ptr(), self.mapping().clone()) }
    }

    /// Fills the array slice with elements by cloning `value`.
    #[inline]
    pub fn fill(&mut self, value: T)
    where
        T: Clone,
    {
        self.expr_mut().for_each(|x| x.clone_from(&value));
    }

    /// Fills the array slice with elements returned by calling a closure repeatedly.
    #[inline]
    pub fn fill_with<F: FnMut() -> T>(&mut self, mut f: F) {
        self.expr_mut().for_each(|x| *x = f());
    }

    /// Returns a one-dimensional array view of the array slice.
    ///
    /// # Panics
    ///
    /// Panics if the array layout is not uniformly strided.
    #[inline]
    pub fn flatten(&self) -> View<'_, T, (Dyn,), L> {
        self.reshape([self.len()])
    }

    /// Returns a mutable one-dimensional array view over the array slice.
    ///
    /// # Panics
    ///
    /// Panics if the array layout is not uniformly strided.
    #[inline]
    pub fn flatten_mut(&mut self) -> ViewMut<'_, T, (Dyn,), L> {
        self.reshape_mut([self.len()])
    }

    /// Returns a reference to an element or a subslice, without doing bounds checking.
    ///
    /// # Safety
    ///
    /// The index must be within bounds of the array slice.
    #[inline]
    pub unsafe fn get_unchecked<I: SliceIndex<T, S, L>>(&self, index: I) -> &I::Output {
        unsafe { index.get_unchecked(self) }
    }

    /// Returns a mutable reference to an element or a subslice, without doing bounds checking.
    ///
    /// # Safety
    ///
    /// The index must be within bounds of the array slice.
    #[inline]
    pub unsafe fn get_unchecked_mut<I: SliceIndex<T, S, L>>(&mut self, index: I) -> &mut I::Output {
        unsafe { index.get_unchecked_mut(self) }
    }

    /// Returns `true` if the array strides are consistent with contiguous memory layout.
    #[inline]
    pub fn is_contiguous(&self) -> bool {
        self.mapping().is_contiguous()
    }

    /// Returns `true` if the array contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.mapping().is_empty()
    }

    /// Returns an iterator over the array slice.
    #[inline]
    pub fn iter(&self) -> Iter<View<'_, T, S, L>> {
        self.expr().into_iter()
    }

    /// Returns a mutable iterator over the array slice.
    #[inline]
    pub fn iter_mut(&mut self) -> Iter<ViewMut<'_, T, S, L>> {
        self.expr_mut().into_iter()
    }

    /// Returns an expression that gives array views over the specified dimension,
    /// iterating over the other dimensions.
    ///
    /// If the dimension to give array views over is know at compile time, the resulting
    /// shape will maintain a constant-sized dimension. Furthermore, if it is the last
    /// dimension the resulting array views have the same layout as the input.
    ///
    /// # Panics
    ///
    /// Panics if the dimension is out of bounds.
    #[inline]
    pub fn lanes<A: Axis>(&self, axis: A) -> Lanes<'_, T, S, L, A> {
        Lanes::new(self, axis)
    }

    /// Returns a mutable expression that gives array views over the specified dimension,
    /// iterating over the other dimensions.
    ///
    /// If the dimension to give array views over is know at compile time, the resulting
    /// shape will maintain a constant-sized dimension. Furthermore, if it is the last
    /// dimension the resulting array views have the same layout as the input.
    ///
    /// # Panics
    ///
    /// Panics if the dimension is out of bounds.
    #[inline]
    pub fn lanes_mut<A: Axis>(&mut self, axis: A) -> LanesMut<'_, T, S, L, A> {
        LanesMut::new(self, axis)
    }

    /// Returns the number of elements in the array.
    #[inline]
    pub fn len(&self) -> usize {
        self.mapping().len()
    }

    /// Returns the array layout mapping.
    #[inline]
    pub fn mapping(&self) -> &L::Mapping<S> {
        if mem::size_of::<L::Mapping<S>>() > 0 {
            RawSlice::from_slice(self).mapping()
        } else {
            unsafe { &*NonNull::dangling().as_ptr() }
        }
    }

    /// Returns an expression that gives array views iterating over the first dimension.
    ///
    /// Iterating over the first dimension results in array views with the same layout
    /// as the input.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 1.
    #[inline]
    pub fn outer_expr(&self) -> AxisExpr<'_, T, S, L, Const<0>> {
        self.axis_expr(Const::<0>)
    }

    /// Returns a mutable expression that gives array views iterating over the first dimension.
    ///
    /// Iterating over the first dimension results in array views with the same layout
    /// as the input.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 1.
    #[inline]
    pub fn outer_expr_mut(&mut self) -> AxisExprMut<'_, T, S, L, Const<0>> {
        self.axis_expr_mut(Const::<0>)
    }

    /// Returns an 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 permute<I: IntoShape<IntoShape: Permutation>>(
        &self,
        perm: I,
    ) -> View<
        '_,
        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 { View::new_unchecked(self.as_ptr(), mapping) }
    }

    /// Returns a mutable 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 permute_mut<I: IntoShape<IntoShape: Permutation>>(
        &mut self,
        perm: I,
    ) -> ViewMut<
        '_,
        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 { ViewMut::new_unchecked(self.as_mut_ptr(), mapping) }
    }

    /// Returns the array rank, i.e. the number of dimensions.
    #[inline]
    pub fn rank(&self) -> usize {
        self.mapping().rank()
    }

    /// Returns a remapped array view of the array slice.
    ///
    /// # Panics
    ///
    /// Panics if the memory layout is not compatible with the new array layout.
    #[inline]
    pub fn remap<R: Shape, K: Layout>(&self) -> View<'_, T, R, K> {
        let mapping = Mapping::remap(self.mapping());

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

    /// Returns a mutable remapped array view of the array slice.
    ///
    /// # Panics
    ///
    /// Panics if the memory layout is not compatible with the new array layout.
    #[inline]
    pub fn remap_mut<R: Shape, K: Layout>(&mut self) -> ViewMut<'_, T, R, K> {
        let mapping = Mapping::remap(self.mapping());

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

    /// Returns a reordered array view of the array slice.
    ///
    /// This method is deprecated, use `transpose` instead.
    #[deprecated]
    #[inline]
    pub fn reorder(&self) -> View<'_, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
        let mapping = Mapping::transpose(self.mapping());

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

    /// Returns a mutable reordered array view of the array slice.
    ///
    /// This method is deprecated, use `transpose_mut` instead.
    #[deprecated]
    #[inline]
    pub fn reorder_mut(&mut self) -> ViewMut<'_, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
        let mapping = Mapping::transpose(self.mapping());

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

    /// Returns a reshaped array view of the array slice.
    ///
    /// 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.reshape([!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 reshape<I: IntoShape>(&self, shape: I) -> View<'_, T, I::IntoShape, L> {
        let mapping = self.mapping().reshape(shape.into_shape());

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

    /// Returns a mutable reshaped array view of the array slice.
    ///
    /// At most one dimension can have dynamic size `usize::MAX`, and is then inferred
    /// from the other dimensions and the array length.
    ///
    /// See the `reshape` method above for examples.
    ///
    /// # Panics
    ///
    /// Panics if the array length is changed, or if the memory layout is not compatible.
    #[inline]
    pub fn reshape_mut<I: IntoShape>(&mut self, shape: I) -> ViewMut<'_, T, I::IntoShape, L> {
        let mapping = self.mapping().reshape(shape.into_shape());

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

    /// Returns an 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 row(&self, index: usize) -> View<'_, T, (<S::Tail as Shape>::Head,), L> {
        let shape = self.shape().with_dims(<(S::Head, _)>::from_dims);

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

    /// Returns a mutable 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 row_mut(&mut self, index: usize) -> ViewMut<'_, T, (<S::Tail as Shape>::Head,), L> {
        let shape = self.shape().with_dims(<(S::Head, _)>::from_dims);

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

    /// Returns an expression that gives row views iterating over the other dimensions.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 1.
    #[inline]
    pub fn rows(&self) -> Lanes<'_, T, S, L, Rows> {
        self.lanes(Rows)
    }

    /// Returns a mutable expression that gives row views iterating over the other dimensions.
    ///
    /// # Panics
    ///
    /// Panics if the rank is not at least 1.
    #[inline]
    pub fn rows_mut(&mut self) -> LanesMut<'_, T, S, L, Rows> {
        self.lanes_mut(Rows)
    }

    /// Returns the array shape.
    #[inline]
    pub fn shape(&self) -> &S {
        self.mapping().shape()
    }

    /// Divides an array slice 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 split_at(
        &self,
        mid: usize,
    ) -> (View<'_, T, Resize<Const<0>, S>, L>, View<'_, T, Resize<Const<0>, S>, L>) {
        self.split_axis_at(Const::<0>, mid)
    }

    /// Divides a mutable array slice 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 split_at_mut(
        &mut self,
        mid: usize,
    ) -> (ViewMut<'_, T, Resize<Const<0>, S>, L>, ViewMut<'_, T, Resize<Const<0>, S>, L>) {
        self.split_axis_at_mut(Const::<0>, mid)
    }

    /// Divides an array slice 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 split_axis_at<A: Axis>(
        &self,
        axis: A,
        mid: usize,
    ) -> (View<'_, T, Resize<A, S>, Split<A, S, L>>, View<'_, T, Resize<A, S>, Split<A, S, L>>)
    {
        unsafe { View::split_axis_at(self.as_ptr(), self.mapping(), axis, mid) }
    }

    /// Divides a mutable array slice 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 split_axis_at_mut<A: Axis>(
        &mut self,
        axis: A,
        mid: usize,
    ) -> (ViewMut<'_, T, Resize<A, S>, Split<A, S, L>>, ViewMut<'_, T, Resize<A, S>, Split<A, S, L>>)
    {
        unsafe { ViewMut::split_axis_at(self.as_mut_ptr(), self.mapping(), axis, mid) }
    }

    /// Returns the distance between elements in the specified dimension.
    ///
    /// # Panics
    ///
    /// Panics if the dimension is out of bounds.
    #[inline]
    pub fn stride(&self, index: usize) -> isize {
        self.mapping().stride(index)
    }

    /// Swaps two elements in the array slice.
    ///
    /// # Panics
    ///
    /// Panics if `a` or `b` are out of bounds.
    #[inline]
    pub fn swap<I, J>(&mut self, a: I, b: J)
    where
        I: SliceIndex<T, S, L, Output = T>,
        J: SliceIndex<T, S, L, Output = T>,
    {
        unsafe {
            ptr::swap(&raw mut self[a], &raw mut self[b]);
        }
    }

    /// Swaps the elements in two subarrays after indexing the specified dimension.
    ///
    /// # Panics
    ///
    /// Panics if `a` or `b` are out of bounds.
    #[inline]
    pub fn swap_axis<A: Axis>(&mut self, axis: A, a: usize, b: usize) {
        let size = self.dim(axis.index(self.rank()));

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

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

        if a != b {
            let (mut first, mut second) = self.split_axis_at_mut(axis, a.max(b));

            let first = first.axis_at_mut(axis, a.min(b));
            let second = second.axis_at_mut(axis, 0);

            first.zip(second).for_each(|(x, y)| mem::swap(x, y));
        }
    }

    /// Copies the array slice into a new array.
    #[inline]
    pub fn to_array(&self) -> Array<T, S>
    where
        T: Clone,
        S: ConstShape,
    {
        Array::from(self)
    }

    /// Copies the array slice into a new array.
    #[inline]
    pub fn to_tensor(&self) -> Tensor<T, S>
    where
        T: Clone,
    {
        Tensor::from(self)
    }

    /// Copies the array slice into a new array with the specified allocator.
    #[cfg(feature = "nightly")]
    #[inline]
    pub fn to_tensor_in<A: Allocator>(&self, alloc: A) -> Tensor<T, S, A>
    where
        T: Clone,
    {
        Tensor::from_expr_in(self.expr().cloned(), alloc)
    }

    /// Copies the array slice into a new vector.
    #[inline]
    pub fn to_vec(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.to_tensor().into_vec()
    }

    /// Copies the array slice into a new vector with the specified allocator.
    #[cfg(feature = "nightly")]
    #[inline]
    pub fn to_vec_in<A: Allocator>(&self, alloc: A) -> Vec<T, A>
    where
        T: Clone,
    {
        self.to_tensor_in(alloc).into_vec()
    }

    /// Returns a transposed array view of the array slice, where the dimensions
    /// are reversed.
    #[inline]
    pub fn transpose(&self) -> View<'_, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
        let mapping = Mapping::transpose(self.mapping());

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

    /// Returns a mutable transposed array view of the array slice, where the dimensions
    /// are reversed.
    #[inline]
    pub fn transpose_mut(&mut self) -> ViewMut<'_, T, S::Reverse, <S::Tail as Shape>::Layout<L>> {
        let mapping = Mapping::transpose(self.mapping());

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

impl<T, L: Layout> Slice<T, DynRank, L> {
    /// Returns the number of elements in each dimension.
    #[inline]
    pub fn dims(&self) -> &[usize] {
        self.mapping().dims()
    }
}

impl<T, S: Shape> Slice<T, S, Strided> {
    /// Returns the distance between elements in each dimension.
    #[inline]
    pub fn strides(&self) -> &[isize] {
        self.mapping().strides()
    }
}

macro_rules! impl_view {
    (($($xyz:tt),+), ($($abc:tt),+), ($($idx:tt),+)) => {
        impl<T, $($xyz: Dim,)+ L: Layout> Slice<T, ($($xyz,)+), L> {
            /// Copies the specified subarray into a new array.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn array<$($abc: DimIndex),+>(
                &self,
                $($idx: $abc),+
            ) -> Array<T, <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>>
            where
                T: Clone,
                ($($abc,)+): ViewIndex<Shape<($($xyz,)+)>: ConstShape>,
            {
                self.view($($idx),+).to_array()
            }

            /// Copies the specified subarray into a new array.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn tensor<$($abc: DimIndex),+>(
                &self,
                $($idx: $abc),+
            ) -> Tensor<T, <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>>
            where
                T: Clone,
            {
                self.view($($idx),+).to_tensor()
            }

            /// Returns an array view for the specified subarray.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn view<$($abc: DimIndex),+>(
                &self,
                $($idx: $abc),+
            ) -> View<
                '_,
                T,
                <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>,
                <($($abc,)+) as ViewIndex>::Layout<L>,
            > {
                self.expr().into_view($($idx),+)
            }

            /// Returns a mutable array view for the specified subarray.
            ///
            /// # Panics
            ///
            /// Panics if the subarray is out of bounds.
            #[inline]
            pub fn view_mut<$($abc: DimIndex),+>(
                &mut self,
                $($idx: $abc),+,
            ) -> ViewMut<
                '_,
                T,
                <($($abc,)+) as ViewIndex>::Shape<($($xyz,)+)>,
                <($($abc,)+) as ViewIndex>::Layout<L>,
            > {
                self.expr_mut().into_view($($idx),+)
            }
        }
    };
}

impl_view!((X), (A), (a));
impl_view!((X, Y), (A, B), (a, b));
impl_view!((X, Y, Z), (A, B, C), (a, b, c));
impl_view!((X, Y, Z, W), (A, B, C, D), (a, b, c, d));
impl_view!((X, Y, Z, W, U), (A, B, C, D, E), (a, b, c, d, e));
impl_view!((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 Slice<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<'a, T, U, S: Shape, L: Layout> Apply<U> for &'a mut Slice<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, S: Shape, L: Layout> AsMut<Self> for Slice<T, S, L> {
    #[inline]
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}

impl<T, D: Dim> AsMut<[T]> for Slice<T, (D,)> {
    #[inline]
    fn as_mut(&mut self) -> &mut [T] {
        self.expr_mut().into()
    }
}

impl<T, S: Shape, L: Layout> AsRef<Self> for Slice<T, S, L> {
    #[inline]
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<T, D: Dim> AsRef<[T]> for Slice<T, (D,)> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        self.expr().into()
    }
}

macro_rules! impl_as_mut_ref {
    (($($xyz:tt),+), $array:tt) => {
        impl<T, $(const $xyz: usize),+> AsMut<$array> for Slice<T, ($(Const<$xyz>,)+)> {
            #[inline]
            fn as_mut(&mut self) -> &mut $array {
                unsafe { &mut *(self as *mut Self as *mut $array) }
            }
        }

        impl<T, $(const $xyz: usize),+> AsRef<$array> for Slice<T, ($(Const<$xyz>,)+)> {
            #[inline]
            fn as_ref(&self) -> &$array {
                unsafe { &*(self as *const Self as *const $array) }
            }
        }
    };
}

impl_as_mut_ref!((X), [T; X]);
impl_as_mut_ref!((X, Y), [[T; Y]; X]);
impl_as_mut_ref!((X, Y, Z), [[[T; Z]; Y]; X]);
impl_as_mut_ref!((X, Y, Z, W), [[[[T; W]; Z]; Y]; X]);
impl_as_mut_ref!((X, Y, Z, W, U), [[[[[T; U]; W]; Z]; Y]; X]);
impl_as_mut_ref!((X, Y, Z, W, U, V), [[[[[[T; V]; U]; W]; Z]; Y]; X]);

impl<T: Debug, S: Shape, L: Layout> Debug for Slice<T, S, L> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        if self.rank() == 0 {
            self[[]].fmt(f)
        } else {
            f.debug_list().entries(self.outer_expr()).finish()
        }
    }
}

impl<T: Hash, S: Shape, L: Layout> Hash for Slice<T, S, L> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        for i in 0..self.rank() {
            #[cfg(not(feature = "nightly"))]
            state.write_usize(self.dim(i));
            #[cfg(feature = "nightly")]
            state.write_length_prefix(self.dim(i));
        }

        self.expr().for_each(|x| x.hash(state));
    }
}

impl<T, S: Shape, L: Layout, I: SliceIndex<T, S, L>> Index<I> for Slice<T, S, L> {
    type Output = I::Output;

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

impl<T, S: Shape, L: Layout, I: SliceIndex<T, S, L>> IndexMut<I> for Slice<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 Slice<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> IntoExpression for &'a mut Slice<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 Slice<T, S, L> {
    type Item = &'a T;
    type IntoIter = Iter<View<'a, T, S, L>>;

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

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

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

impl<T: Clone, S: Shape> ToOwned for Slice<T, S> {
    type Owned = S::Owned<T>;

    #[inline]
    fn to_owned(&self) -> Self::Owned {
        FromExpression::from_expr(self.into_expr().cloned())
    }

    #[inline]
    fn clone_into(&self, target: &mut Self::Owned) {
        target.clone_from_slice(self);
    }
}

#[inline]
fn contains<T: PartialEq, S: Shape, L: Layout>(this: &Slice<T, S, L>, value: &T) -> bool {
    if L::IS_DENSE {
        this.remap::<S, _>()[..].contains(value)
    } else if this.rank() < 2 {
        this.iter().any(|x| x == value)
    } else {
        this.outer_expr().into_iter().any(|x| x.contains(value))
    }
}