strided-basic 0.15.0

Shared typed strided CPU primitives and copy/reduction execution.
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
//! Allocation-free copy/axpy over borrowed raw strided layouts.
//!
//! The map/zip kernels build a traversal plan per call; for small replay
//! copies that fixed cost dominates. These entry points take
//! [`RawStridedRef`]/[`RawStridedMut`], fuse the stride pair into a loop nest
//! (inline storage for fused ranks at most [`RAW_FUSED_RANK_LIMIT`], a stack
//! layout bounded by the moving-axis count above that), and run plain loops -
//! no view plan, no cache, and no per-element allocation on any call path; the
//! `replay_*_raw` entries allocate nothing at any rank on a serial token.
//! Higher *original* ranks are normalized and fused before that choice is
//! made, so they no longer leave the fused replay.

use crate::cost::KernelClass;
use crate::{ElementOpApply, Exec, RawStridedMut, RawStridedRef, Result};
use core::mem::MaybeUninit;
use core::num::NonZeroUsize;
use core::ops::{Add, Mul};

/// Rank up to which a fused loop nest is stored inline.
///
/// It selects the traversal: a layout of at most this many axes replays through
/// the inline loop nest, a longer one through the out-of-line wide loop. It
/// does not decide allocation for the `replay_*_raw` entries, which allocate
/// nothing at any rank on a serial token (see [`replay_copy_raw`]).
///
/// The stateless [`copy_scale_raw`] family and the compilation of
/// [`crate::CopyPlan`] fuse any rank. An *original* rank above this limit needs
/// one transient fusion scratch buffer there even when the fused layout still
/// fits inline, because fusion happens before the representation is chosen.
pub const RAW_FUSED_RANK_LIMIT: usize = 8;

/// Capacity of the stack storage of the wide replay route.
///
/// A replay reaches its loops only with a checked, nonzero element count, and
/// every axis of extent above 1 at least doubles that count, so
/// `2^m <= total <= usize::MAX` bounds the `m` moving axes by
/// `usize::BITS - 1`. Extent-1 axes are dropped before the bound is used: their
/// coordinate is 0 throughout the walk, so dropping them changes neither the
/// slots nor their column-major order.
pub(crate) const MAX_MOVING_AXES: usize = usize::BITS as usize;

/// One fused axis, used while sorting and merging axes and when a layout has to
/// spill beyond [`RAW_FUSED_RANK_LIMIT`].
#[derive(Clone, Copy, Debug)]
pub(crate) struct FusedAxis {
    pub(crate) dim: usize,
    pub(crate) dst: isize,
    pub(crate) src: isize,
}

const EMPTY_AXIS: FusedAxis = FusedAxis {
    dim: 1,
    dst: 0,
    src: 0,
};

/// Stack-allocated fused stride pair (axes ordered by destination stride,
/// adjacent contiguous axes merged). Built once and replayed by both the
/// per-call raw kernels and the prepared [`crate::CopyPlan`].
///
/// This is the representation every call site replays through, so it keeps the
/// exact shape, size and `Copy`-ness it had before high-rank fusion existed.
#[derive(Clone, Copy, Debug)]
pub(crate) struct FusedPairLayout {
    pub(crate) rank: usize,
    pub(crate) dims: [usize; RAW_FUSED_RANK_LIMIT],
    pub(crate) dst_strides: [isize; RAW_FUSED_RANK_LIMIT],
    pub(crate) src_strides: [isize; RAW_FUSED_RANK_LIMIT],
}

impl FusedPairLayout {
    /// An empty rank-zero layout (one element at the base offset).
    ///
    /// Used as the neutral value when an inline `TinyVec<[CopyPlan; N]>` is
    /// default-initialized; it is never executed as a real plan.
    fn empty() -> Self {
        Self {
            rank: 0,
            dims: [1; RAW_FUSED_RANK_LIMIT],
            dst_strides: [0; RAW_FUSED_RANK_LIMIT],
            src_strides: [0; RAW_FUSED_RANK_LIMIT],
        }
    }

    fn from_axes(axes: &[FusedAxis]) -> Self {
        debug_assert!(axes.len() <= RAW_FUSED_RANK_LIMIT);
        let mut layout = Self {
            rank: axes.len(),
            dims: [1; RAW_FUSED_RANK_LIMIT],
            dst_strides: [0; RAW_FUSED_RANK_LIMIT],
            src_strides: [0; RAW_FUSED_RANK_LIMIT],
        };
        for (slot, axis) in layout.dims[..axes.len()].iter_mut().zip(axes) {
            *slot = axis.dim;
        }
        for (slot, axis) in layout.dst_strides[..axes.len()].iter_mut().zip(axes) {
            *slot = axis.dst;
        }
        for (slot, axis) in layout.src_strides[..axes.len()].iter_mut().zip(axes) {
            *slot = axis.src;
        }
        layout
    }
}

/// A fused pair traversal of any rank.
///
/// Fused ranks at most [`RAW_FUSED_RANK_LIMIT`] use the inline layout; longer
/// layouts keep their axes in one `Vec`. That storage is sized by the original
/// rank (the fusion scratch is reused, and `truncate` keeps its capacity), never
/// by the tensor's element count.
#[derive(Clone, Debug)]
pub(crate) enum PairTraversal {
    Inline(FusedPairLayout),
    Spilled(Vec<FusedAxis>),
}

impl Default for FusedPairLayout {
    fn default() -> Self {
        Self::empty()
    }
}

impl Default for PairTraversal {
    fn default() -> Self {
        Self::empty()
    }
}

impl PairTraversal {
    /// The empty inline layout, used as a neutral default.
    #[inline]
    fn empty() -> Self {
        Self::Inline(FusedPairLayout::empty())
    }

    /// Run `f` on the replay route of this traversal: its axes with the cache
    /// tiles of destination element `D` and source element `S`, or no tiles
    /// when the column-major walk is kept.
    ///
    /// The one decision entry point for both storage shapes, so a plan and a
    /// replay entry ask the same question whatever the fused rank. A spilled
    /// traversal decides in [`with_spilled_route`], whose stack frame holds the
    /// wide tiles while `f` runs.
    pub(crate) fn with_route<D, S, R>(&self, f: impl FnOnce(Route<'_>) -> R) -> R {
        match self {
            Self::Inline(layout) => {
                let tiles = pair_tiles::<D, S>(layout);
                f(Route::Inline {
                    layout,
                    tiles: tiles.as_ref(),
                })
            }
            Self::Spilled(axes) => with_spilled_route::<D, S, R>(axes, f),
        }
    }

    /// The cache tiles of this traversal, copied out of its route.
    #[cfg(test)]
    pub(crate) fn tiles<D, S>(&self) -> Option<Tiles> {
        self.with_route::<D, S, _>(|route| route.snapshot())
    }

    /// Whether [`Self::with_route`] can tile for any element types: `false`
    /// when the traversal covers at most one element or has fewer than two
    /// axes of extent above 1, the exits [`pair_tiles`] and
    /// [`with_spilled_route`] take before they look at an element size. Such
    /// a traversal is one run, whose order no block vector can change.
    pub(crate) fn may_tile(&self) -> bool {
        let (total, moving) = match self {
            Self::Inline(layout) => (
                fused_total(layout),
                layout.dims[..layout.rank]
                    .iter()
                    .filter(|&&dim| dim != 1)
                    .count(),
            ),
            Self::Spilled(axes) => (
                spilled_total(axes),
                axes.iter().filter(|axis| axis.dim != 1).count(),
            ),
        };
        total > 1 && moving >= 2
    }

    /// The inline layout, or `None` when the traversal spilled.
    #[inline]
    pub(crate) fn inline(&self) -> Option<&FusedPairLayout> {
        match self {
            Self::Inline(layout) => Some(layout),
            Self::Spilled(_) => None,
        }
    }

    /// Number of fused axes.
    #[cfg(test)]
    pub(crate) fn rank(&self) -> usize {
        match self {
            Self::Inline(layout) => layout.rank,
            Self::Spilled(axes) => axes.len(),
        }
    }
}

/// Sort `dims`/`dst_strides`/`src_strides` by destination stride, drop size-1
/// axes, and merge axes that are contiguous in both layouts.
///
/// Returns the fused rank written to `scratch[..rank]`. A zero extent collapses
/// to a single zero-length axis, which every replay treats as an empty range.
fn fuse_axes(
    scratch: &mut [FusedAxis],
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
) -> usize {
    debug_assert!(scratch.len() >= dims.len());
    let mut rank = 0usize;
    for axis in 0..dims.len() {
        if dims[axis] == 1 {
            continue;
        }
        if dims[axis] == 0 {
            scratch[0] = FusedAxis {
                dim: 0,
                dst: 0,
                src: 0,
            };
            return 1;
        }
        let entry = FusedAxis {
            dim: dims[axis],
            dst: dst_strides[axis],
            src: src_strides[axis],
        };
        let mut position = rank;
        while position > 0 && scratch[position - 1].dst > entry.dst {
            scratch[position] = scratch[position - 1];
            position -= 1;
        }
        scratch[position] = entry;
        rank += 1;
    }
    if rank == 0 {
        scratch[0] = EMPTY_AXIS;
        return 1;
    }
    let mut fused = 0usize;
    for axis in 1..rank {
        // A merged extent that overflows (possible for a stride-0 broadcast
        // whose element count exceeds usize) leaves the axes unfused.
        let merged = isize::try_from(scratch[fused].dim)
            .ok()
            .filter(|&extent| {
                scratch[fused].dst.checked_mul(extent) == Some(scratch[axis].dst)
                    && scratch[fused].src.checked_mul(extent) == Some(scratch[axis].src)
            })
            .and_then(|_| scratch[fused].dim.checked_mul(scratch[axis].dim));
        if let Some(merged) = merged {
            scratch[fused].dim = merged;
        } else {
            fused += 1;
            scratch[fused] = scratch[axis];
        }
    }
    fused + 1
}

/// Fuse a raw stride pair into a traversal of any rank.
///
/// Inline when the fused rank is at most [`RAW_FUSED_RANK_LIMIT`], otherwise one
/// rank-bounded spill. An original rank above the limit uses a transient scratch
/// buffer even when the fused layout still fits inline, so that fusion happens
/// before the representation is chosen.
pub(crate) fn fuse_pair_traversal(
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
) -> PairTraversal {
    if dims.len() <= RAW_FUSED_RANK_LIMIT {
        let mut scratch = [EMPTY_AXIS; RAW_FUSED_RANK_LIMIT];
        let rank = fuse_axes(&mut scratch, dims, dst_strides, src_strides);
        debug_assert!(rank <= RAW_FUSED_RANK_LIMIT);
        return PairTraversal::Inline(FusedPairLayout::from_axes(&scratch[..rank]));
    }
    let mut scratch = vec![EMPTY_AXIS; dims.len()];
    let rank = fuse_axes(&mut scratch, dims, dst_strides, src_strides);
    scratch.truncate(rank);
    if rank <= RAW_FUSED_RANK_LIMIT {
        PairTraversal::Inline(FusedPairLayout::from_axes(&scratch))
    } else {
        PairTraversal::Spilled(scratch)
    }
}

impl PairTraversal {
    /// The traversal [`with_given_route`] replays for the given axes, as an
    /// owned value for the tests.
    #[cfg(test)]
    pub(crate) fn given(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> Self {
        with_given_route::<(), (), _>(dims, dst_strides, src_strides, |route| match route {
            Route::Inline { layout, .. } => Self::Inline(*layout),
            Route::Spilled { axes, .. } => Self::Spilled(axes.to_vec()),
        })
    }
}

/// A replay route borrowed from the frame that decided it: the axes to walk
/// and, when the walk is tiled, their cache tiles.
///
/// The wide storage lives in the out-of-line frames of [`with_spilled_route`]
/// and [`with_given_route`], so the inline route's frame never holds it.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Route<'a> {
    Inline {
        layout: &'a FusedPairLayout,
        tiles: Option<&'a PairTiles>,
    },
    Spilled {
        axes: &'a [FusedAxis],
        tiles: Option<&'a SpilledTiles>,
    },
}

impl<'a> Route<'a> {
    /// Whether the route walks cache tiles.
    pub(crate) fn is_tiled(&self) -> bool {
        match self {
            Self::Inline { tiles, .. } => tiles.is_some(),
            Self::Spilled { tiles, .. } => tiles.is_some(),
        }
    }

