rlst 0.10.0

A Rust native linear algebra library.
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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
//! Basic Array type
//!
//! [Array] is the basic type for dense calculations in Rlst. The full definition
//! `Array<ArrayImpl, NDIM>` represents a tensor with `NDIM` axes implemented through
//! the implementeation type `ArrayImpl`.

use std::ops::{Add, Sub};

use aligned_vec::{AVec, CACHELINE_ALIGN, ConstAlign};
use empty_axis::AxisPosition;
use iterators::{
    ArrayDefaultIteratorByRef, ArrayDefaultIteratorByValue, ArrayDefaultIteratorMut,
    ArrayDiagIteratorByRef, ArrayDiagIteratorByValue, ArrayDiagIteratorMut, ColIterator,
    ColIteratorMut, RowIterator, RowIteratorMut,
};
use itertools::izip;
use num::{One, Zero, traits::MulAdd};
use operators::{
    addition::ArrayAddition, cast::ArrayCast, cmp_wise_division::CmpWiseDivision,
    cmp_wise_product::CmpWiseProduct, coerce::CoerceArray, mul_add::MulAddImpl, negation::ArrayNeg,
    reverse_axis::ReverseAxis, scalar_mult::ArrayScalarMult, subtraction::ArraySubtraction,
    transpose::ArrayTranspose, unary_op::ArrayUnaryOperator,
};
use typenum::{Const, NonZero, PInt, ToUInt, U, Unsigned};

use crate::base_types::{c32, c64};

use crate::dense::array::iterators::{MultisliceIterator, MultisliceIteratorMut};
use crate::{
    ArrayFromContainerType, Linspace, MutableArrayImpl, RowMajorArrayFromContainerType,
    ScalarAsArray,
};

use paste::paste;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use rand_distr::{Distribution, StandardNormal, StandardUniform};
use reference::{ArrayRef, ArrayRefMut};
use slice::ArraySlice;
use subview::ArraySubView;

use crate::{
    AsMatrixApply, AsMultiIndex, EvaluateArray, EvaluateRowMajorArray, Gemm, IsGreaterByOne,
    IsGreaterZero, IsSmallerThan, Max, MemoryLayout, NumberDifference, NumberType, RandScalar,
    RandomAccessByValue, RlstError, RlstResult, RlstScalar, SubtractEqual, TransMode,
    dense::{
        array::multislice::Multislice,
        base_array::BaseArray,
        data_container::{
            AlignedVectorContainer, SliceContainer, SliceContainerMut, VectorContainer,
        },
        layout::check_multi_index_in_bounds,
        strided_base_array::{StridedBaseArray, required_storage_len},
    },
    traits::{
        accessors::{
            RandomAccessByRef, RandomAccessMut, RawAccess, RawAccessMut,
            UnsafeDisjointRandom1DAccessMut, UnsafeRandom1DAccessByRef,
            UnsafeRandom1DAccessByValue, UnsafeRandomAccessByRef, UnsafeRandomAccessByValue,
            UnsafeRandomAccessMut,
        },
        base_operations::{BaseItem, ResizeInPlace, Shape, Stride},
        data_container::ContainerType,
    },
};

use super::{data_container::ArrayContainer, layout::row_major_stride_from_shape};

pub mod empty_axis;
pub mod iterators;
pub mod mult_into;
pub mod operations;
pub mod operators;
// pub mod rank1_array;
pub mod flattened;
pub mod multislice;
pub mod reference;
pub mod shared_array;
pub mod slice;
pub mod subview;
pub mod zero_dim;

pub use zero_dim::ZeroDimArray;

/// A heap-allocated, contiguous column-major array.
///
/// Construct one with [`DynArray::from_shape`], [`DynArray::from_shape_and_vec`], or
/// [`crate::rlst_dynamic_array`]. Elements supplied as a flat vector use column-major order.
/// This storage requires at least one axis; use [`ZeroDimArray`] for scalar results.
pub type DynArray<Item, const NDIM: usize> = Array<BaseArray<VectorContainer<Item>, NDIM>, NDIM>;

/// A contiguous column-major array with an explicitly aligned heap allocation.
pub type AlignedDynArray<Item, const NDIM: usize, const ALIGNMENT: usize = CACHELINE_ALIGN> =
    Array<BaseArray<AlignedVectorContainer<Item, ALIGNMENT>, NDIM>, NDIM>;

/// A heap-allocated array with an explicit non-overlapping stride.
///
/// Logical iteration remains column-major even when the physical storage layout is not.
pub type StridedDynArray<Item, const NDIM: usize> =
    Array<StridedBaseArray<VectorContainer<Item>, NDIM>, NDIM>;

/// A statically allocated array.
///
/// `N` is the number of elements to be reserved in the static
/// container.
pub type StaticArray<Item, const NDIM: usize, const N: usize> =
    Array<BaseArray<ArrayContainer<Item, N>, NDIM>, NDIM>;

/// A dynamically allocated array from a data slice.
pub type SliceArray<'a, Item, const NDIM: usize> =
    Array<BaseArray<SliceContainer<'a, Item>, NDIM>, NDIM>;

/// A dynamically allocated array from a data slice with a given stride.
pub type StridedSliceArray<'a, Item, const NDIM: usize> =
    Array<StridedBaseArray<SliceContainer<'a, Item>, NDIM>, NDIM>;

/// A mutable dynamically allocated array from a data slice.
pub type SliceArrayMut<'a, Item, const NDIM: usize> =
    Array<BaseArray<SliceContainerMut<'a, Item>, NDIM>, NDIM>;

/// A mutable dynamically allocated array from a data slice with a given stride.
pub type StridedSliceArrayMut<'a, Item, const NDIM: usize> =
    Array<StridedBaseArray<SliceContainerMut<'a, Item>, NDIM>, NDIM>;

/// Public array wrapper around a storage, view, or lazy-expression implementation.
///
/// `NDIM` is the number of axes. The implementation determines whether data is owned or
/// borrowed, contiguous or strided, mutable, or computed lazily. Most users construct one of
/// the aliases such as [`DynArray`] rather than naming the implementation type.
pub struct Array<ArrayImpl, const NDIM: usize>(ArrayImpl);

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Wrap an array implementation.
    ///
    /// The implementation determines the supported ranks and access operations.
    /// [`ZeroDimArray`] provides scalar-only storage for rank zero.
    pub fn new(arr: ArrayImpl) -> Self {
        Self(arr)
    }

    /// Return a reference to the implementation.
    #[inline(always)]
    pub fn imp(&self) -> &ArrayImpl {
        &self.0
    }

    /// Return a mutable reference to the implementation.
    #[inline(always)]
    pub fn imp_mut(&mut self) -> &mut ArrayImpl {
        &mut self.0
    }

    /// Extract the inner implementation.
    #[inline(always)]
    pub fn into_imp(self) -> ArrayImpl {
        self.0
    }

    /// Wrap a shared borrow in an array value.
    ///
    /// This is useful with operators and views that consume their operands. The returned value
    /// does not copy data and cannot outlive `self`.
    #[inline(always)]
    pub fn r(&self) -> Array<ArrayRef<'_, ArrayImpl, NDIM>, NDIM> {
        Array::new(ArrayRef::new(self))
    }

    /// Wrap an exclusive borrow in an array value.
    ///
    /// The returned value does not copy data and cannot outlive the mutable borrow of `self`.
    #[inline(always)]
    pub fn r_mut(&mut self) -> Array<ArrayRefMut<'_, ArrayImpl, NDIM>, NDIM> {
        Array::new(ArrayRefMut::new(self))
    }
}

impl<ArrayImpl, const NDIM: usize> BaseItem for Array<ArrayImpl, NDIM>
where
    ArrayImpl: BaseItem,
{
    type Item = ArrayImpl::Item;
}

impl<ArrayImpl: Shape<NDIM>, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Return the number of elements in the array.
    #[inline(always)]
    pub fn number_of_elements(&self) -> usize {
        self.0.shape().iter().product()
    }
}

impl<Item: Copy + Default, const NDIM: usize> DynArray<Item, NDIM> {
    /// Allocate a default-initialized column-major array with `shape`.
    ///
    /// A zero extent is permitted and produces an empty array.
    #[inline(always)]
    pub fn from_shape(shape: [usize; NDIM]) -> Self {
        let size = shape.iter().product();
        Self::new(BaseArray::new(VectorContainer::new(size), shape))
    }

    /// Create a column-major array from `data` without copying the vector.
    ///
    /// Flat element `i` corresponds to the column-major logical index `i`.
    ///
    /// # Panics
    ///
    /// Panics if `data.len()` differs from the product of `shape`.
    #[inline(always)]
    pub fn from_shape_and_vec(shape: [usize; NDIM], data: Vec<Item>) -> Self {
        assert_eq!(
            data.len(),
            shape.iter().product::<usize>(),
            "Data length does not match the shape: {} != {}",
            data.len(),
            shape.iter().product::<usize>()
        );
        Self::new(BaseArray::new(VectorContainer::from_vec(data), shape))
    }
}