    /// The same axes walked column-major.
    pub(crate) fn untiled(self) -> Self {
        match self {
            Self::Inline { layout, .. } => Self::Inline {
                layout,
                tiles: None,
            },
            Self::Spilled { axes, .. } => Self::Spilled { axes, tiles: None },
        }
    }

    /// The block vector of the tiles over their compressed axes, or `None` for
    /// the column-major walk.
    #[cfg(feature = "bench-hooks")]
    pub(crate) fn blocks(&self) -> Option<&'a [usize]> {
        match *self {
            Self::Inline { tiles, .. } => tiles.map(|tiles| &tiles.blocks[..tiles.layout.rank]),
            Self::Spilled { tiles, .. } => tiles.map(SpilledTiles::blocks),
        }
    }

    /// The tiles of the route, copied out.
    #[cfg(test)]
    pub(crate) fn snapshot(self) -> Option<Tiles> {
        match self {
            Self::Inline { tiles, .. } => tiles.copied().map(Tiles::Inline),
            Self::Spilled { tiles, .. } => tiles.copied().map(Tiles::Spilled),
        }
    }
}

/// Run `f` on the replay route of the given axes, in their given order:
/// nothing is sorted or merged. Rank zero becomes the one-element
/// `EMPTY_AXIS` layout that [`fuse_axes`] also produces.
///
/// The three slices must have equal length, and the extents a checked,
/// nonzero product (the replay totals multiply them unchecked). A rank above
/// [`RAW_FUSED_RANK_LIMIT`] is compacted to its moving axes first, out of line
/// ([`with_wide_given_route`]).
pub(crate) fn with_given_route<D, S, R>(
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
    f: impl FnOnce(Route<'_>) -> R,
) -> R {
    debug_assert!(dims.len() == dst_strides.len() && dims.len() == src_strides.len());
    let rank = dims.len();
    if rank > RAW_FUSED_RANK_LIMIT {
        return with_wide_given_route::<D, S, R>(dims, dst_strides, src_strides, f);
    }
    let mut layout = FusedPairLayout::empty();
    layout.rank = rank.max(1);
    layout.dims[..rank].copy_from_slice(dims);
    layout.dst_strides[..rank].copy_from_slice(dst_strides);
    layout.src_strides[..rank].copy_from_slice(src_strides);
    let tiles = pair_tiles::<D, S>(&layout);
    f(Route::Inline {
        layout: &layout,
        tiles: tiles.as_ref(),
    })
}

/// [`with_given_route`] above [`RAW_FUSED_RANK_LIMIT`] given axes: the moving
/// axes, in their given order, in a stack array. At most
/// [`RAW_FUSED_RANK_LIMIT`] of them replay through the inline layout, more
/// through [`with_spilled_route`].
///
/// The tile decision is the one the given axes would get: the model already
/// drops extent-1 axes before it decides.
#[inline(never)]
fn with_wide_given_route<D, S, R>(
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
    f: impl FnOnce(Route<'_>) -> R,
) -> R {
    let mut axes = [EMPTY_AXIS; MAX_MOVING_AXES];
    let mut moving = 0;
    for ((&dim, &dst), &src) in dims.iter().zip(dst_strides).zip(src_strides) {
        if dim == 1 {
            continue;
        }
        // INVARIANT: the caller's checked nonzero count gives
        // `2^moving <= total <= usize::MAX`, so `moving < MAX_MOVING_AXES`.
        axes[moving] = FusedAxis { dim, dst, src };
        moving += 1;
    }
    if moving <= RAW_FUSED_RANK_LIMIT {
        let layout = FusedPairLayout::from_axes(if moving == 0 {
            &[EMPTY_AXIS]
        } else {
            &axes[..moving]
        });
        let tiles = pair_tiles::<D, S>(&layout);
        return f(Route::Inline {
            layout: &layout,
            tiles: tiles.as_ref(),
        });
    }
    with_spilled_route::<D, S, R>(&axes[..moving], f)
}

/// Run `f` on the replay route of a spilled axis list: more than
/// [`RAW_FUSED_RANK_LIMIT`] axes, every extent at least 2, and a checked
/// product (fused or compacted axes).
///
/// The exits the model decides before its metadata are answered from the axes
/// first ([#425]), so a layout they answer never sets up the tiles' storage.
///
/// [#425]: https://github.com/tensor4all/strided-rs/issues/425
#[inline(never)]
fn with_spilled_route<D, S, R>(axes: &[FusedAxis], f: impl FnOnce(Route<'_>) -> R) -> R {
    debug_assert!(axes.len() > RAW_FUSED_RANK_LIMIT && axes.iter().all(|axis| axis.dim >= 2));
    if crate::block::exits_before_metadata(
        axes.iter().map(|axis| (axis.dim, axis.dst, axis.src)),
        core::mem::size_of::<D>(),
        core::mem::size_of::<S>(),
    ) {
        return f(Route::Spilled { axes, tiles: None });
    }
    with_modelled_spilled_route::<D, S, R>(axes, f)
}

/// [`with_spilled_route`] past the model's early exits: the tiles live in this
/// frame while `f` runs, so neither the inline route nor an early exit carries
/// their storage.
#[inline(never)]
fn with_modelled_spilled_route<D, S, R>(axes: &[FusedAxis], f: impl FnOnce(Route<'_>) -> R) -> R {
    let mut tiles = SpilledTiles::EMPTY;
    let tiled = spilled_tiles::<D, S>(axes, &mut tiles);
    f(Route::Spilled {
        axes,
        tiles: tiled.then_some(&tiles),
    })
}

/// Fuse a raw stride pair into the inline representation.
///
/// Returns `None` when the fused rank exceeds [`RAW_FUSED_RANK_LIMIT`]. Used by
/// the window plans, whose non-fused replay is compiled alongside the plan.
pub(crate) fn fuse_pair_layout(
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
) -> Option<FusedPairLayout> {
    match fuse_pair_traversal(dims, dst_strides, src_strides) {
        PairTraversal::Inline(layout) => Some(layout),
        PairTraversal::Spilled(_) => None,
    }
}

/// Number of logical elements covered by a fused layout.
///
/// Every constructor of a [`FusedPairLayout`] starts from dims whose product
/// was checked by [`crate::kernel::total_len`], and fusion only merges axes
/// with a checked product, so the product cannot overflow.
#[inline]
pub(crate) fn fused_total(layout: &FusedPairLayout) -> usize {
    layout.dims[..layout.rank].iter().product()
}

/// Number of logical elements covered by a spilled axis list.
#[inline]
fn spilled_total(axes: &[FusedAxis]) -> usize {
    axes.iter().map(|axis| axis.dim).product()
}

/// The tiles of a route, copied out for the tests.
#[cfg(test)]
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)] // a test snapshot; production borrows `Route`
pub(crate) enum Tiles {
    Inline(PairTiles),
    Spilled(SpilledTiles),
}

#[cfg(test)]
impl Tiles {
    /// The tiles of the inline walk, or `None` for a spilled one.
    pub(crate) fn inline(&self) -> Option<&PairTiles> {
        match self {
            Self::Inline(tiles) => Some(tiles),
            Self::Spilled(_) => None,
        }
    }
}

/// The cache tiles of a spilled axis list whose rank exceeds
/// [`RAW_FUSED_RANK_LIMIT`].
///
/// `dims`/`dst`/`src` are the axes of the list, every extent at least 2, and
/// address exactly its slots in the same column-major order. They are stored
/// in arrays of [`MAX_MOVING_AXES`] and read as `rank`-long slices, because the
/// tile walk and the dimension splitter both take slices.
#[derive(Clone, Copy, Debug)]
pub(crate) struct SpilledTiles {
    rank: usize,
    dims: [usize; MAX_MOVING_AXES],
    dst: [isize; MAX_MOVING_AXES],
    src: [isize; MAX_MOVING_AXES],
    blocks: [usize; MAX_MOVING_AXES],
}

impl SpilledTiles {
    const EMPTY: Self = Self {
        rank: 0,
        dims: [1; MAX_MOVING_AXES],
        dst: [0; MAX_MOVING_AXES],
        src: [0; MAX_MOVING_AXES],
        blocks: [1; MAX_MOVING_AXES],
    };

    pub(crate) fn dims(&self) -> &[usize] {
        &self.dims[..self.rank]
    }

    pub(crate) fn dst(&self) -> &[isize] {
        &self.dst[..self.rank]
    }

    pub(crate) fn src(&self) -> &[isize] {
        &self.src[..self.rank]
    }

    pub(crate) fn blocks(&self) -> &[usize] {
        &self.blocks[..self.rank]
    }
}

/// The cache tiles of a fused pair layout whose tiled walk visits the slots in
/// a different order from the column-major walk.
///
/// Built by [`pair_tiles`]; `layout` addresses exactly the slots of the layout
/// it was built from, in the same column-major order, without its extent-1
/// axes.
#[derive(Clone, Copy, Debug)]
pub(crate) struct PairTiles {
    pub(crate) layout: FusedPairLayout,
    pub(crate) blocks: [usize; RAW_FUSED_RANK_LIMIT],
}

/// Cache tiles for replaying `layout` with destination element `D` and source
/// element `S`, or `None` when the column-major walk is kept.
///
/// The extent-1 axes are dropped first: they address offset 0 whatever their
/// stride, so the compressed layout addresses the same slots in the same
/// order, and an unvalidated stride on such an axis never reaches the block
/// arithmetic. Fewer than two remaining axes form one run, whose order no
/// block vector can change. The blocks come from the shared model
/// (`block::compute_block_sizes`), which sizes each operand by its own element
/// size exactly as the view path does. Tiles are returned only when they
/// change the visit order (the first axis whose block is smaller than its
/// extent is followed by an axis with a block above 1) and when that change can
/// reuse a cache line (see [`crate::block::declines_tiles`]).
///
/// The extents of `layout` must have a product that fits `usize` (every
/// constructor of a [`FusedPairLayout`] checks it).
pub(crate) fn pair_tiles<D, S>(layout: &FusedPairLayout) -> Option<PairTiles> {
    if fused_total(layout) <= 1 {
        return None;
    }
    let moving = layout.dims[..layout.rank]
        .iter()
        .filter(|&&dim| dim != 1)
        .count();
    if moving < 2 {
        return None;
    }
    let compressed;
    let layout = if moving == layout.rank {
        layout
    } else {
        compressed = without_unit_axes(layout);
        &compressed
    };
    let rank = layout.rank;
    let mut blocks = [1; RAW_FUSED_RANK_LIMIT];
    tile_blocks::<D, S, { 2 * RAW_FUSED_RANK_LIMIT }, RAW_FUSED_RANK_LIMIT>(
        &layout.dims[..rank],
        &layout.dst_strides[..rank],
        &layout.src_strides[..rank],
        &mut blocks[..rank],
    )
    .then_some(PairTiles {
        layout: *layout,
        blocks,
    })
}

/// The block vector of the shared cache-block model for already-compressed
/// axes (`dims`/`dst`/`src` of one length, every extent at least 2), written
/// to `blocks`; `false` when the column-major walk is kept.
///
/// The model's scratch holds `ORDERS` stride-order slots (two per axis) and
/// `AXES` cost slots, at least what `dims` needs. It is set up only past the
/// model's exits, so a layout they answer does not pay for it.
///
/// The single source of the tiling decision for both storage shapes: the
/// inline [`FusedPairLayout`] and the spilled [`SpilledTiles`].
fn tile_blocks<D, S, const ORDERS: usize, const AXES: usize>(
    dims: &[usize],
    dst: &[isize],
    src: &[isize],
    blocks: &mut [usize],
) -> bool {
    let strides = [dst, src];
    let elem_sizes = [core::mem::size_of::<D>(), core::mem::size_of::<S>()];
    // `false`: one of the model's exits keeps the full dimensions, which
    // cannot change the visit order.
    if crate::block::model_exits(dims, &strides, &elem_sizes) {
        return false;
    }
    let rank = dims.len();
    // INVARIANT: both callers pass capacities of at least their rank.
    let mut orders = [0usize; ORDERS];
    let mut costs = [0isize; AXES];
    crate::block::reduced_block_sizes_into(
        dims,
        &strides,
        &elem_sizes,
        blocks,
        &mut orders[..2 * rank],
        &mut costs[..rank],
    );
    let Some(first_cut) = (0..dims.len()).find(|&axis| blocks[axis] < dims[axis]) else {
        return false;
    };
    if blocks[first_cut + 1..].iter().all(|&block| block == 1) {
        return false;
    }
    // The axes before `first_cut` are walked whole inside every tile, so each
    // operand is judged with its own element size, as the model now does.
    if crate::block::declines_tiles(dims, &strides, &elem_sizes, blocks) {
        return false;
    }
    // Operand 0 is the destination, as on the view path (#287).
    crate::block::fit_l1_sets(dims, &strides, &elem_sizes, 0, blocks);
    true
}

/// Cache tiles for replaying a spilled axis list (more than
/// [`RAW_FUSED_RANK_LIMIT`] axes, every extent at least 2, a checked product)
/// that [`crate::block::exits_before_metadata`] does not answer, written to
/// `tiles`; `false` when the column-major walk is kept.
///
/// The invariant: an axis list is tiled exactly when the same layout given
/// inline would be.
fn spilled_tiles<D, S>(axes: &[FusedAxis], tiles: &mut SpilledTiles) -> bool {
    let rank = axes.len();
    // INVARIANT: every axis has an extent of at least 2 and the product is a
    // checked nonzero count, so `2^rank <= usize::MAX` and
    // `rank < MAX_MOVING_AXES`.
    tiles.rank = rank;
    for (axis, entry) in axes.iter().enumerate() {
        tiles.dims[axis] = entry.dim;
        tiles.dst[axis] = entry.dst;
        tiles.src[axis] = entry.src;
    }
    tile_blocks::<D, S, { 2 * MAX_MOVING_AXES }, MAX_MOVING_AXES>(
        &tiles.dims[..rank],
        &tiles.dst[..rank],
        &tiles.src[..rank],
        &mut tiles.blocks[..rank],
    )
}

/// `layout` without its extent-1 axes, in the given order.
fn without_unit_axes(layout: &FusedPairLayout) -> FusedPairLayout {
    let mut compressed = FusedPairLayout::empty();
    let mut rank = 0;
    for axis in 0..layout.rank {
        if layout.dims[axis] == 1 {
            continue;
        }
        compressed.dims[rank] = layout.dims[axis];
        compressed.dst_strides[rank] = layout.dst_strides[axis];
        compressed.src_strides[rank] = layout.src_strides[axis];
        rank += 1;
    }
    compressed.rank = rank;
    compressed
}

/// Replay every logical index of `tile_box` tile by tile: the tiles of extents
/// `blocks`, anchored at the box origin and clipped to the box, are visited in
/// column-major order of the tile grid, and each tile is walked in
/// column-major order by [`apply_fused_range`].
///
/// Kept out of line so that the untiled replay keeps its code shape.
///
/// # Safety
///
/// The [`apply_fused_range`] contract for the whole of `tile_box`, and every
/// `blocks[axis]` for `axis < tile_box.rank` is at least 1.
#[inline(never)]
pub(crate) unsafe fn apply_tiled_box<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    tile_box: &FusedPairLayout,
    blocks: &[usize; RAW_FUSED_RANK_LIMIT],
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    let tiles = tile_count(tile_box, blocks);
    // SAFETY: forwarded caller contract; `0..tiles` is the whole tile grid.
    unsafe {
        apply_tile_range(
            dst_ptr, dst_base, src_ptr, src_base, tile_box, blocks, 0, tiles, apply,
        );
    }
}

/// Number of tiles of extents `blocks` that cover `tile_box`; at most its
/// element count, so it cannot overflow.
pub(crate) fn tile_count(
    tile_box: &FusedPairLayout,
    blocks: &[usize; RAW_FUSED_RANK_LIMIT],
) -> usize {
    tile_box.dims[..tile_box.rank]
        .iter()
        .zip(blocks)
        .map(|(&dim, &block)| dim.div_ceil(block))
        .product()
}

/// Replay the tiles `first..first + count` of `tile_box`, numbered in
/// column-major order of the tile grid [`apply_tiled_box`] walks, each in
/// column-major order by [`apply_fused_range`].
///
/// Disjoint tile ranges address disjoint logical indices, and the ranges
/// `0..k`, `k..tile_count` together walk exactly what [`apply_tiled_box`]
/// walks, in the same order.
///
/// # Safety
///
/// The [`apply_fused_range`] contract for the whole of `tile_box`, every
/// `blocks[axis]` for `axis < tile_box.rank` at least 1, and
/// `first + count` at most [`tile_count`] of `tile_box` and `blocks`.
#[allow(clippy::too_many_arguments)]
#[inline(never)]
pub(crate) unsafe fn apply_tile_range<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    tile_box: &FusedPairLayout,
    blocks: &[usize; RAW_FUSED_RANK_LIMIT],
    first: usize,
    count: usize,
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    if count == 0 {
        return;
    }
    let rank = tile_box.rank;
    let mut tile = *tile_box;
    // `origin[axis]` is the first box coordinate of the current tile along
    // `axis`; `dst_tile`/`src_tile` are the offsets of the tile origin.
    let mut origin = [0usize; RAW_FUSED_RANK_LIMIT];
    let mut dst_tile = dst_base;
    let mut src_tile = src_base;
    // Decode `first` into its tile-grid coordinates, axis 0 fastest.
    let mut rest = first;
    for axis in 0..rank {
        let along = tile_box.dims[axis].div_ceil(blocks[axis]);
        origin[axis] = (rest % along) * blocks[axis];
        rest /= along;
        dst_tile += origin[axis] as isize * tile_box.dst_strides[axis];
        src_tile += origin[axis] as isize * tile_box.src_strides[axis];
        tile.dims[axis] = blocks[axis].min(tile_box.dims[axis] - origin[axis]);
    }
    let mut left = count;
    loop {
        // Counted here, where the tile is walked, so that a test sees the
        // walk itself and not the range a caller asked for.
        #[cfg(test)]
        crate::threading::record_tile_box();
        // SAFETY: the tile is a sub-box of `tile_box` at a reachable origin, so
        // the caller's contract covers every logical index of the tile.
        unsafe {
            apply_fused_range(
                dst_ptr,
                dst_tile,
                src_ptr,
                src_tile,
                &tile,
                0,
                fused_total(&tile),
                apply,
            );
        }
        left -= 1;
        if left == 0 {
            return;
        }
        // Column-major odometer over the tile grid. An axis advances only
        // when another tile follows along it, so `blocks[axis]` is at most
        // its last box coordinate, and it rewinds by its current origin:
        // every intermediate offset is a reachable offset of the box. The
        // caller's bound on `first + count` keeps the walk inside the grid.
        let mut axis = 0;
        loop {
            debug_assert!(axis < rank, "tile range past the end of the grid");
            let next = origin[axis] + blocks[axis];
            if next < tile_box.dims[axis] {
                origin[axis] = next;
                dst_tile += blocks[axis] as isize * tile_box.dst_strides[axis];
                src_tile += blocks[axis] as isize * tile_box.src_strides[axis];
                tile.dims[axis] = blocks[axis].min(tile_box.dims[axis] - next);
                break;
            }
            dst_tile -= origin[axis] as isize * tile_box.dst_strides[axis];
            src_tile -= origin[axis] as isize * tile_box.src_strides[axis];
            origin[axis] = 0;
            tile.dims[axis] = blocks[axis].min(tile_box.dims[axis]);
            axis += 1;
        }
    }
}