impl<Item: Copy + Default, const NDIM: usize, const ALIGNMENT: usize>
    AlignedDynArray<Item, NDIM, ALIGNMENT>
{
    /// Allocate a default-initialized column-major array with `shape` and `ALIGNMENT`.
    ///
    /// `ALIGNMENT` must satisfy the allocator requirements documented by `aligned-vec`.
    #[inline(always)]
    pub fn from_shape(shape: [usize; NDIM]) -> Self {
        let size = shape.iter().product();
        Self::new(BaseArray::new(AlignedVectorContainer::new(size), shape))
    }

    /// Create an aligned column-major array from an aligned vector without copying it.
    ///
    /// # Panics
    ///
    /// Panics if `data.len()` differs from the product of `shape`.
    #[inline(always)]
    pub fn from_shape_and_avec(
        shape: [usize; NDIM],
        data: AVec<Item, ConstAlign<ALIGNMENT>>,
    ) -> Self {
        assert_eq!(
            data.len(),
            shape.iter().product::<usize>(),
            "Data length does not match the shape: {} != {}",
            data.len(),
            shape.iter().product::<usize>()
        );
        Self::new(BaseArray::new(
            AlignedVectorContainer::from_avec(data),
            shape,
        ))
    }
}

impl<Item: Copy + Default> DynArray<Item, 2> {
    /// Create a new dense matrix with shape `shape` filled with values from the iterator `iter`.
    pub fn from_iter_aij<Iter: Iterator<Item = ([usize; 2], Item)>>(
        shape: [usize; 2],
        iter: Iter,
    ) -> DynArray<Item, 2> {
        let mut out = DynArray::<Item, 2>::from_shape(shape);

        for (index, item) in iter {
            out[index] = item;
        }

        out
    }
}

impl<Item: Copy + Default, const ALIGNMENT: usize> AlignedDynArray<Item, 2, ALIGNMENT> {
    /// Create a new dense matrix with shape `shape` filled with values from the iterator `iter`.
    pub fn from_iter_aij<Iter: Iterator<Item = ([usize; 2], Item)>>(
        shape: [usize; 2],
        iter: Iter,
    ) -> AlignedDynArray<Item, 2, ALIGNMENT> {
        let mut out = AlignedDynArray::<Item, 2, ALIGNMENT>::from_shape(shape);

        for (index, item) in iter {
            out[index] = item;
        }

        out
    }
}

impl<Item: Copy + Default> From<&[Item]> for DynArray<Item, 1> {
    fn from(value: &[Item]) -> Self {
        DynArray::<Item, 1>::from_shape_and_vec([value.len()], value.to_vec())
    }
}

impl<Item: Copy + Default, const N: usize> From<[Item; N]> for StaticArray<Item, 1, N> {
    fn from(value: [Item; N]) -> Self {
        StaticArray::new(BaseArray::new(value.into(), [N]))
    }
}

impl<Item: Copy + Default> From<Vec<Item>> for DynArray<Item, 1> {
    fn from(value: Vec<Item>) -> Self {
        DynArray::<Item, 1>::from_shape_and_vec([value.len()], value)
    }
}

impl<Item: Copy + Default> From<Vec<Vec<Item>>> for DynArray<Item, 2> {
    fn from(value: Vec<Vec<Item>>) -> Self {
        let nrows = value.len();
        if nrows == 0 {
            empty_array()
        } else {
            let ncols = value.first().unwrap().len();
            // Check that all columns have identical length

            for row in value.iter() {
                assert_eq!(ncols, row.len(), "All rows must have equal length.");
            }

            // Now create the matrix and fill with values.

            let mut out = DynArray::<Item, 2>::from_shape([nrows, ncols]);

            for (row_index, row) in value.iter().enumerate() {
                for (col_index, &elem) in row.iter().enumerate() {
                    out[[row_index, col_index]] = elem;
                }
            }

            out
        }
    }
}

impl<Item: Copy + Default, const NDIM: usize> StridedDynArray<Item, NDIM> {
    /// Allocate an array with an explicit physical `stride`.
    ///
    /// The allocation spans through the greatest reachable storage offset. Strides must map
    /// every logical index to a distinct storage element.
    ///
    /// # Panics
    ///
    /// Panics if two computed logical offsets are equal. Shape/stride arithmetic uses ordinary
    /// `usize` operations, so callers must provide metadata whose products, offsets, and storage
    /// span are representable.
    #[inline(always)]
    pub fn from_shape_and_stride(shape: [usize; NDIM], stride: [usize; NDIM]) -> Self {
        let size = required_storage_len(shape, stride);
        Self::new(StridedBaseArray::new(
            VectorContainer::new(size),
            shape,
            stride,
        ))
    }
}

impl<Item: Copy + Default, const NDIM: usize>
    Array<StridedBaseArray<VectorContainer<Item>, NDIM>, NDIM>
{
    /// Create a new heap allocated row-major array.
    #[inline(always)]
    pub fn row_major(shape: [usize; NDIM]) -> Self {
        let size = shape.iter().product();
        Self::new(StridedBaseArray::new(
            VectorContainer::new(size),
            shape,
            row_major_stride_from_shape(shape),
        ))
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM>,
{
    /// Return the shape of an array.
    ///
    /// # Traits:
    /// - [Shape]
    #[inline(always)]
    pub fn shape(&self) -> [usize; NDIM] {
        self.0.shape()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM>,
{
    /// Return the length of an array.
    ///
    /// For more than one dimension the length is the number of elements.
    /// # Traits:
    /// - [Shape]
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Return true if the array is empty.
    ///
    /// This is equivalent to at least one dimension being zero.
    /// # Traits:
    /// - [Shape]
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessByValue<NDIM>,
{
    /// Get an element by value.
    ///
    /// # Safety
    /// `multi_index` must be in range.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByValue]
    #[inline(always)]
    pub unsafe fn get_value_unchecked(&self, multi_index: [usize; NDIM]) -> ArrayImpl::Item {
        unsafe { self.0.get_value_unchecked(multi_index) }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessByRef<NDIM>,
{
    /// Get an element by reference.
    ///
    /// # Safety
    /// `multi_index` must be in range.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByRef]
    #[inline(always)]
    pub unsafe fn get_unchecked(&self, multi_index: [usize; NDIM]) -> &ArrayImpl::Item {
        unsafe { self.0.get_unchecked(multi_index) }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessMut<NDIM>,
{
    /// Get an element by mutable reference.
    ///
    /// # Safety
    /// `multi_index` must be in range.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessMut]
    #[inline(always)]
    pub unsafe fn get_unchecked_mut(&mut self, multi_index: [usize; NDIM]) -> &mut ArrayImpl::Item {
        unsafe { self.0.get_unchecked_mut(multi_index) }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: RandomAccessByValue<NDIM>,
{
    /// Get an element by value.
    ///
    /// # Traits
    /// - [RandomAccessByValue]
    #[inline(always)]
    pub fn get_value(&self, multi_index: [usize; NDIM]) -> Option<ArrayImpl::Item> {
        self.0.get_value(multi_index)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: RandomAccessByRef<NDIM>,
{
    /// Get an element by reference.
    ///
    /// # Traits
    /// - [RandomAccessByRef]
    #[inline(always)]
    pub fn get(&self, multi_index: [usize; NDIM]) -> Option<&ArrayImpl::Item> {
        self.0.get(multi_index)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: RandomAccessMut<NDIM>,
{
    /// Get an element by mutable reference.
    ///
    /// # Traits
    /// - [RandomAccessMut]
    #[inline(always)]
    pub fn get_mut(&mut self, multi_index: [usize; NDIM]) -> Option<&mut ArrayImpl::Item> {
        self.0.get_mut(multi_index)
    }
}

impl<ArrayImpl, const NDIM: usize> std::ops::Index<[usize; NDIM]> for Array<ArrayImpl, NDIM>
where
    ArrayImpl: RandomAccessByRef<NDIM>,
{
    type Output = ArrayImpl::Item;
    #[inline(always)]
    fn index(&self, index: [usize; NDIM]) -> &Self::Output {
        self.0.get(index).unwrap()
    }
}

impl<ArrayImpl, const NDIM: usize> std::ops::IndexMut<[usize; NDIM]> for Array<ArrayImpl, NDIM>
where
    Array<ArrayImpl, NDIM>: std::ops::Index<[usize; NDIM], Output = ArrayImpl::Item>,
    ArrayImpl: RandomAccessMut<NDIM>,
{
    #[inline(always)]
    fn index_mut(&mut self, index: [usize; NDIM]) -> &mut ArrayImpl::Item {
        self.0.get_mut(index).unwrap()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: RawAccess,
{
    /// Return the complete backing storage when it is exposed as one contiguous slice.
    ///
    /// The slice follows physical storage order, which may differ from logical column-major
    /// iteration for a row-major array. Views and lazy expressions can return `None`.
    #[inline(always)]
    pub fn data(&self) -> Option<&[ArrayImpl::Item]> {
        self.0.data()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: RawAccessMut,
{
    /// Return the complete mutable backing storage when exposed as one contiguous slice.
    ///
    /// The slice follows physical storage order. Views and lazy expressions can return `None`.
    #[inline(always)]
    pub fn data_mut(&mut self) -> Option<&mut [ArrayImpl::Item]> {
        self.0.data_mut()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: Stride<NDIM>,
{
    /// Return the stride.
    ///
    /// # Traits
    /// - [Stride]
    #[inline(always)]
    pub fn stride(&self) -> [usize; NDIM] {
        self.0.stride()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: Stride<NDIM> + Shape<NDIM>,
{
    /// Return the memory layout
    ///
    /// The possible memory layouts are defined in [MemoryLayout].
    #[inline(always)]
    pub fn memory_layout(&self) -> MemoryLayout {
        self.0.memory_layout()
    }

    /// Return true of the memory layout is contiguous, otherwise false.
    ///
    /// A memory layout is contiguous if it is either row or column major.
    pub fn is_contiguous(&self) -> bool {
        self.0.is_contiguous()
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: ResizeInPlace<NDIM>,
{
    /// Resize the array to the new `shape`.
    ///
    /// The content of the array will be lost upon resizing.
    ///
    /// # Traits
    /// - [ResizeInPlace]
    pub fn resize_in_place(&mut self, shape: [usize; NDIM]) {
        self.0.resize_in_place(shape)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> EvaluateArray<Item, NDIM> for Array<ArrayImpl, NDIM>
where
    Item: Copy + Default,
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM> + ContainerType,
{
    type OutputImpl =
        <<ArrayImpl as ContainerType>::Type as ArrayFromContainerType>::OutputImpl<Item, NDIM>;

    fn eval(&self) -> Array<Self::OutputImpl, NDIM> {
        let mut out = <<ArrayImpl as ContainerType>::Type as ArrayFromContainerType>::new_arr::<
            Item,
            NDIM,
        >(self.shape());

        out.fill_from(self);

        out
    }
}

impl<Item, ArrayImpl, const NDIM: usize> EvaluateRowMajorArray<Item, NDIM>
    for Array<ArrayImpl, NDIM>
where
    Item: Copy + Default,
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM> + ContainerType,
{
    type OutputImpl =
        <<ArrayImpl as ContainerType>::Type as RowMajorArrayFromContainerType>::OutputImpl<
            Item,
            NDIM,
        >;

    fn eval_row_major(&self) -> Array<Self::OutputImpl, NDIM> {
        let mut out =
            <<ArrayImpl as ContainerType>::Type as RowMajorArrayFromContainerType>::new_row_major_arr::<
                Item,
                NDIM,
            >(self.shape());

        out.fill_from(self);

        out
    }
}

/// Create an empty array of given type and dimension.
///
/// Empty arrays serve as convenient containers for input into functions that
/// resize an array before filling it with data.
pub fn empty_array<Item, const NDIM: usize>() -> Array<BaseArray<VectorContainer<Item>, NDIM>, NDIM>
where
    Item: Copy + Default,
{
    let shape = [0; NDIM];
    let container = VectorContainer::new(0);
    Array::new(BaseArray::new(container, shape))
}

impl<'a, Item, const NDIM: usize> SliceArray<'a, Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new array from `slice` with a given `shape`.
    pub fn from_shape(slice: &'a [Item], shape: [usize; NDIM]) -> Self {
        assert_eq!(
            slice.len(),
            shape.iter().product::<usize>(),
            "Slice length does not match the shape: {} != {}",
            slice.len(),
            shape.iter().product::<usize>()
        );
        Array::new(BaseArray::new(SliceContainer::new(slice), shape))
    }
}

impl<'a, Item, const NDIM: usize> SliceArrayMut<'a, Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new array from mutable `slice` with a given `shape`.
    pub fn from_shape(slice: &'a mut [Item], shape: [usize; NDIM]) -> Self {
        assert_eq!(
            slice.len(),
            shape.iter().product::<usize>(),
            "Slice length does not match the shape: {} != {}",
            slice.len(),
            shape.iter().product::<usize>()
        );
        Array::new(BaseArray::new(SliceContainerMut::new(slice), shape))
    }
}

impl<'a, Item, const NDIM: usize> StridedSliceArray<'a, Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new array from `slice` with a given `shape` and `stride`.
    pub fn from_shape_and_stride(
        slice: &'a [Item],
        shape: [usize; NDIM],
        stride: [usize; NDIM],
    ) -> Self {
        Array::new(StridedBaseArray::new(
            SliceContainer::new(slice),
            shape,
            stride,
        ))
    }
}

impl<'a, Item, const NDIM: usize> StridedSliceArrayMut<'a, Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new array from `slice` with a given `shape` and `stride`.
    pub fn from_shape_and_stride(
        slice: &'a mut [Item],
        shape: [usize; NDIM],
        stride: [usize; NDIM],
    ) -> Self {
        Array::new(StridedBaseArray::new(
            SliceContainerMut::new(slice),
            shape,
            stride,
        ))
    }
}

impl<ArrayImpl: Shape<NDIM>, const NDIM: usize> std::fmt::Debug for Array<ArrayImpl, NDIM> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let shape = self.shape();
        write!(f, "Array[").unwrap();
        for item in shape {
            write!(f, "{item},").unwrap();
        }
        write!(f, "]")
    }
}

impl<Item, const NDIM: usize> DynArray<Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new array and fill with values from `arr`.
    pub fn new_from<ArrayImpl>(arr: &Array<ArrayImpl, NDIM>) -> Self
    where
        ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    {
        let mut output = empty_array::<Item, NDIM>();
        output.fill_from_resize(arr);
        output
    }
}

impl<Item, const NDIM: usize> StridedDynArray<Item, NDIM>
where
    Item: Copy + Default,
{
    /// Create a new strided array with `stride` and fill with values from `arr`.
    pub fn new_from<ArrayImpl>(stride: [usize; NDIM], arr: &Array<ArrayImpl, NDIM>) -> Self
    where
        ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    {
        let mut output = StridedDynArray::from_shape_and_stride(arr.shape(), stride);
        output.fill_from(arr);
        output
    }

    /// Create a new row-major array from existing array `arr`.
    pub fn row_major_from<ArrayImpl>(arr: &Array<ArrayImpl, NDIM>) -> Self
    where
        ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    {
        StridedDynArray::new_from(row_major_stride_from_shape(arr.shape()), arr)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandom1DAccessByValue + Shape<NDIM>,
{
    /// Iterate through the array by value.
    ///
    /// The iterator always proceeds in column-major order.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn iter_value(&self) -> ArrayDefaultIteratorByValue<'_, ArrayImpl, NDIM> {
        ArrayDefaultIteratorByValue::new(self)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandom1DAccessByRef + Shape<NDIM>,
{
    /// Iterate through the array by reference.
    ///
    /// The iterator always proceeds in column-major order.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByRef]
    /// - [Shape]
    #[inline(always)]
    pub fn iter_ref(&self) -> ArrayDefaultIteratorByRef<'_, ArrayImpl, NDIM> {
        ArrayDefaultIteratorByRef::new(self)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + Shape<NDIM>,
{
    /// Iterate through the array by mutable reference.
    ///
    /// The iterator always proceeds in column-major order.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    #[inline(always)]
    pub fn iter_mut(&mut self) -> ArrayDefaultIteratorMut<'_, ArrayImpl, NDIM> {
        ArrayDefaultIteratorMut::new(self)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessByValue<NDIM, Item = Item> + Shape<NDIM>,
{
    /// Iterate through the diagonal of the array by value.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn diag_iter_value(&self) -> ArrayDiagIteratorByValue<'_, ArrayImpl, NDIM> {
        ArrayDiagIteratorByValue::new(self)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessByRef<NDIM, Item = Item> + Shape<NDIM>,
{
    /// Iterate through the diagonal of the array by reference.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByRef]
    /// - [Shape]
    #[inline(always)]
    pub fn diag_iter_ref(&self) -> ArrayDiagIteratorByRef<'_, ArrayImpl, NDIM> {
        ArrayDiagIteratorByRef::new(self)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessMut<NDIM, Item = Item> + Shape<NDIM>,
{
    /// Iterate through the diagonal of the array by mutable reference.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByRef]
    /// - [Shape]
    #[inline(always)]
    pub fn diag_iter_mut(&mut self) -> ArrayDiagIteratorMut<'_, ArrayImpl, NDIM> {
        ArrayDiagIteratorMut::new(self)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut<Item = Item> + Shape<NDIM>,
{
    /// Copy values from another array in logical column-major order.
    ///
    /// # Panics
    ///
    /// Panics if the shapes differ.
    #[inline(always)]
    pub fn fill_from<ArrayImplOther>(&mut self, other: &Array<ArrayImplOther, NDIM>)
    where
        ArrayImplOther: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    {
        assert_eq!(self.shape(), other.shape());

        for (item, other_item) in self.iter_mut().zip(other.iter_value()) {
            *item = other_item;
        }
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    Const<NDIM>: ToUInt,
    <Const<NDIM> as ToUInt>::Output: Unsigned + NonZero,
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item>
        + UnsafeRandomAccessByValue<NDIM, Item = Item>
        + Shape<NDIM>,
{
    /// Create a new multislice iterator.
    ///
    /// Given an array `arr` with dimensions `[2, 3, 4, 5]`. Calling
    /// `self.multislice_iter` with `axes = [0, 2]` returns an iterator
    /// over values of the type `(indices, slice)`, where indices is a
    /// [2; usize] array taking all possible axis indices in axes `0` and `2`,
    /// and `slice` is the output of `arr.multislice([0, 2], [indices])`.
    pub fn multislice_iter<const SDIM: usize, const OUTDIM: usize>(
        &self,
        axes: [usize; SDIM],
    ) -> MultisliceIterator<'_, Item, ArrayImpl, NDIM, SDIM, OUTDIM>
    where
        Const<SDIM>: ToUInt,
        Const<OUTDIM>: ToUInt,
        <Const<SDIM> as ToUInt>::Output: Unsigned + NonZero,
        <Const<OUTDIM> as ToUInt>::Output: Unsigned + NonZero,
        NumberType<SDIM>: IsSmallerThan<NDIM>,
        PInt<U<OUTDIM>>: Add<PInt<U<SDIM>>, Output = PInt<U<NDIM>>>,
        PInt<U<NDIM>>: Sub<PInt<U<SDIM>>>,
    {
        MultisliceIterator::new(self, axes)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    Const<NDIM>: ToUInt,
    <Const<NDIM> as ToUInt>::Output: Unsigned + NonZero,
    ArrayImpl: UnsafeDisjointRandom1DAccessMut<Item = Item>
        + UnsafeRandomAccessMut<NDIM, Item = Item>
        + Shape<NDIM>,
{
    /// Create a new mutable multislice iterator.
    ///
    /// Given an array `arr` with dimensions `[2, 3, 4, 5]`. Calling
    /// `self.multislice_iter_mut` with `axes = [0, 2]` returns an iterator
    /// over values of the type `(indices, slice)`, where indices is a
    /// [2; usize] array taking all possible axis indices in axes `0` and `2`,
    /// and `slice` is the output of `arr.multislice([0, 2], [indices])`.
    pub fn multislice_iter_mut<const SDIM: usize, const OUTDIM: usize>(
        &mut self,
        axes: [usize; SDIM],
    ) -> MultisliceIteratorMut<'_, Item, ArrayImpl, NDIM, SDIM, OUTDIM>
    where
        Const<SDIM>: ToUInt,
        Const<OUTDIM>: ToUInt,
        <Const<SDIM> as ToUInt>::Output: Unsigned + NonZero,
        <Const<OUTDIM> as ToUInt>::Output: Unsigned + NonZero,
        NumberType<SDIM>: IsSmallerThan<NDIM>,
        PInt<U<OUTDIM>>: Add<PInt<U<SDIM>>, Output = PInt<U<NDIM>>>,
        PInt<U<NDIM>>: Sub<PInt<U<SDIM>>>,
    {
        MultisliceIteratorMut::new(self, axes)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + Shape<NDIM>,
{
    /// Fill elements in logical column-major order from an iterator.
    ///
    /// Filling stops when either the array or iterator is exhausted. Existing trailing array
    /// elements are unchanged when the iterator is short; excess iterator values are ignored.
    #[inline(always)]
    pub fn fill_from_iter<Iter>(&mut self, iter: Iter)
    where
        Iter: Iterator<Item = ArrayImpl::Item>,
    {
        for (item, other_item) in izip!(self.iter_mut(), iter) {
            *item = other_item;
        }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: ResizeInPlace<NDIM> + Shape<NDIM> + UnsafeDisjointRandom1DAccessMut,
{
    /// Fill from another array and resize if necessary.
    ///
    /// This method is especially useful together with [empty_array].
    ///
    /// #Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    #[inline(always)]
    pub fn fill_from_resize<ArrayImplOther>(&mut self, other: &Array<ArrayImplOther, NDIM>)
    where
        ArrayImplOther: Shape<NDIM> + UnsafeRandom1DAccessByValue<Item = ArrayImpl::Item>,
    {
        self.resize_in_place(other.shape());
        self.fill_from(other);
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + Shape<NDIM>,
{
    /// Fill array with a given value.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    #[inline(always)]
    pub fn fill_with_value(&mut self, value: ArrayImpl::Item) {
        for item in self.iter_mut() {
            *item = value;
        }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + Shape<NDIM>,
{
    /// Set the elements of the array to zero.
    pub fn set_zero(&mut self) {
        for item in self.iter_mut() {
            *item = Default::default();
        }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + UnsafeRandomAccessMut<NDIM> + Shape<NDIM>,
    ArrayImpl::Item: One,
{
    /// Set all off-diagonal elements to zero and the diagonal to one.
    pub fn set_identity(&mut self) {
        self.set_zero();
        self.diag_iter_mut().for_each(|elem| *elem = One::one());
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessByValue<NDIM> + Shape<NDIM>,
    ArrayImpl::Item: std::iter::Sum,
{
    /// Compute the sum of the diagonal values of the array.
    ///
    /// Note: The Item type must support the trait [std::iter::Sum].
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn trace(&self) -> ArrayImpl::Item {
        self.diag_iter_value().sum()
    }
}

impl<Item, ArrayImpl> Array<ArrayImpl, 1>
where
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<1>,
    ArrayImpl::Item: Conj<Output = Item>
        + std::ops::Mul<Output = ArrayImpl::Item>
        + std::ops::Add<Output = Item>,
{
    /// Compute the inner product of two 1d arrays.
    ///
    /// The elements of `other` are taken as conjugate.
    ///
    /// Returns `None` if the arrays are empty.
    ///
    /// Note: The Item type must support the traits [Conj], [std::iter::Sum] and [std::ops::Mul].
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn inner<ArrayImplOther>(&self, other: &Array<ArrayImplOther, 1>) -> Option<Item>
    where
        ArrayImplOther: UnsafeRandom1DAccessByValue<Item = Item> + Shape<1>,
    {
        assert_eq!(self.shape(), other.shape());
        izip!(self.iter_value(), other.iter_value())
            .map(|(x, y)| x * y.conj())
            .reduce(std::ops::Add::add)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    Item: Abs,
    <Item as Abs>::Output: Max<Output = <Item as Abs>::Output>,
{
    /// Compute the maximum absolute value over all elements.
    ///
    /// Note: The item type must support [Abs] and the output of [Abs]
    /// must support [Max].
    ///
    /// The function returns `None` if the array is empty.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn max_abs(&self) -> Option<<Item as Abs>::Output> {
        self.iter_value().map(|elem| elem.abs()).reduce(Max::max)
    }
}

impl<Item, ArrayImpl> Array<ArrayImpl, 1>
where
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<1>,
    Item: Abs,
    <Item as Abs>::Output: std::ops::Add<Output = <Item as Abs>::Output>,
{
    /// Compute the 1-norm of a 1d array.
    ///
    /// The function returns `None` if the array is empty.
    ///
    /// Note: The item type must support [Abs] and the output of [Abs] must
    /// support [std::ops::Add].
    ///
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn norm_1(&self) -> Option<<Item as Abs>::Output> {
        self.iter_value()
            .map(|elem| elem.abs())
            .reduce(std::ops::Add::add)
    }
}

impl<Item, ArrayImpl> Array<ArrayImpl, 1>
where
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<1>,
    Item: AbsSquare,
    <Item as AbsSquare>::Output: Sqrt<Output = <Item as AbsSquare>::Output>
        + std::ops::Add<Output = <Item as AbsSquare>::Output>,
{
    /// Compute the 2-norm of a 1d array.
    ///
    /// Note: The item type must support [AbsSquare]. The output of [AbsSquare]
    /// must support [std::ops::Add] and [Sqrt].
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn norm_2(&self) -> Option<<Item as AbsSquare>::Output> {
        self.iter_value()
            .map(|elem| elem.abs_square())
            .reduce(std::ops::Add::add)
            .map(|elem| elem.sqrt())
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandom1DAccessByValue<Item = Item> + Shape<NDIM>,
    Item: AbsSquare,
    <Item as AbsSquare>::Output: Sqrt<Output = <Item as AbsSquare>::Output>
        + std::ops::Add<Output = <Item as AbsSquare>::Output>
        + Copy
        + Default,
{
    /// Compute the Frobenius-Norm of a nd array.
    ///
    /// Note: The item type must support [AbsSquare]. The output of [AbsSquare]
    /// must support [std::ops::Add], [Sqrt], [Copy], and [Default].
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[inline(always)]
    pub fn norm_fro(&self) -> Option<<Item as AbsSquare>::Output> {
        self.r()
            .abs_square()
            .iter_value()
            .reduce(std::ops::Add::add)
            .map(|elem| elem.sqrt())
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandom1DAccessByValue + Shape<NDIM>,
{
    /// Convert an array into the new item type T.
    ///
    /// Note: It is required that `ArrayImpl::Item: Into<T>`.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    #[allow(clippy::type_complexity)]
    pub fn into_type<T>(
        self,
    ) -> Array<
        ArrayUnaryOperator<ArrayImpl::Item, T, ArrayImpl, fn(ArrayImpl::Item) -> T, NDIM>,
        NDIM,
    >
    where
        ArrayImpl::Item: Into<T>,
    {
        Array::new(ArrayUnaryOperator::new(self, |item| item.into()))
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: Shape<2> + UnsafeRandomAccessByValue<2>,
{
    /// Return a column iterator for a 2d array.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByValue]
    /// - [Shape]
    pub fn col_iter(&self) -> ColIterator<'_, ArrayImpl, 2> {
        ColIterator::new(self)
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: Shape<2> + UnsafeRandomAccessMut<2>,
{
    /// Return a mutable column iterator for a 2d array.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessMut]
    /// - [Shape]
    pub fn col_iter_mut(&mut self) -> ColIteratorMut<'_, ArrayImpl, 2> {
        ColIteratorMut::new(self)
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: Shape<2> + UnsafeRandomAccessByValue<2>,
{
    /// Return a row iterator for a 2d array.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessByValue]
    /// - [Shape]
    pub fn row_iter(&self) -> RowIterator<'_, ArrayImpl, 2> {
        RowIterator::new(self)
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: Shape<2> + UnsafeRandomAccessByValue<2>,
{
    /// Return a mutable row iterator for a 2d array.
    ///
    /// # Traits
    /// - [UnsafeRandomAccessMut]
    /// - [Shape]
    pub fn row_iter_mut(&mut self) -> RowIteratorMut<'_, ArrayImpl, 2> {
        RowIteratorMut::new(self)
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: UnsafeRandom1DAccessByValue + Shape<2>,
{
    /// Return an iterator of the form `(i, j, data)`.
    ///
    /// Here, `i` is the row, `j` is the column, and `data` is the associated element
    /// returned by value.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByValue]
    /// - [Shape]
    pub fn iter_aij_value(&self) -> impl Iterator<Item = ([usize; 2], ArrayImpl::Item)> + '_ {
        let iter = ArrayDefaultIteratorByValue::new(self);
        AsMultiIndex::multi_index(std::iter::Iterator::enumerate(iter), self.shape())
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: UnsafeRandom1DAccessByRef + Shape<2>,
{
    /// Return an iterator of the form `(i, j, &data)`.
    ///
    /// Here, `i` is the row, `j` is the column, and `&data` is the reference to the associated
    /// element.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByRef]
    /// - [Shape]
    pub fn iter_aij_ref(&self) -> impl Iterator<Item = ([usize; 2], &ArrayImpl::Item)> + '_ {
        let iter = ArrayDefaultIteratorByRef::new(self);
        AsMultiIndex::multi_index(std::iter::Iterator::enumerate(iter), self.shape())
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: UnsafeDisjointRandom1DAccessMut + Shape<2>,
{
    /// Return an iterator of the form `(i, j, &mut data)`.
    ///
    /// Here, `i` is the row, `j` is the column, and `&data` is the mutable reference to the associated
    /// element.
    ///
    /// # Traits
    /// - [UnsafeRandom1DAccessByRef]
    /// - [Shape]
    pub fn iter_aij_mut(
        &mut self,
    ) -> impl Iterator<Item = ([usize; 2], &mut ArrayImpl::Item)> + '_ {
        let shape = self.shape();
        let iter = ArrayDefaultIteratorMut::new(self);
        AsMultiIndex::multi_index(std::iter::Iterator::enumerate(iter), shape)
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Cast array to type `T`.
    ///
    /// The cast is done through [num::cast::cast] and source and target types need to
    /// support casting through that function.
    pub fn cast<Target>(self) -> Array<ArrayCast<Target, ArrayImpl, NDIM>, NDIM> {
        Array::new(ArrayCast::new(self))
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Coerce the array to a specific dimension.
    ///
    /// This is useful to coerce from a generic dimension parameter to
    /// a specific number of dimensions.
    pub fn coerce_dim<const CDIM: usize>(
        self,
    ) -> RlstResult<Array<CoerceArray<ArrayImpl, NDIM, CDIM>, CDIM>> {
        if CDIM == NDIM {
            // If the dimensions and item types match return a CoerceArray
            Ok(Array::new(CoerceArray::new(self)))
        } else {
            // Otherwise, we need to coerce the array.
            Err(RlstError::GeneralError(
                format!("Cannot coerce array: dimensions do not match {CDIM} != {NDIM}.")
                    .to_string(),
            ))
        }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM>,
{
    /// Permute axes of an array.
    ///
    /// For a valid permutation, `permutation[output_axis]` identifies the corresponding source
    /// axis. For example, `[1, 0, 2]` swaps the first two axes.
    ///
    /// # Panics
    ///
    /// Panics if an entry is outside `0..NDIM` or if an axis occurs more than once.
    /// Every source axis must occur exactly once.
    pub fn permute_axes(
        self,
        permutation: [usize; NDIM],
    ) -> Array<ArrayTranspose<ArrayImpl, NDIM>, NDIM> {
        Array::new(ArrayTranspose::new(self, permutation))
    }

    /// Transpose an array.
    ///
    /// The transpose of an n-dimensional array reverses the order of the axes.
    pub fn transpose(self) -> Array<ArrayTranspose<ArrayImpl, NDIM>, NDIM> {
        let mut permutation = [0; NDIM];

        for (ind, p) in (0..NDIM).rev().enumerate() {
            permutation[ind] = p;
        }

        self.permute_axes(permutation)
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    Item: RandScalar + RlstScalar,
    ArrayImpl: UnsafeDisjointRandom1DAccessMut<Item = Item> + Shape<NDIM>,
    StandardNormal: Distribution<Item::Real>,
    StandardUniform: Distribution<Item::Real>,
{
    /// Fill an array with normally distributed random numbers.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    /// - Item: [RandScalar] + [RlstScalar]
    pub fn fill_from_standard_normal<R: Rng>(&mut self, rng: &mut R) {
        let dist = StandardNormal;
        self.iter_mut()
            .for_each(|val| *val = <Item>::random_scalar(rng, &dist));
    }

    /// Fill an array with equally distributed random numbers.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    /// - Item: [RandScalar] + [RlstScalar]
    pub fn fill_from_equally_distributed<R: Rng>(&mut self, rng: &mut R) {
        let dist = StandardUniform;
        self.iter_mut()
            .for_each(|val| *val = <Item>::random_scalar(rng, &dist));
    }

    /// Fill an array with equally distributed random numbers using a given `seed`.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    /// - Item: [RandScalar] + [RlstScalar]
    pub fn fill_from_seed_equally_distributed(&mut self, seed: usize) {
        let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
        let dist = StandardUniform;
        self.iter_mut()
            .for_each(|val| *val = <Item>::random_scalar(&mut rng, &dist));
    }

    /// Fill an array with normally distributed random numbers using a given `seed`.
    ///
    /// # Traits
    /// - [UnsafeDisjointRandom1DAccessMut]
    /// - [Shape]
    /// - Item: [RandScalar] + [RlstScalar]
    pub fn fill_from_seed_normally_distributed(&mut self, seed: usize) {
        let mut rng = ChaCha8Rng::seed_from_u64(seed as u64);
        let dist = StandardNormal;
        self.iter_mut()
            .for_each(|val| *val = <Item>::random_scalar(&mut rng, &dist));
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Return a lazy view with one axis indexed in reverse.
    ///
    /// # Panics
    ///
    /// Panics if `axis >= NDIM`.
    pub fn reverse_axis(self, axis: usize) -> Array<ReverseAxis<ArrayImpl, NDIM>, NDIM> {
        assert!(axis < NDIM, "Axis out of bounds");
        Array::new(ReverseAxis::new(self, axis))
    }
}

impl<ArrayImpl, const ADIM: usize> Array<ArrayImpl, ADIM>
where
    ArrayImpl: Shape<ADIM>,
{
    /// Create a slice from a given array.
    ///
    /// Consider an array `arr` with shape `[a0, a1, a2, a3, ...]`. The function call
    /// `arr.slice(2, 3)` returns a one dimension smaller array indexed by `[a0, a1, 3, a3, ...]`.
    /// Hence, the dimension `2` has been fixed to always have the value `3.`
    ///
    /// # Examples
    ///
    /// If `arr` is a matrix then the first column of the matrix is obtained from
    /// `arr.slice(1, 0)`, while the third row of the matrix is obtained from
    /// `arr.slice(0, 2)`.
    pub fn slice<const OUTDIM: usize>(
        self,
        axis: usize,
        index: usize,
    ) -> Array<ArraySlice<ArrayImpl, ADIM, OUTDIM>, OUTDIM>
    where
        NumberType<ADIM>: IsGreaterByOne<OUTDIM>,
        NumberType<OUTDIM>: IsGreaterZero,
    {
        Array::new(ArraySlice::new(self, [axis, index]))
    }

    /// Create a multislice from a given array.
    ///
    /// A multislice works like [Array::slice] but allows the slicing along multiple dimensions at the same time.
    /// The `axes` array determines which axes are fixed and the `indices` array determines the value
    /// in each fixed axis. The dimension `SDIM` is the number of axes along which we slice. The parameter `OUTDIM`
    /// is the number of dimensions after slicing.
    pub fn multislice<const SDIM: usize, const OUTDIM: usize>(
        self,
        axes: [usize; SDIM],
        indices: [usize; SDIM],
    ) -> Array<Multislice<ArrayImpl, ADIM, SDIM, OUTDIM>, OUTDIM>
    where
        NumberType<SDIM>: IsSmallerThan<ADIM>,
        NumberDifference<ADIM, SDIM>: SubtractEqual<OUTDIM>,
    {
        Array::new(Multislice::new(self, axes, indices))
    }
}

impl<ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: Shape<2>,
{
    /// Return the row with index `row_index` from a two-dimensional array.
    pub fn row(self, row_index: usize) -> Array<ArraySlice<ArrayImpl, 2, 1>, 1> {
        self.slice::<1>(0, row_index)
    }

    /// Return the column with index `col_index` from a two-dimensional array.
    pub fn col(self, col_index: usize) -> Array<ArraySlice<ArrayImpl, 2, 1>, 1> {
        self.slice::<1>(1, col_index)
    }
}

impl<ArrayImpl: Shape<NDIM>, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Move the array into a subview specified by an `offset` and `shape` of the subview.
    ///
    /// The `offset` is the starting index of the subview and the `shape` is the number of indices
    /// in each dimension of the subview.
    pub fn into_subview(
        self,
        offset: [usize; NDIM],
        shape: [usize; NDIM],
    ) -> Array<ArraySubView<ArrayImpl, NDIM>, NDIM> {
        Array::new(ArraySubView::new(self, offset, shape))
    }
}

impl<Item, ArrayImpl1, ArrayImpl2, const NDIM: usize> MulAdd<Item, Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: BaseItem<Item = Item> + Shape<NDIM>,
    ArrayImpl2: BaseItem<Item = Item> + Shape<NDIM>,
    Item: MulAdd<Output = Item> + Copy,
{
    type Output = Array<MulAddImpl<ArrayImpl1, ArrayImpl2, Item, NDIM>, NDIM>;
    /// Compentwie form `self * a + b`, where `a` is a scalar and `b` is another array.
    /// The implementation depdends on the `MulAdd` trait from the `num` crate for the componets of
    /// the arrays.
    fn mul_add(
        self,
        a: Item,
        b: Array<ArrayImpl2, NDIM>,
    ) -> Array<MulAddImpl<ArrayImpl1, ArrayImpl2, Item, NDIM>, NDIM>
    where
        ArrayImpl1: BaseItem<Item = Item> + Shape<NDIM>,
        ArrayImpl2: BaseItem<Item = Item> + Shape<NDIM>,
        Item: MulAdd<Output = Item> + Copy,
    {
        Array::new(MulAddImpl::new(self, b, a))
    }
}

impl<ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::Add<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM>,
    ArrayImpl2: Shape<NDIM>,
{
    type Output = Array<ArrayAddition<ArrayImpl1, ArrayImpl2, NDIM>, NDIM>;

    #[inline(always)]
    fn add(self, rhs: Array<ArrayImpl2, NDIM>) -> Self::Output {
        Array::new(ArrayAddition::new(self, rhs))
    }
}

impl<Item, ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::AddAssign<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    ArrayImpl2: Shape<NDIM> + UnsafeRandom1DAccessByValue<Item = Item>,
    Item: std::ops::AddAssign,
{
    #[inline(always)]
    fn add_assign(&mut self, rhs: Array<ArrayImpl2, NDIM>) {
        assert_eq!(self.shape(), rhs.shape());
        for (item1, item2) in izip!(self.iter_mut(), rhs.iter_value()) {
            *item1 += item2;
        }
    }
}

impl<ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::Sub<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM>,
    ArrayImpl2: Shape<NDIM>,
{
    type Output = Array<ArraySubtraction<ArrayImpl1, ArrayImpl2, NDIM>, NDIM>;

    fn sub(self, rhs: Array<ArrayImpl2, NDIM>) -> Self::Output {
        Array::new(ArraySubtraction::new(self, rhs))
    }
}

impl<Item, ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::SubAssign<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    ArrayImpl2: Shape<NDIM> + UnsafeRandom1DAccessByValue<Item = Item>,
    Item: std::ops::SubAssign,
{
    #[inline(always)]
    fn sub_assign(&mut self, rhs: Array<ArrayImpl2, NDIM>) {
        assert_eq!(self.shape(), rhs.shape());
        for (item1, item2) in izip!(self.iter_mut(), rhs.iter_value()) {
            *item1 -= item2;
        }
    }
}

impl<Item, ArrayImpl, const NDIM: usize> std::ops::Neg for Array<ArrayImpl, NDIM>
where
    ArrayImpl: BaseItem<Item = Item>,
    Item: std::ops::Neg<Output = Item>,
{
    type Output = Array<ArrayNeg<ArrayImpl, NDIM>, NDIM>;

    fn neg(self) -> Self::Output {
        Array::new(ArrayNeg::new(self))
    }
}

impl<ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::Div<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM>,
    ArrayImpl2: Shape<NDIM>,
{
    type Output = Array<CmpWiseDivision<ArrayImpl1, ArrayImpl2, NDIM>, NDIM>;

    fn div(self, rhs: Array<ArrayImpl2, NDIM>) -> Self::Output {
        Array::new(CmpWiseDivision::new(self, rhs))
    }
}

impl<Item, ArrayImpl, const NDIM: usize> std::ops::Div<Item> for Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM> + BaseItem<Item = Item>,
    Item: Recip<Output = Item> + std::ops::Div<Output = Item>,
{
    type Output = Array<ArrayScalarMult<Item, ArrayImpl, NDIM>, NDIM>;

    fn div(self, rhs: Item) -> Self::Output {
        Array::new(ArrayScalarMult::new(rhs.recip(), self))
    }
}

impl<Item, ArrayImpl, const NDIM: usize> std::ops::DivAssign<Item> for Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    Item: std::ops::DivAssign + Copy,
{
    fn div_assign(&mut self, rhs: Item) {
        for item in self.iter_mut() {
            *item /= rhs;
        }
    }
}

impl<ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::Mul<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM>,
    ArrayImpl2: Shape<NDIM>,
{
    type Output = Array<CmpWiseProduct<ArrayImpl1, ArrayImpl2, NDIM>, NDIM>;

    fn mul(self, rhs: Array<ArrayImpl2, NDIM>) -> Self::Output {
        Array::new(CmpWiseProduct::new(self, rhs))
    }
}

impl<Item, ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::MulAssign<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    ArrayImpl2: Shape<NDIM> + UnsafeRandom1DAccessByValue<Item = Item>,
    Item: std::ops::MulAssign,
{
    fn mul_assign(&mut self, rhs: Array<ArrayImpl2, NDIM>) {
        for (item1, item2) in izip!(self.iter_mut(), rhs.iter_value()) {
            *item1 *= item2;
        }
    }
}

impl<Item, ArrayImpl1, ArrayImpl2, const NDIM: usize> std::ops::DivAssign<Array<ArrayImpl2, NDIM>>
    for Array<ArrayImpl1, NDIM>
where
    ArrayImpl1: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    ArrayImpl2: Shape<NDIM> + UnsafeRandom1DAccessByValue<Item = Item>,
    Item: std::ops::DivAssign,
{
    fn div_assign(&mut self, rhs: Array<ArrayImpl2, NDIM>) {
        for (item1, item2) in izip!(self.iter_mut(), rhs.iter_value()) {
            *item1 /= item2;
        }
    }
}

macro_rules! impl_scalar_mult {
    ($ScalarType:ty) => {
        impl<ArrayImpl, const NDIM: usize> std::ops::Mul<Array<ArrayImpl, NDIM>> for $ScalarType {
            type Output = Array<ArrayScalarMult<$ScalarType, ArrayImpl, NDIM>, NDIM>;

            fn mul(self, rhs: Array<ArrayImpl, NDIM>) -> Self::Output {
                Array::new(ArrayScalarMult::new(self, rhs))
            }
        }

        impl<ArrayImpl, const NDIM: usize> std::ops::Mul<$ScalarType> for Array<ArrayImpl, NDIM>
        where
            ArrayImpl: Shape<NDIM> + BaseItem<Item = $ScalarType>,
        {
            type Output = Array<ArrayScalarMult<$ScalarType, ArrayImpl, NDIM>, NDIM>;

            fn mul(self, rhs: $ScalarType) -> Self::Output {
                Array::new(ArrayScalarMult::new(rhs, self))
            }
        }
    };
}

impl_scalar_mult!(f64);
impl_scalar_mult!(f32);
impl_scalar_mult!(c64);
impl_scalar_mult!(c32);
impl_scalar_mult!(usize);
impl_scalar_mult!(i8);
impl_scalar_mult!(i16);
impl_scalar_mult!(i32);
impl_scalar_mult!(i64);
impl_scalar_mult!(u8);
impl_scalar_mult!(u16);
impl_scalar_mult!(u32);
impl_scalar_mult!(u64);

impl<Item, ArrayImpl, const NDIM: usize> std::ops::MulAssign<Item> for Array<ArrayImpl, NDIM>
where
    ArrayImpl: Shape<NDIM> + UnsafeDisjointRandom1DAccessMut<Item = Item>,
    Item: std::ops::MulAssign + Copy,
{
    fn mul_assign(&mut self, rhs: Item) {
        for item in self.iter_mut() {
            *item *= rhs;
        }
    }
}

impl<ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM> {
    /// Create a new array by applying the unitary operator `op` to each element of `self`.
    pub fn unary_op<OpItem, OpTarget, Op: Fn(OpItem) -> OpTarget>(
        self,
        op: Op,
    ) -> Array<ArrayUnaryOperator<OpItem, OpTarget, ArrayImpl, Op, NDIM>, NDIM> {
        Array::new(ArrayUnaryOperator::new(self, op))
    }
}

impl<Item: Default + Copy + std::ops::Mul<Output = Item>, ArrayImpl, const NDIM: usize>
    Array<ArrayImpl, NDIM>
where
    ArrayImpl: BaseItem<Item = Item>,
{
    /// Multiple the array with a given `scalar`.
    ///
    /// Note: The `Item` type must support [std::ops::Mul].
    ///
    pub fn scalar_mul(self, scalar: Item) -> Array<ArrayScalarMult<Item, ArrayImpl, NDIM>, NDIM> {
        Array::new(ArrayScalarMult::new(scalar, self))
    }
}

macro_rules! impl_unary_op_trait {
    ($name:ident, $method_name:ident) => {
        paste! {

        use crate::traits::number_traits::$name;
        impl<Item: $name, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
            where
                ArrayImpl: BaseItem<Item = Item>,
            {
                #[inline(always)]
                #[doc = "Componentwise apply `" $method_name "` to the array."]
                pub fn $method_name(self) -> Array<ArrayUnaryOperator<Item, <Item as $name>::Output, ArrayImpl, fn(Item) -> <Item as $name>::Output, NDIM>, NDIM> {
                    self.unary_op(|x| x.$method_name())
                }
            }
        }

    };
}

impl_unary_op_trait!(Conj, conj);
impl_unary_op_trait!(Abs, abs);
impl_unary_op_trait!(Square, square);
impl_unary_op_trait!(AbsSquare, abs_square);
impl_unary_op_trait!(Sqrt, sqrt);
impl_unary_op_trait!(Exp, exp);
impl_unary_op_trait!(Ln, ln);
impl_unary_op_trait!(Recip, recip);
impl_unary_op_trait!(Sin, sin);
impl_unary_op_trait!(Cos, cos);
impl_unary_op_trait!(Tan, tan);
impl_unary_op_trait!(Asin, asin);
impl_unary_op_trait!(Acos, acos);
impl_unary_op_trait!(Atan, atan);
impl_unary_op_trait!(Sinh, sinh);
impl_unary_op_trait!(Cosh, cosh);
impl_unary_op_trait!(Tanh, tanh);
impl_unary_op_trait!(Asinh, asinh);
impl_unary_op_trait!(Acosh, acosh);
impl_unary_op_trait!(Atanh, atanh);

impl<Item, ArrayImplX, ArrayImplY, ArrayImpl>
    AsMatrixApply<Array<ArrayImplX, 2>, Array<ArrayImplY, 2>> for Array<ArrayImpl, 2>
where
    Item: Gemm + Copy,
    ArrayImplX: RawAccess<Item = Item> + Stride<2> + Shape<2>,
    ArrayImplY: RawAccessMut<Item = Item> + Stride<2> + Shape<2>,
    ArrayImpl: RawAccess<Item = Item> + Stride<2> + Shape<2>,
{
    fn apply(
        &self,
        alpha: Self::Item,
        x: &Array<ArrayImplX, 2>,
        beta: Self::Item,
        y: &mut Array<ArrayImplY, 2>,
    ) {
        let stride_a = self.stride();
        let stride_x = x.stride();
        let stride_y = y.stride();

        let shape_a = self.shape();
        let shape_x = x.shape();
        let shape_y = y.shape();

        assert_eq!(
            shape_a[0], shape_y[0],
            "`y` has incompatible shape {shape_y:#?} with `self` {shape_a:#?}."
        );

        assert_eq!(
            shape_a[1], shape_x[0],
            "`x` has incompatible shape {shape_x:#?} with `self` {shape_a:#?}."
        );

        assert_eq!(
            shape_y[1], shape_x[1],
            "`x` has incompatible shape {shape_x:#?} with `y` {shape_y:#?}."
        );

        let m = shape_a[0];
        let n = shape_x[1];
        let k = shape_a[1];

        <Item as Gemm>::gemm(
            TransMode::NoTrans,
            TransMode::NoTrans,
            m,
            n,
            k,
            alpha,
            self.data().unwrap(),
            stride_a[0],
            stride_a[1],
            x.data().unwrap(),
            stride_x[0],
            stride_x[1],
            beta,
            y.data_mut().unwrap(),
            stride_y[0],
            stride_y[1],
        );
    }
}

impl<Item, ArrayImplX, ArrayImplY, ArrayImpl>
    AsMatrixApply<Array<ArrayImplX, 1>, Array<ArrayImplY, 1>> for Array<ArrayImpl, 2>
where
    Item: Gemm + Copy,
    ArrayImplX: RawAccess<Item = Item> + Stride<1> + Shape<1>,
    ArrayImplY: RawAccessMut<Item = Item> + Stride<1> + Shape<1>,
    ArrayImpl: RawAccess<Item = Item> + Stride<2> + Shape<2>,
{
    fn apply(
        &self,
        alpha: Self::Item,
        x: &Array<ArrayImplX, 1>,
        beta: Self::Item,
        y: &mut Array<ArrayImplY, 1>,
    ) {
        self.apply(
            alpha,
            &x.r().insert_empty_axis::<2>(AxisPosition::Back),
            beta,
            &mut y.r_mut().insert_empty_axis::<2>(AxisPosition::Back),
        );
    }
}

impl<Item, ArrayImpl> Array<ArrayImpl, 2>
where
    ArrayImpl: RawAccess<Item = Item> + Stride<2> + Shape<2>,
    Item: Gemm + Copy + Default + One + Zero,
{
    /// Compute the matrix-matrix product of `self` with `other`.
    pub fn dot<ArrayImplOther, const NDIM: usize>(
        &self,
        other: &Array<ArrayImplOther, NDIM>,
    ) -> DynArray<Item, NDIM>
    where
        ArrayImplOther: RawAccess<Item = Item> + Shape<NDIM> + Stride<NDIM>,
    {
        let a_shape = self.shape();
        let x_shape = other.shape();

        let mut out = empty_array::<Item, NDIM>();

        if NDIM == 1 {
            let mut out = out.r_mut().coerce_dim::<1>().unwrap();
            out.resize_in_place([a_shape[0]]);

            self.apply(
                Item::one(),
                &other.r().coerce_dim::<1>().unwrap(),
                Item::zero(),
                &mut out,
            );
        } else if NDIM == 2 {
            let mut out = out.r_mut().coerce_dim::<2>().unwrap();
            out.resize_in_place([a_shape[0], x_shape[1]]);

            self.apply(
                Item::one(),
                &other.r().coerce_dim::<2>().unwrap(),
                Item::zero(),
                &mut out,
            )
        } else {
            panic!("NDIM = {NDIM} not supported.");
        }

        out
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessMut<NDIM, Item = Item>,
    Item: Copy,
{
    /// Swap the elements at the positions `pos1` and `pos2`
    ///
    /// # Safety
    ///
    /// `pos1` and `pos2` must not be out of bounds.
    #[inline(always)]
    pub unsafe fn swap_unsafe(&mut self, pos1: [usize; NDIM], pos2: [usize; NDIM]) {
        let elem1 = *unsafe { self.get_unchecked_mut(pos1) };
        let elem2 = *unsafe { self.get_unchecked_mut(pos2) };

        *unsafe { self.get_unchecked_mut(pos1) } = elem2;
        *unsafe { self.get_unchecked_mut(pos2) } = elem1;
    }
}

impl<Item, ArrayImpl, const NDIM: usize> Array<ArrayImpl, NDIM>
where
    ArrayImpl: UnsafeRandomAccessMut<NDIM, Item = Item> + Shape<NDIM>,
    Item: Copy,
{
    /// Swap the elements at the positions `pos1` and `pos2`.
    ///
    /// Returns an error if either `pos1` or `pos2` is out of bounds.
    #[inline(always)]
    pub fn swap(&mut self, pos1: [usize; NDIM], pos2: [usize; NDIM]) -> RlstResult<()> {
        let shape = self.shape();
        if !check_multi_index_in_bounds(pos1, shape) {
            Err(RlstError::GeneralError(format!(
                "Index `pos1` = {:#?} out of bounds.",
                pos1
            )))
        } else if !check_multi_index_in_bounds(pos2, shape) {
            Err(RlstError::GeneralError(format!(
                "Index `pos2` = {:#?} out of bounds.",
                pos2
            )))
        } else {
            unsafe {
                self.swap_unsafe(pos1, pos2);
            }
            Ok(())
        }
    }
}

impl<Item> ScalarAsArray for Item
where
    Item: Default + Copy,
{
    fn as_array<const NDIM: usize>(&self) -> StaticArray<Self, NDIM, 1> {
        let mut arr = Array::new(BaseArray::new(ArrayContainer::<Item, 1>::new(), [1; NDIM]));
        *unsafe { arr.get_unchecked_mut([0; NDIM]) } = *self;
        arr
    }
}

impl<Item, const NDIM: usize> StaticArray<Item, NDIM, 1>
where
    Item: Copy + Default,
{
    /// Create an empty 1-element array of the given dimension.
    pub fn one_element_array() -> Self {
        Array::new(BaseArray::new(ArrayContainer::<Item, 1>::new(), [1; NDIM]))
    }
}

macro_rules! impl_linspace_float {
    ($dtype:ty) => {
        impl<ArrayImpl> Linspace<$dtype> for Array<ArrayImpl, 1>
        where
            ArrayImpl: MutableArrayImpl<$dtype, 1>,
        {
            fn linspace(&mut self, a: $dtype, b: $dtype) {
                let n = self.len() - 1;

                assert!(b > a, "`linspace` requires `{b} = b > a = {a} ");
                assert!(n > 1, "`linspace` requires `{n} = self.len() > 1");

                let delta = (b - a) / (n as $dtype);

                for (ind, elem) in self.iter_mut().enumerate().take(n) {
                    *elem = a + delta * ind as $dtype;
                }

                self[[n]] = b;
            }
        }
    };
}

impl_linspace_float!(f32);
impl_linspace_float!(f64);

#[cfg(test)]
mod test {

    use approx::assert_relative_eq;

    use crate::assert_array_relative_eq;

    use super::*;

    #[test]
    pub fn test_add() {
        let a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![2.5, 4.3, 7.0].into();

        crate::assert_array_relative_eq!((a.r() + b.r()).eval(), expected, 1E-10);
    }

    #[test]
    pub fn test_add_assign() {
        let mut a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![2.5, 4.3, 7.0].into();

        a += b;

        crate::assert_array_relative_eq!(a, expected, 1E-10);
    }

    #[test]
    pub fn test_sub() {
        let a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![-0.5, -0.3, -1.0].into();

        crate::assert_array_relative_eq!((a.r() - b.r()).eval(), expected, 1E-10);
    }

    #[test]
    pub fn test_sub_assign() {
        let mut a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![-0.5, -0.3, -1.0].into();

        a -= b;

        crate::assert_array_relative_eq!(a, expected, 1E-10);
    }

    #[test]
    pub fn test_cmp_mul() {
        let a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![1.5, 4.6, 12.0].into();

        crate::assert_array_relative_eq!(a.r() * b.r(), expected, 1E-10);
    }

    #[test]
    pub fn test_cmp_mul_assign() {
        let mut a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let b: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();
        let expected: DynArray<_, 1> = vec![1.5, 4.6, 12.0].into();

        a *= b;

        crate::assert_array_relative_eq!(a, expected, 1E-10);
    }

    #[test]
    pub fn test_scalar_mul() {
        let a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let expected: DynArray<_, 1> = vec![2.0, 4.0, 6.0].into();

        crate::assert_array_relative_eq!(2.0_f64 * a.r(), expected, 1E-10);
    }

    #[test]
    pub fn test_scalar_mul_assign() {
        let mut a: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let expected: DynArray<_, 1> = vec![2.0, 4.0, 6.0].into();

        a *= 2.0;

        crate::assert_array_relative_eq!(a.r(), expected, 1E-10);
    }

    #[test]
    pub fn test_cmp_div() {
        let a: DynArray<_, 1> = vec![1.5, 4.6, 12.0].into();
        let b: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let expected: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();

        crate::assert_array_relative_eq!(a.r() / b.r(), expected, 1E-10);
    }

    #[test]
    pub fn test_cmp_div_assign() {
        let mut a: DynArray<_, 1> = vec![1.5, 4.6, 12.0].into();
        let b: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();
        let expected: DynArray<_, 1> = vec![1.5, 2.3, 4.0].into();

        a /= b;

        crate::assert_array_relative_eq!(a, expected, 1E-10);
    }

    #[test]
    pub fn test_scalar_div() {
        let a: DynArray<_, 1> = vec![2.0, 4.0, 6.0].into();
        let expected: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();

        crate::assert_array_relative_eq!(a.r() / 2.0, expected, 1E-10);
    }

    #[test]
    pub fn test_scalar_div_assign() {
        let mut a: DynArray<_, 1> = vec![2.0, 4.0, 6.0].into();
        let expected: DynArray<_, 1> = vec![1.0, 2.0, 3.0].into();

        a /= 2.0;

        crate::assert_array_relative_eq!(a.r(), expected, 1E-10);
    }

    #[test]
    pub fn test_into_subview() {
        let mut rng = ChaCha8Rng::seed_from_u64(0);
        let mut a = DynArray::<f64, 3>::from_shape([7, 5, 9]);
        a.fill_from_equally_distributed(&mut rng);

        let view = a.r().into_subview([1, 0, 3], [2, 3, 4]);

        assert_eq!(view[[1, 2, 3]], a[[2, 2, 6]])
    }

    #[test]
    pub fn test_apply() {
        let mut rng = ChaCha8Rng::seed_from_u64(0);

        let alpha = 1.5;
        let beta = 3.6;

        let mut a = DynArray::<f64, 2>::from_shape([3, 2]);
        a.fill_from_equally_distributed(&mut rng);

        let mut x = DynArray::<f64, 1>::from_shape([2]);
        x.fill_from_equally_distributed(&mut rng);

        let mut y = DynArray::<f64, 1>::from_shape([3]);
        y.fill_from_equally_distributed(&mut rng);
        let y2 = y.eval();

        a.apply(alpha, &x, beta, &mut y);

        for (row_index, row) in a.row_iter().enumerate() {
            assert_relative_eq!(
                alpha * row.inner(&x).unwrap() + beta * y2[[row_index]],
                y[[row_index]],
                epsilon = 1E-10
            );
        }

        let mut x = DynArray::<f64, 2>::from_shape([2, 5]);
        x.fill_from_equally_distributed(&mut rng);

        let mut y = DynArray::<f64, 2>::from_shape([3, 5]);
        y.fill_from_equally_distributed(&mut rng);
        let y2 = y.eval();

        a.apply(alpha, &x, beta, &mut y);

        for (row_index, row) in a.row_iter().enumerate() {
            for (col_index, col) in x.col_iter().enumerate() {
                assert_relative_eq!(
                    alpha * row.inner(&col).unwrap() + beta * y2[[row_index, col_index]],
                    y[[row_index, col_index]],
                    epsilon = 1E-10
                );
            }
        }
    }

    #[test]
    pub fn test_dot() {
        let mut rng = ChaCha8Rng::seed_from_u64(0);

        let mut a = DynArray::<f64, 2>::from_shape([3, 2]);
        a.fill_from_equally_distributed(&mut rng);

        let mut x = DynArray::<f64, 1>::from_shape([2]);
        x.fill_from_equally_distributed(&mut rng);

        let mut y = DynArray::<f64, 1>::from_shape([3]);

        a.apply(1.0, &x, 0.0, &mut y);

        crate::assert_array_relative_eq!(y, a.dot(&x), 1E-10);

        let mut x = DynArray::<f64, 2>::from_shape([2, 5]);
        x.fill_from_equally_distributed(&mut rng);

        let mut y = DynArray::<f64, 2>::from_shape([3, 5]);

        a.apply(1.0, &x, 0.0, &mut y);

        crate::assert_array_relative_eq!(y, a.dot(&x), 1E-10);
    }

    #[test]
    pub fn test_swap() {
        let mut a = DynArray::<usize, 1>::from_shape([2]);
        a[[0]] = 1;
        a[[1]] = 2;

        a.swap([0], [1]).unwrap();
        assert_eq!(a[[0]], 2);
        assert_eq!(a[[1]], 1);
    }

    #[test]
    pub fn test_multislice_iterator() {
        let mut arr = DynArray::<f64, _>::from_shape([2, 3, 4, 5]);
        arr.fill_from_seed_equally_distributed(0);

        let mut count = 0;
        for (indices, slice) in arr.r().multislice_iter::<_, 2>([2, 3]) {
            assert_array_relative_eq!(slice, arr.r().multislice::<_, 2>([2, 3], indices), 1E-12);
            count += 1;
        }
        assert_eq!(count, 20);
    }

    #[test]
    pub fn test_multislice_iterator_mut() {
        let mut arr = DynArray::<f64, _>::from_shape([2, 3, 4, 5]);
        arr.fill_from_seed_equally_distributed(0);
        let expected = arr.eval();

        let mut count = 0;
        for (indices, slice) in arr.r_mut().multislice_iter_mut::<_, 2>([2, 3]) {
            assert_array_relative_eq!(
                slice,
                expected.r().multislice::<_, 2>([2, 3], indices),
                1E-12
            );
            count += 1;
        }
        assert_eq!(count, 20);
    }
}