/// Replay every logical index of `box_dims`, a sub-box of `tiles`, tile by
/// tile: the tiles of extents `tiles.blocks`, anchored at the box origin and
/// clipped to it, are visited in column-major order of the tile grid, and each
/// tile is walked in column-major order by [`apply_spilled_range`].
///
/// The spilled counterpart of [`apply_tiled_box`]: same tile odometer, same
/// per-element walk as the untiled replay, only the axis storage differs. Kept
/// out of line so that the untiled spilled replay keeps its code shape. The
/// tile, its cursor and its origin are stack arrays of [`MAX_MOVING_AXES`].
///
/// # Safety
///
/// The [`apply_spilled_range`] contract for the whole of `box_dims`, which
/// must be `tiles.dims` or a sub-box of it anchored at `dst_base`/`src_base`,
/// and every `tiles.blocks[axis]` at least 1.
#[allow(clippy::too_many_arguments)]
#[inline(never)]
pub(crate) unsafe fn apply_spilled_tiled_box<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    tiles: &SpilledTiles,
    box_dims: &[usize],
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    let rank = box_dims.len();
    // One axis list for the current tile and one cursor for the whole walk,
    // however many tiles it visits.
    // INVARIANT: `box_dims` is `tiles.dims` or a sub-box of it, so
    // `rank == tiles.rank < MAX_MOVING_AXES`.
    let mut tile_axes = [EMPTY_AXIS; MAX_MOVING_AXES];
    let tile = &mut tile_axes[..rank];
    for (axis, slot) in tile.iter_mut().enumerate() {
        slot.dst = tiles.dst[axis];
        slot.src = tiles.src[axis];
    }
    let mut cursor = [0usize; MAX_MOVING_AXES];
    let index = &mut cursor[..rank];
    let mut origins = [0usize; MAX_MOVING_AXES];
    let origin = &mut origins[..rank];
    let mut dst_tile = dst_base;
    let mut src_tile = src_base;
    loop {
        #[cfg(test)]
        crate::threading::record_tile_box();
        let mut count = 1usize;
        for axis in 0..rank {
            let dim = tiles.blocks[axis].min(box_dims[axis] - origin[axis]);
            tile[axis].dim = dim;
            count *= dim;
        }
        // SAFETY: the tile is a sub-box of `box_dims` at a reachable origin, so
        // the caller's contract covers every logical index of the tile.
        unsafe {
            apply_spilled_range_with(
                dst_ptr, dst_tile, src_ptr, src_tile, tile, 0, count, index, apply,
            );
        }
        // The column-major odometer of [`apply_tiled_box`], over slices.
        let mut axis = 0;
        loop {
            if axis == rank {
                return;
            }
            let next = origin[axis] + tiles.blocks[axis];
            if next < box_dims[axis] {
                origin[axis] = next;
                dst_tile += tiles.blocks[axis] as isize * tiles.dst[axis];
                src_tile += tiles.blocks[axis] as isize * tiles.src[axis];
                break;
            }
            dst_tile -= origin[axis] as isize * tiles.dst[axis];
            src_tile -= origin[axis] as isize * tiles.src[axis];
            origin[axis] = 0;
            axis += 1;
        }
    }
}

/// Serial replay of a fused pair layout over borrowed raw views.
///
/// The destination layout need not be injective: runs are replayed in order,
/// so accumulating callers such as [`axpy_raw`] keep their sequential
/// semantics. Parallel replay goes through `copy_plan::replay_fused`, which
/// the plans and the `replay_*_raw` entries call only with a destination
/// proven injective or a serial token.
pub(crate) fn apply_fused_pair<D, S, Apply>(
    dst: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    layout: &FusedPairLayout,
    mut apply: Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    let total = fused_total(layout);
    if total == 0 {
        return;
    }
    let src_ptr = src.data().as_ptr();
    let src_base = src.offset();
    let dst_base = dst.offset();
    let dst_ptr = dst.data_mut().as_mut_ptr();
    // SAFETY: `RawStridedRef`/`RawStridedMut` guarantee (by `new`, or by the
    // caller of `new_unchecked`) that every offset reachable from their offset
    // through their dims/strides lies inside their data. Callers pass a layout
    // fused from exactly those dims/strides, so every logical index in
    // `0..total` maps to in-bounds source and destination slots. The shared
    // and exclusive borrows cannot overlap, and this is the only writer.
    unsafe {
        apply_fused_range(
            dst_ptr, dst_base, src_ptr, src_base, layout, 0, total, &mut apply,
        );
    }
}

/// Serial replay of a spilled fused axis list over borrowed raw views.
///
/// Kept out of line and separate from [`apply_fused_pair`] so that the inline
/// entry points keep the code shape they had before high-rank fusion existed:
/// fused ranks above [`RAW_FUSED_RANK_LIMIT`] are the rare case, and inlining
/// this second carry loop into them measurably slowed the inline path (extra
/// register pressure in a loop that runs once per short run).
#[inline(never)]
pub(crate) fn apply_spilled_pair<D, S, Apply>(
    dst: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    axes: &[FusedAxis],
    mut apply: Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    let total = spilled_total(axes);
    if total == 0 {
        return;
    }
    let src_ptr = src.data().as_ptr();
    let src_base = src.offset();
    let dst_base = dst.offset();
    let dst_ptr = dst.data_mut().as_mut_ptr();
    // SAFETY: same contract as `apply_fused_pair`, for the axis list fused from
    // the same dims/strides.
    unsafe {
        apply_spilled_range(
            dst_ptr, dst_base, src_ptr, src_base, axes, 0, total, &mut apply,
        );
    }
}

/// Serial replay of a route on the calling thread: the four whole-box walks of
/// the parallel replay's serial branches, one sequential pass through `apply`.
///
/// [`crate::copy_plan::replay_fused`] sends a serial token here, and so does
/// [`replay_map_raw_serial`] with its `FnMut`, so both walk the same leaves in
/// the same order. No arm needs `Send` or `Sync`: nothing crosses a thread.
///
/// # Safety
///
/// The [`crate::copy_plan::replay_fused`] contract for `route` at these bases,
/// with a serial token: every logical index maps to in-bounds slots of both
/// allocations, the product of the extents does not overflow, the tiles (when
/// present) are the route builder's own and the destination is injective over
/// a tiled route, and the destination does not overlap the source.
pub(crate) unsafe fn replay_route_serial<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    route: Route<'_>,
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    // SAFETY: forwarded caller contract. Inline tiles address exactly the
    // slots of their layout; spilled tiles hold their own axes. One
    // sequential walk updates a repeated slot once per logical index, in
    // order, so an untiled route needs no injectivity.
    unsafe {
        match route {
            Route::Inline {
                layout,
                tiles: None,
            } => apply_fused_range(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                layout,
                0,
                fused_total(layout),
                apply,
            ),
            Route::Inline {
                tiles: Some(tiles), ..
            } => apply_tiled_box(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                &tiles.layout,
                &tiles.blocks,
                apply,
            ),
            Route::Spilled { axes, tiles: None } => apply_spilled_range(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                axes,
                0,
                spilled_total(axes),
                apply,
            ),
            Route::Spilled {
                tiles: Some(tiles), ..
            } => apply_spilled_tiled_box(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                tiles,
                tiles.dims(),
                apply,
            ),
        }
    }
}

/// Replay logical indices `start..start + len` of a fused pair layout, in
/// column-major order of the fused axes (axis 0 fastest).
///
/// The start coordinate is decoded once; runs along axis 0 then advance the
/// outer coordinates incrementally, so no per-element range checks or
/// coordinate rebuilds remain in the hot loop.
///
/// # Safety
///
/// - `start + len` must not exceed [`fused_total`] of `layout`.
/// - For every logical index `i` in the range, `dst_base` plus the fused
///   destination offset of `i` must be an in-bounds, writable slot of the
///   allocation behind `dst_ptr`, and likewise `src_base` plus the source
///   offset must be an in-bounds, readable slot behind `src_ptr`.
/// - No other thread may access the destination slots of this range while it
///   runs, and the source slots must not be written concurrently. Destination
///   and source slots must not overlap.
// Range leaf: both bases, the layout, the range and the closure, called once per worker
// range.
#[allow(clippy::too_many_arguments)]
pub(crate) unsafe fn apply_fused_range<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    layout: &FusedPairLayout,
    start: usize,
    len: usize,
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    if len == 0 {
        return;
    }
    let rank = layout.rank;
    let inner_len = layout.dims[0];
    let inner_dst = layout.dst_strides[0];
    let inner_src = layout.src_strides[0];

    // Decode the start coordinate once per range. `dst_offset`/`src_offset`
    // track the offset of the current run start (outer coordinates plus the
    // inner coordinate `inner_start`); every value is a reachable offset.
    let mut index = [0usize; RAW_FUSED_RANK_LIMIT];
    let mut rest = start;
    let mut dst_outer = dst_base;
    let mut src_outer = src_base;
    // The axis indexes `index`, `layout.dims` and both stride tables at once.
    #[allow(clippy::needless_range_loop)]
    for axis in 0..rank {
        let dim = layout.dims[axis];
        index[axis] = rest % dim;
        rest /= dim;
        if axis > 0 {
            dst_outer += index[axis] as isize * layout.dst_strides[axis];
            src_outer += index[axis] as isize * layout.src_strides[axis];
        }
    }
    let mut inner_start = index[0];
    let mut remaining = len;
    loop {
        let run = (inner_len - inner_start).min(remaining);
        let dst_run = dst_outer + inner_start as isize * inner_dst;
        let src_run = src_outer + inner_start as isize * inner_src;
        // SAFETY: the run covers logical indices inside the caller's range, so
        // by this function's contract every slot touched below is in-bounds,
        // exclusively owned by this call (destination) and unaliased.
        unsafe {
            apply_run(
                dst_ptr, dst_run, inner_dst, src_ptr, src_run, inner_src, run, apply,
            )
        };
        remaining -= run;
        if remaining == 0 {
            return;
        }
        inner_start = 0;
        // Advance an axis only when another position along it follows, and
        // rewind it from its last position, so every intermediate base is a
        // reachable offset of a validated layout (issue #243 follow-up): a
        // layout ending within one stride of `isize::MAX` must not overflow.
        // `remaining > 0` guarantees a following run exists, so the loop
        // always finds an axis to advance before running out of rank.
        let mut axis = 1;
        while axis < rank {
            if index[axis] + 1 < layout.dims[axis] {
                index[axis] += 1;
                dst_outer += layout.dst_strides[axis];
                src_outer += layout.src_strides[axis];
                break;
            }
            let last = (layout.dims[axis] - 1) as isize;
            dst_outer -= last * layout.dst_strides[axis];
            src_outer -= last * layout.src_strides[axis];
            index[axis] = 0;
            axis += 1;
        }
    }
}

/// Replay logical indices `start..start + len` of a spilled fused axis list, in
/// column-major order of the axes (axis 0 fastest).
///
/// The carry loop is the one [`apply_fused_range`] uses, over interleaved axes
/// with its carry state in a stack array of [`MAX_MOVING_AXES`]: nothing is
/// allocated and no per-element coordinate decode happens.
///
/// # Safety
///
/// The [`apply_fused_range`] contract holds for `axes`, which hold at most
/// [`MAX_MOVING_AXES`] entries (every caller passes fused or compacted axes of
/// a checked count; a longer list panics before any access).
///
/// Kept out of line: inlining this second carry loop into the inline replay
/// measurably slows that one down.
// Same shape as `apply_fused_range` for the spilled layout, per worker range.
#[allow(clippy::too_many_arguments)]
#[inline(never)]
pub(crate) unsafe fn apply_spilled_range<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    axes: &[FusedAxis],
    start: usize,
    len: usize,
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    if len == 0 {
        return;
    }
    let mut cursor = [0usize; MAX_MOVING_AXES];
    // INVARIANT: fused and compacted axes have extents of at least 2 and a
    // checked product, so `axes.len() < MAX_MOVING_AXES`.
    let index = &mut cursor[..axes.len()];
    // SAFETY: forwarded caller contract; `index` is the rank-sized cursor.
    unsafe {
        apply_spilled_range_with(
            dst_ptr, dst_base, src_ptr, src_base, axes, start, len, index, apply,
        )
    }
}

/// [`apply_spilled_range`] with the caller's rank-sized coordinate buffer, so
/// that the tile walk keeps one cursor for all its tiles.
///
/// # Safety
///
/// The [`apply_spilled_range`] contract, and `index.len()` at least
/// `axes.len()`.
#[allow(clippy::too_many_arguments)]
unsafe fn apply_spilled_range_with<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    axes: &[FusedAxis],
    start: usize,
    len: usize,
    index: &mut [usize],
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    if len == 0 {
        return;
    }
    let rank = axes.len();
    debug_assert!(index.len() >= rank);
    let inner_len = axes[0].dim;
    let inner_dst = axes[0].dst;
    let inner_src = axes[0].src;

    let mut rest = start;
    let mut dst_outer = dst_base;
    let mut src_outer = src_base;
    for axis in 0..rank {
        let dim = axes[axis].dim;
        index[axis] = rest % dim;
        rest /= dim;
        if axis > 0 {
            dst_outer += index[axis] as isize * axes[axis].dst;
            src_outer += index[axis] as isize * axes[axis].src;
        }
    }
    let mut inner_start = index[0];
    let mut remaining = len;
    loop {
        let run = (inner_len - inner_start).min(remaining);
        let dst_run = dst_outer + inner_start as isize * inner_dst;
        let src_run = src_outer + inner_start as isize * inner_src;
        // SAFETY: the run covers logical indices inside the caller's range, so
        // by the caller's contract every slot touched below is in-bounds,
        // exclusively owned by this call (destination) and unaliased.
        unsafe {
            apply_run(
                dst_ptr, dst_run, inner_dst, src_ptr, src_run, inner_src, run, apply,
            )
        };
        remaining -= run;
        if remaining == 0 {
            return;
        }
        inner_start = 0;
        // Same incremental carry as the inline replay: offsets only ever hold
        // reachable positions, and `remaining > 0` guarantees an axis advances.
        let mut axis = 1;
        while axis < rank {
            if index[axis] + 1 < axes[axis].dim {
                index[axis] += 1;
                dst_outer += axes[axis].dst;
                src_outer += axes[axis].src;
                break;
            }
            let last = (axes[axis].dim - 1) as isize;
            dst_outer -= last * axes[axis].dst;
            src_outer -= last * axes[axis].src;
            index[axis] = 0;
            axis += 1;
        }
    }
}

/// One run along the fused inner axis.
///
/// # Safety
///
/// Every `dst_offset + k * dst_stride` and `src_offset + k * src_stride` for
/// `k < len` must be an in-bounds slot as described in [`apply_fused_range`],
/// with exclusive access to the destination slots.
// Run leaf: both base/offset/stride triples, the length and the closure, per run.
#[allow(clippy::too_many_arguments)]
#[inline(always)]
unsafe fn apply_run<D, S, Apply>(
    dst_ptr: *mut D,
    dst_offset: isize,
    dst_stride: isize,
    src_ptr: *const S,
    src_offset: isize,
    src_stride: isize,
    len: usize,
    apply: &mut Apply,
) where
    D: Copy,
    S: Copy,
    Apply: FnMut(&mut D, S),
{
    if dst_stride == 1 {
        // SAFETY: a unit destination stride makes the run `len` consecutive
        // in-bounds slots starting at `dst_offset`, exclusively owned here.
        let dst_run = unsafe { core::slice::from_raw_parts_mut(dst_ptr.offset(dst_offset), len) };
        if src_stride == 1 {
            // A `copy_nonoverlapping` per run is not used for plain copies:
            // it measured slower than this element loop for short runs
            // (one `memcpy` call each) and for long cache-resident copies.
            // SAFETY: `len` consecutive in-bounds source slots, which the
            // exclusive destination run cannot overlap.
            let src_run = unsafe { core::slice::from_raw_parts(src_ptr.offset(src_offset), len) };
            for (dst, &value) in dst_run.iter_mut().zip(src_run) {
                apply(dst, value);
            }
            return;
        }
        if src_stride == -1 {
            // INVARIANT: the range walks never pass an empty run, and both
            // strides are nonzero, so the validated reach `len - 1` fits
            // `isize`; casting `len` itself would wrap for a run of
            // `isize::MAX + 1` elements. (A `saturating_sub` here measurably
            // slowed short unit-stride runs by changing the code layout of
            // the whole inlined walk.)
            let last = (len - 1) as isize;
            // SAFETY: the run reads `src_offset - (len - 1) ..= src_offset`,
            // all in-bounds; the lowest one is the run's last source slot.
            let src_run =
                unsafe { core::slice::from_raw_parts(src_ptr.offset(src_offset - last), len) };
            for (dst, &value) in dst_run.iter_mut().zip(src_run.iter().rev()) {
                apply(dst, value);
            }
            return;
        }
        // SAFETY: the run start is an in-bounds source slot.
        let src_start = unsafe { src_ptr.offset(src_offset) };
        for (position, dst) in dst_run.iter_mut().enumerate() {
            // SAFETY: `position < len`, so this is a run source slot.
            let value = unsafe { *src_start.offset(position as isize * src_stride) };
            apply(dst, value);
        }
        return;
    }
    // SAFETY: the run start is an in-bounds slot of each allocation.
    let dst_start = unsafe { dst_ptr.offset(dst_offset) };
    let src_start = unsafe { src_ptr.offset(src_offset) };
    // The bound stays `usize`: a checked broadcast run may hold more than
    // `isize::MAX` elements, and `len as isize` would wrap to an empty loop.
    for position in 0..len {
        // INVARIANT: a nonzero stride bounds the run by its validated reach,
        // so `position` fits `isize` exactly; a longer run is possible only
        // along a zero stride, where the wrapped cast is multiplied by zero.
        let position = position as isize;
        // SAFETY: `position < len`, so both are slots of this run.
        unsafe {
            let value = *src_start.offset(position * src_stride);
            apply(&mut *dst_start.offset(position * dst_stride), value);
        }
    }
}

fn ensure_same_dims(dst: &[usize], src: &[usize]) -> Result<()> {
    if dst != src {
        return Err(crate::StridedError::ShapeMismatch(
            dst.to_vec(),
            src.to_vec(),
        ));
    }
    // Reject an element count beyond usize (a huge stride-0 broadcast)
    // instead of replaying it.
    crate::kernel::total_len(dst)?;
    Ok(())
}

/// `dest = scale * src` over borrowed raw strided layouts.
///
/// # Errors
///
/// Returns [`crate::StridedError::ShapeMismatch`] when `dest` and `src` do
/// not describe the same extents, or [`crate::StridedError::OffsetOverflow`]
/// when the element count does not fit `usize`. Nothing is written on error.
pub fn copy_scale_raw<T>(
    dest: &mut RawStridedMut<'_, T>,
    src: &RawStridedRef<'_, T>,
    scale: T,
) -> Result<()>
where
    T: Copy + Mul<T, Output = T> + ElementOpApply + Send + Sync,
{
    ensure_same_dims(dest.dims(), src.dims())?;
    match fuse_pair_traversal(dest.dims(), dest.strides(), src.strides()) {
        PairTraversal::Inline(layout) => {
            apply_fused_pair(dest, src, &layout, |dst: &mut T, value: T| {
                *dst = scale * value
            })
        }
        PairTraversal::Spilled(axes) => {
            apply_spilled_pair(dest, src, &axes, |dst: &mut T, value: T| {
                *dst = scale * value
            })
        }
    }
    Ok(())
}

/// `dest = scale * conj(src)` over borrowed raw strided layouts.
///
/// # Errors
///
/// Returns [`crate::StridedError::ShapeMismatch`] when `dest` and `src` do
/// not describe the same extents, or [`crate::StridedError::OffsetOverflow`]
/// when the element count does not fit `usize`. Nothing is written on error.
pub fn copy_scale_conj_raw<T>(
    dest: &mut RawStridedMut<'_, T>,
    src: &RawStridedRef<'_, T>,
    scale: T,
) -> Result<()>
where
    T: Copy + Mul<T, Output = T> + ElementOpApply + Send + Sync,
{
    ensure_same_dims(dest.dims(), src.dims())?;
    match fuse_pair_traversal(dest.dims(), dest.strides(), src.strides()) {
        PairTraversal::Inline(layout) => {
            apply_fused_pair(dest, src, &layout, |dst: &mut T, value: T| {
                *dst = scale * value.conj()
            })
        }
        PairTraversal::Spilled(axes) => {
            apply_spilled_pair(dest, src, &axes, |dst: &mut T, value: T| {
                *dst = scale * value.conj()
            })
        }
    }
    Ok(())
}

/// `dest = alpha * src + dest` over borrowed raw strided layouts.
///
/// # Errors
///
/// Returns [`crate::StridedError::ShapeMismatch`] when `dest` and `src` do
/// not describe the same extents, or [`crate::StridedError::OffsetOverflow`]
/// when the element count does not fit `usize`. Nothing is written on error.
pub fn axpy_raw<T>(
    dest: &mut RawStridedMut<'_, T>,
    src: &RawStridedRef<'_, T>,
    alpha: T,
) -> Result<()>
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T> + ElementOpApply + Send + Sync,
{
    ensure_same_dims(dest.dims(), src.dims())?;
    match fuse_pair_traversal(dest.dims(), dest.strides(), src.strides()) {
        PairTraversal::Inline(layout) => {
            apply_fused_pair(dest, src, &layout, |dst: &mut T, value: T| {
                *dst = *dst + alpha * value
            })
        }
        PairTraversal::Spilled(axes) => {
            apply_spilled_pair(dest, src, &axes, |dst: &mut T, value: T| {
                *dst = *dst + alpha * value
            })
        }
    }
    Ok(())
}

/// `dest = alpha * conj(src) + dest` over borrowed raw strided layouts.
///
/// # Errors
///
/// Returns [`crate::StridedError::ShapeMismatch`] when `dest` and `src` do
/// not describe the same extents, or [`crate::StridedError::OffsetOverflow`]
/// when the element count does not fit `usize`. Nothing is written on error.
pub fn axpy_conj_raw<T>(
    dest: &mut RawStridedMut<'_, T>,
    src: &RawStridedRef<'_, T>,
    alpha: T,
) -> Result<()>
where
    T: Copy + Add<T, Output = T> + Mul<T, Output = T> + ElementOpApply + Send + Sync,
{
    ensure_same_dims(dest.dims(), src.dims())?;
    match fuse_pair_traversal(dest.dims(), dest.strides(), src.strides()) {
        PairTraversal::Inline(layout) => {
            apply_fused_pair(dest, src, &layout, |dst: &mut T, value: T| {
                *dst = *dst + alpha * value.conj()
            })
        }
        PairTraversal::Spilled(axes) => {
            apply_spilled_pair(dest, src, &axes, |dst: &mut T, value: T| {
                *dst = *dst + alpha * value.conj()
            })
        }
    }
    Ok(())
}

/// The checked route of the given axes of two views: the shared front of
/// every `replay_*_raw` entry, parallel and serial.
///
/// The element count is checked before anything is built. The unfused
/// traversal keeps every given extent, and the replay totals (`fused_total`,
/// `replay_spilled_raw`) take an unchecked product, so the zero-first count
/// of `kernel::total_len` has to keep an empty layout whose nonzero prefix
/// overflows, such as `[usize::MAX, 2, 0]`, away from them. An empty layout
/// returns before `f` runs.
///
/// `f` receives the route, the element count and, when the route came out
/// tiled, whether the destination was proven injective; the tiles are dropped
/// unless it was.
///
/// The slices are the views' own metadata, borrowed apart from the views so
/// that `f` can take the destination mutably.
fn with_checked_route<D, S>(
    dims: &[usize],
    dst_strides: &[isize],
    src_dims: &[usize],
    src_strides: &[isize],
    f: impl FnOnce(Route<'_>, usize, Option<bool>),
) -> Result<()> {
    ensure_same_dims(dims, src_dims)?;
    let total = crate::kernel::total_len(dims)?;
    if total == 0 {
        return Ok(());
    }
    with_given_route::<D, S, _>(dims, dst_strides, src_strides, |route| {
        let mut route = route;
        let mut proven = None;
        if route.is_tiled() {
            let holds = crate::layout_check::is_injective_layout_without_alloc(dims, dst_strides);
            proven = Some(holds);
            if !holds {
                route = route.untiled();
            }
        }
        f(route, total, proven)
    });
    Ok(())
}

/// Checked replay of the given axes of two views: the shared body of the
/// parallel `replay_*_raw` entries.
fn replay_given<D, S, Apply>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    apply: Apply,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let (dims, dst_strides) = (dest.dims(), dest.strides());
    let injective = || crate::layout_check::is_injective_layout_without_alloc(dims, dst_strides);
    with_checked_route::<D, S>(
        dims,
        dst_strides,
        src.dims(),
        src.strides(),
        |route, total, proven| {
            let exec = if route.is_tiled() {
                // The tiled tree gates every node on the caller's token itself; the
                // flat width rule would cap it at the width of one flat dispatch.
                exec
            } else {
                let exec = crate::cost::for_len(exec, KernelClass::Copy, total);
                if !exec.is_serial() && !proven.unwrap_or_else(injective) {
                    // A destination not proven injective replays as one sequential
                    // column-major walk, which is also its defined semantics; the
                    // budget-one token cannot be widened again by the replay's own
                    // width rule.
                    exec.limit(NonZeroUsize::MIN)
                } else {
                    exec
                }
            };
            // SAFETY: the route is built from exactly the views' dims and strides
            // (`ensure_same_dims` proved the dims agree); compaction drops only
            // extent-1 axes, whose coordinate is always 0, so the reachable
            // offsets equal the views' validated set, and the original metadata
            // still drives bounds, shape and injectivity. The views' bounds proofs
            // therefore cover every replayed offset; `total_len` checked the
            // nonzero product; the route's tiles are the decision for its own
            // axes, and tiles or a non-serial `exec` are left only for a
            // destination proven injective; the exclusive and shared borrows
            // cannot overlap.
            unsafe {
                crate::copy_plan::replay_fused(
                    dest,
                    src,
                    route,
                    apply,
                    KernelClass::Copy.ns_per_element(),
                    exec,
                )
            };
        },
    )
}

/// `dest = src`, replaying the axes of the two views exactly as given.
///
/// The views carry already-fused dims: no axis is reordered, dropped or
/// merged, and no plan is compiled. Axis 0 is the inner run of the
/// column-major walk; when the shared cache-block model finds tiles that change
/// the visit order and can reuse a cache line, the walk goes tile by tile
/// instead, each tile column-major over the given axes. Bounds were validated when the views were built
/// ([`RawStridedRef::new`], [`RawStridedMut::new`]).
///
/// On a successful call the replay itself (validation, traversal and
/// dispatch) allocates nothing at any rank on a serial token, or on a pooled
/// token whose replay is not tiled. A pooled tiled replay with more than
/// [`RAW_FUSED_RANK_LIMIT`] moving axes may allocate the splitter's metadata.
/// The wide route uses a rank-bounded amount of stack. An error may allocate
/// its payload.
///
/// The width comes from the repository rule on `exec`. A parallel or tiled
/// replay runs only on a destination proven injective without allocating; any
/// other destination is replayed serially in column-major order of the given
/// axes.
///
/// # Errors
///
/// [`StridedError::ShapeMismatch`](crate::StridedError::ShapeMismatch) when the
/// two views have different dims, and
/// [`StridedError::OffsetOverflow`](crate::StridedError::OffsetOverflow) when the
/// element count overflows `usize`; both before any write.
///
/// # Examples
///
/// Copy the outer band `1..3` of a stored `2 x 3` block into a transposed
/// destination:
///
/// ```rust
/// use strided_basic::{replay_copy_raw, Exec, RawStridedMut, RawStridedRef};
///
/// let stored = [0.0f64, 1.0, 2.0, 3.0, 4.0, 5.0]; // column-major 2 x 3
/// let band = [2usize, 2];
/// let src = RawStridedRef::new(&stored, &band, &[1, 2], 2).unwrap();
/// let mut out = [0.0f64; 4];
/// let mut dst = RawStridedMut::new(&mut out, &band, &[2, 1], 0).unwrap();
/// replay_copy_raw(&mut dst, &src, Exec::serial()).unwrap();
/// assert_eq!(out, [2.0, 4.0, 3.0, 5.0]);
/// ```
pub fn replay_copy_raw<T>(
    dest: &mut RawStridedMut<'_, T>,
    src: &RawStridedRef<'_, T>,
    exec: Exec<'_>,
) -> Result<()>
where
    T: Copy + Send + Sync,
{
    replay_given(dest, src, |dst: &mut T, value: T| *dst = value, exec)
}

/// [`replay_copy_raw`] into a potentially uninitialized destination.
///
/// On success every reachable destination element is initialized and no
/// other slot is written. The destination is never read.
///
/// # Errors
///
/// As [`replay_copy_raw`].
///
/// # Examples
///
/// ```rust
/// use core::mem::MaybeUninit;
/// use strided_basic::{replay_copy_raw_uninit, Exec, RawStridedMut, RawStridedRef};
///
/// let src = [1.0f64, 2.0, 3.0];
/// let mut storage = [MaybeUninit::<f64>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut storage, &[3], &[1], 0).unwrap();
/// let source = RawStridedRef::new(&src, &[3], &[-1], 2).unwrap();
/// replay_copy_raw_uninit(&mut dst, &source, Exec::serial()).unwrap();
/// drop(dst);
/// // SAFETY: every reachable destination slot was initialized above.
/// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
/// assert_eq!(values, [3.0, 2.0, 1.0]);
/// ```
pub fn replay_copy_raw_uninit<T>(
    dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
    src: &RawStridedRef<'_, T>,
    exec: Exec<'_>,
) -> Result<()>
where
    T: Copy + Send + Sync,
{
    replay_given(
        dest,
        src,
        |dst: &mut MaybeUninit<T>, value: T| {
            dst.write(value);
        },
        exec,
    )
}

/// `f(&mut dest[i], src[i])` for every element, replaying the axes of the two
/// views exactly as given.
///
/// Traversal, width and errors are those of [`replay_copy_raw`], and so is the
/// allocation guarantee, which covers the replay only: allocations made by `f`
/// are its own. `f` runs once per logical element with exactly its arithmetic,
/// so an accumulate such as `|d, s| *d += s` is exact. The order in which
/// elements are visited is unspecified, and on a parallel replay `f` runs
/// concurrently on disjoint slots: the result is defined only for an `f` whose
/// effect depends on the supplied slot values alone. On a destination that is
/// not proven injective, the elements are visited serially in column-major
/// order of the given axes.
/// For an `FnMut`, or for element types that are not `Send + Sync`, use
/// [`replay_map_raw_serial`].
///
/// # Errors
///
/// As [`replay_copy_raw`].
///
/// # Examples
///
/// ```rust
/// use strided_basic::{replay_map_raw, Exec, RawStridedMut, RawStridedRef};
///
/// let src = [1.0f64, 2.0, 3.0, 4.0];
/// let mut acc = [10.0f64, 20.0, 30.0, 40.0];
/// let source = RawStridedRef::new(&src, &[2, 2], &[2, 1], 0).unwrap();
/// let mut dst = RawStridedMut::new(&mut acc, &[2, 2], &[1, 2], 0).unwrap();
/// replay_map_raw(&mut dst, &source, |d, s| *d += s, Exec::serial()).unwrap();
/// assert_eq!(acc, [11.0, 23.0, 32.0, 44.0]);
/// ```
pub fn replay_map_raw<D, S, F>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    f: F,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    F: Fn(&mut D, S) + Send + Sync,
{
    replay_given(dest, src, f, exec)
}

/// [`replay_map_raw`] on the calling thread, for callbacks and elements that
/// are not `Send + Sync`: `f(&mut dest[i], src[i])` for every element, with
/// `f` an `FnMut`.
///
/// The traversal, the errors and the visit order are those of
/// [`replay_map_raw`] under [`Exec::serial()`]: both walk the same route
/// through the same leaves. `f` is called exactly once per logical element,
/// sequentially on the calling thread, column-major over the given axes with
/// axis 0 fastest. The one exception is a destination proven injective whose
/// layout the shared cache-block model tiles: the walk then goes tile by tile,
/// the tile grid and each tile column-major. A destination that is not proven
/// injective is always walked column-major, so an accumulating `f` sees a
/// repeated slot once per logical index, in that order.
///
/// A successful call allocates nothing at any rank; allocations made by `f`
/// are its own. The wide route uses a rank-bounded amount of the caller's
/// stack. An error may allocate its payload.
///
/// With `D = MaybeUninit<T>` the destination is initialized only if `f`
/// writes its slot on every call: a successful return guarantees that `f` ran
/// exactly once for every reachable destination element, not that it wrote.
///
/// # Errors
///
/// As [`replay_copy_raw`], before `f` first runs.
///
/// # Examples
///
/// A generic copy whose element type need not be `Send` or `Sync`, counting
/// its calls through a captured `Rc`:
///
/// ```rust
/// use std::cell::Cell;
/// use std::rc::Rc;
/// use strided_basic::{replay_map_raw_serial, RawStridedMut, RawStridedRef, Result};
///
/// fn copy_generic<T: Copy>(dst: &mut RawStridedMut<'_, T>, src: &RawStridedRef<'_, T>) -> Result<()> {
///     replay_map_raw_serial(dst, src, |d, s| *d = s)
/// }
///
/// let stored = [0.0f64, 1.0, 2.0, 3.0, 4.0, 5.0]; // column-major 2 x 3
/// let src = RawStridedRef::new(&stored, &[2, 3], &[1, 2], 0).unwrap();
/// let mut out = [0.0f64; 6];
/// let mut dst = RawStridedMut::new(&mut out, &[2, 3], &[3, 1], 0).unwrap();
/// copy_generic(&mut dst, &src).unwrap();
///
/// let calls = Rc::new(Cell::new(0));
/// let counter = Rc::clone(&calls);
/// replay_map_raw_serial(&mut dst, &src, |d, s| {
///     counter.set(counter.get() + 1);
///     *d += s;
/// })
/// .unwrap();
/// drop(dst);
/// assert_eq!(calls.get(), 6);
/// assert_eq!(out, [0.0, 4.0, 8.0, 2.0, 6.0, 10.0]);
/// ```
///
/// An uninitialized destination, filled by a closure that writes every slot:
///
/// ```rust
/// use core::mem::MaybeUninit;
/// use strided_basic::{replay_map_raw_serial, RawStridedMut, RawStridedRef};
///
/// let src = [1.0f64, 2.0, 3.0];
/// let mut storage = [MaybeUninit::<f64>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut storage, &[3], &[1], 0).unwrap();
/// let source = RawStridedRef::new(&src, &[3], &[-1], 2).unwrap();
/// replay_map_raw_serial(&mut dst, &source, |d: &mut MaybeUninit<f64>, s| {
///     d.write(s);
/// })
/// .unwrap();
/// drop(dst);
/// // SAFETY: the closure writes its slot on every call, and the successful
/// // replay called it once for every reachable destination slot, which are
/// // all three slots of `storage`.
/// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
/// assert_eq!(values, [3.0, 2.0, 1.0]);
/// ```
pub fn replay_map_raw_serial<D, S, F>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    mut f: F,
) -> Result<()>
where
    D: Copy,
    S: Copy,
    F: FnMut(&mut D, S),
{
    let (dims, dst_strides) = (dest.dims(), dest.strides());
    with_checked_route::<D, S>(
        dims,
        dst_strides,
        src.dims(),
        src.strides(),
        |route, _, _| {
            let src_ptr = src.data().as_ptr();
            let src_base = src.offset();
            let dst_base = dest.offset();
            let dst_ptr = dest.data_mut().as_mut_ptr();
            // SAFETY: the route is the one `replay_given` builds from exactly the
            // views' dims and strides, so the views' bounds proofs cover every
            // replayed offset and `total_len` checked the nonzero product (see
            // there). `with_checked_route` kept tiles only for a destination
            // proven injective, and an untiled walk is one sequential pass; the
            // exclusive and shared borrows cannot overlap.
            unsafe { replay_route_serial(dst_ptr, dst_base, src_ptr, src_base, route, &mut f) };
        },
    )
}

/// `dest[i] = f(src[i])` into a potentially uninitialized destination.
///
/// `f` cannot read the destination. On success every reachable destination
/// element is initialized and no other slot is written. The visit-order,
/// callback and allocation contract is that of [`replay_map_raw`].
///
/// # Errors
///
/// As [`replay_copy_raw`].
///
/// # Examples
///
/// ```rust
/// use core::mem::MaybeUninit;
/// use strided_basic::{replay_map_raw_uninit, Exec, RawStridedMut, RawStridedRef};
///
/// let src = [1i32, 2, 3];
/// let mut storage = [MaybeUninit::<f64>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut storage, &[3], &[1], 0).unwrap();
/// let source = RawStridedRef::new(&src, &[3], &[1], 0).unwrap();
/// replay_map_raw_uninit(&mut dst, &source, |s| f64::from(s) * 0.5, Exec::serial()).unwrap();
/// drop(dst);
/// // SAFETY: every reachable destination slot was initialized above.
/// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
/// assert_eq!(values, [0.5, 1.0, 1.5]);
/// ```
pub fn replay_map_raw_uninit<D, S, F>(
    dest: &mut RawStridedMut<'_, MaybeUninit<D>>,
    src: &RawStridedRef<'_, S>,
    f: F,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    F: Fn(S) -> D + Send + Sync,
{
    replay_given(
        dest,
        src,
        move |dst: &mut MaybeUninit<D>, value: S| {
            dst.write(f(value));
        },
        exec,
    )
}

/// `f(&mut dest[i], src[i])` after fusing the two layouts inside the call.
///
/// [`replay_map_raw`] replays the axes exactly as given, so a caller that holds
/// an unfused layout has to fuse it first and pays that pass per call. This
/// entry performs the same fusion [`copy_scale_raw`] does before choosing the
/// route, then replays with the caller's token; the small-block fusion cost is
/// therefore inside the crate, once, instead of at every call site.
///
/// The traversal, width, callback and allocation contracts are those of
/// [`replay_map_raw`]: the visit order is unspecified, and a successful call
/// allocates nothing at any rank on a serial token, or on a pooled token whose
/// replay is not tiled above [`RAW_FUSED_RANK_LIMIT`] moving axes. The fusion
/// itself holds its scratch on the stack, so it does not allocate either.
///
/// # Errors
///
/// As [`replay_map_raw`].
///
/// # Examples
///
/// ```rust
/// use strided_basic::{replay_map_raw_fused, Exec, RawStridedMut, RawStridedRef};
///
/// let src = [1.0f64, 2.0, 3.0, 4.0];
/// let mut acc = [10.0f64, 20.0, 30.0, 40.0];
/// let source = RawStridedRef::new(&src, &[2, 2], &[2, 1], 0).unwrap();
/// // The destination is transposed relative to the source; the fused entry
/// // fuses the two layouts before it walks them.
/// let mut dst = RawStridedMut::new(&mut acc, &[2, 2], &[1, 2], 0).unwrap();
/// replay_map_raw_fused(&mut dst, &source, |d, s| *d += s, Exec::serial()).unwrap();
/// assert_eq!(acc, [11.0, 23.0, 32.0, 44.0]);
/// ```
pub fn replay_map_raw_fused<D, S, F>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    f: F,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    F: Fn(&mut D, S) + Send + Sync,
{
    replay_fused_given(dest, src, f, exec)
}

/// [`replay_map_raw_fused`] into a potentially uninitialized destination.
///
/// `f` cannot read the destination. On success every reachable destination
/// element is initialized and no other slot is written. The fused traversal,
/// callback and allocation contract is that of [`replay_map_raw_fused`].
///
/// # Errors
///
/// As [`replay_map_raw`].
///
/// # Examples
///
/// ```rust
/// use core::mem::MaybeUninit;
/// use strided_basic::{replay_map_raw_uninit_fused, Exec, RawStridedMut, RawStridedRef};
///
/// let src = [1i32, 2, 3];
/// let mut storage = [MaybeUninit::<f64>::uninit(); 3];
/// let mut dst = RawStridedMut::new(&mut storage, &[3], &[1], 0).unwrap();
/// let source = RawStridedRef::new(&src, &[3], &[1], 0).unwrap();
/// replay_map_raw_uninit_fused(&mut dst, &source, |s| f64::from(s) * 0.5, Exec::serial())
///     .unwrap();
/// drop(dst);
/// // SAFETY: every reachable destination slot was initialized above.
/// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
/// assert_eq!(values, [0.5, 1.0, 1.5]);
/// ```
pub fn replay_map_raw_uninit_fused<D, S, F>(
    dest: &mut RawStridedMut<'_, MaybeUninit<D>>,
    src: &RawStridedRef<'_, S>,
    f: F,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    F: Fn(S) -> D + Send + Sync,
{
    replay_fused_given(
        dest,
        src,
        move |dst: &mut MaybeUninit<D>, value: S| {
            dst.write(f(value));
        },
        exec,
    )
}

/// Fuse the compacted moving axes of the pair on the stack, then replay them.
///
/// [`fuse_pair_traversal`] keeps a `Vec` for an original rank above
/// [`RAW_FUSED_RANK_LIMIT`]; this path compacts extent-1 axes first and holds
/// both the compacted and the fused axes in fixed arrays, so the fusion adds no
/// allocation at any rank. The element count is checked before the arrays are
/// indexed, which also bounds the moving-axis count by
/// [`MAX_MOVING_AXES`].
fn replay_fused_given<D, S, Apply>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    apply: Apply,
    exec: Exec<'_>,
) -> Result<()>
where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Send + Sync,
{
    ensure_same_dims(dest.dims(), src.dims())?;
    if crate::kernel::total_len(dest.dims())? == 0 {
        return Ok(());
    }

    let mut dims = [1usize; MAX_MOVING_AXES];
    let mut dst_strides = [0isize; MAX_MOVING_AXES];
    let mut src_strides = [0isize; MAX_MOVING_AXES];
    let mut moving = 0;
    for ((&dim, &dst), &src_stride) in dest.dims().iter().zip(dest.strides()).zip(src.strides()) {
        if dim == 1 {
            continue;
        }
        // INVARIANT: the checked nonzero count gives `2^moving <= total`, so
        // `moving < MAX_MOVING_AXES`.
        dims[moving] = dim;
        dst_strides[moving] = dst;
        src_strides[moving] = src_stride;
        moving += 1;
    }

    let mut fused = [EMPTY_AXIS; MAX_MOVING_AXES];
    let rank = fuse_axes(
        &mut fused[..moving.max(1)],
        &dims[..moving],
        &dst_strides[..moving],
        &src_strides[..moving],
    );
    let mut fused_dims = [1usize; MAX_MOVING_AXES];
    let mut fused_dst = [0isize; MAX_MOVING_AXES];
    let mut fused_src = [0isize; MAX_MOVING_AXES];
    for (slot, axis) in fused[..rank].iter().enumerate() {
        fused_dims[slot] = axis.dim;
        fused_dst[slot] = axis.dst;
        fused_src[slot] = axis.src;
    }

    let dst_offset = dest.offset();
    let src_offset = src.offset();
    // SAFETY: fusion only reorders and merges the compacted moving axes, so the
    // set of reachable offsets is unchanged and the views' constructors already
    // proved that set inside their data.
    let mut dest = unsafe {
        RawStridedMut::new_unchecked(
            dest.data_mut(),
            &fused_dims[..rank],
            &fused_dst[..rank],
            dst_offset,
        )
    };
    let src = unsafe {
        RawStridedRef::new_unchecked(
            src.data(),
            &fused_dims[..rank],
            &fused_src[..rank],
            src_offset,
        )
    };
    replay_given(&mut dest, &src, apply, exec)
}

#[cfg(test)]
#[path = "raw_ops/tests/tests.rs"]
mod tests;

#[cfg(test)]
#[path = "raw_ops/tests/replay_tests.rs"]
mod replay_tests;

#[cfg(test)]
#[path = "raw_ops/tests/tiled_tests.rs"]
mod tiled_tests;