jkl 0.2.1

Asset compression and packing tool
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
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
pub mod block;
pub mod compress;
pub mod filter;
pub mod format;
pub mod tiles;

/// The spatial extent of an image, encoding both size and dimensionality.
///
/// Each variant carries only the dimensions relevant to that image type,
/// so a `D2` stores width and height while a `D1Array` stores width and
/// layer count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Extent {
    /// A single-row, 1D image.
    D1 { width: usize },
    /// A 2D image.
    D2 { width: usize, height: usize },
    /// A 3D (volumetric) image.
    D3 {
        width: usize,
        height: usize,
        depth: usize,
    },
    /// An array of 1D images.
    D1Array { width: usize, layers: usize },
    /// An array of 2D images.
    D2Array {
        width: usize,
        height: usize,
        layers: usize,
    },
}

impl Extent {
    /// Returns the width (first dimension).
    pub fn width(&self) -> usize {
        match *self {
            Extent::D1 { width } => width,
            Extent::D2 { width, .. } => width,
            Extent::D3 { width, .. } => width,
            Extent::D1Array { width, .. } => width,
            Extent::D2Array { width, .. } => width,
        }
    }

    /// Returns the height, or `1` for dimensionalities without a height axis.
    pub fn height(&self) -> usize {
        match *self {
            Extent::D1 { .. } => 1,
            Extent::D2 { height, .. } => height,
            Extent::D3 { height, .. } => height,
            Extent::D1Array { .. } => 1,
            Extent::D2Array { height, .. } => height,
        }
    }

    /// Returns the depth, or `1` for non-volumetric extents.
    pub fn depth(&self) -> usize {
        match *self {
            Extent::D1 { .. } => 1,
            Extent::D2 { .. } => 1,
            Extent::D3 { depth, .. } => depth,
            Extent::D1Array { .. } => 1,
            Extent::D2Array { .. } => 1,
        }
    }

    /// Returns the layer count, or `1` for non-array extents.
    pub fn layers(&self) -> usize {
        match *self {
            Extent::D1 { .. } => 1,
            Extent::D2 { .. } => 1,
            Extent::D3 { .. } => 1,
            Extent::D1Array { layers, .. } => layers,
            Extent::D2Array { layers, .. } => layers,
        }
    }

    /// Returns the [`Dimensions`] discriminant for this extent.
    pub fn dimensions(self) -> Dimensions {
        match self {
            Extent::D1 { .. } => Dimensions::D1,
            Extent::D2 { .. } => Dimensions::D2,
            Extent::D3 { .. } => Dimensions::D3,
            Extent::D1Array { .. } => Dimensions::D1,
            Extent::D2Array { .. } => Dimensions::D2,
        }
    }

    /// Converts this extent into a `[width, height, depth_or_layers]` triple.
    pub fn raw_size(self) -> [usize; 3] {
        match self {
            Extent::D1 { width } => [width, 1, 1],
            Extent::D2 { width, height } => [width, height, 1],
            Extent::D3 {
                width,
                height,
                depth,
            } => [width, height, depth],
            Extent::D1Array { width, layers } => [width, 1, layers],
            Extent::D2Array {
                width,
                height,
                layers,
            } => [width, height, layers],
        }
    }

    /// Reconstructs an `Extent` from a raw `[width, height, depth_or_layers]`
    /// triple and a [`Dimensions`] tag.
    ///
    /// Returns `None` if the values are inconsistent with the
    /// chosen dimensionality (e.g. height ≠ 1 for `D1`).
    pub fn from_raw_size(value: [usize; 3], dimensions: Dimensions) -> Option<Self> {
        match dimensions {
            Dimensions::D1 => {
                if value[1] != 1 || value[2] != 1 {
                    return None;
                }
                Some(Extent::D1 { width: value[0] })
            }
            Dimensions::D2 => {
                if value[2] != 1 {
                    return None;
                }
                Some(Extent::D2 {
                    width: value[0],
                    height: value[1],
                })
            }
            Dimensions::D3 => Some(Extent::D3 {
                width: value[0],
                height: value[1],
                depth: value[2],
            }),
            Dimensions::D1Array => {
                if value[1] != 1 {
                    return None;
                }
                Some(Extent::D1Array {
                    width: value[0],
                    layers: value[2],
                })
            }
            Dimensions::D2Array => Some(Extent::D2Array {
                width: value[0],
                height: value[1],
                layers: value[2],
            }),
        }
    }
}

/// Discriminant for the dimensionality of an image, without carrying
/// size information.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Dimensions {
    /// One-dimensional.
    D1,
    /// Two-dimensional.
    D2,
    /// Three-dimensional (volumetric).
    D3,
    /// Array of one-dimensional images.
    D1Array,
    /// Array of two-dimensional images.
    D2Array,
}

/// An immutable, non-owning 2D rectangular view into a pixel buffer.
///
/// `Image2DRef` borrows a flat slice of pixel data and interprets it as a 2D image
/// with the given `width`, `height`, and row `stride`. It is `Copy` and `Clone`,
/// making it cheap to pass around.
///
/// # Type Parameters
///
/// * `T` - The pixel type. Must be `Copy` for most operations.
pub struct Image2DRef<'a, T> {
    /// The width of the image view in pixels.
    width: usize,
    /// The height of the image view in pixels.
    height: usize,
    /// The number of `T` elements between the start of consecutive rows.
    stride: usize,
    /// The underlying pixel data. Length must be at least `(height - 1) * stride + width`.
    pixels: &'a [T],
}

impl<T> Copy for Image2DRef<'_, T> {}
impl<T> Clone for Image2DRef<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> Image2DRef<'a, T> {
    /// Creates a new `Image2DRef` with contiguous row storage (stride equals width).
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `pixels` - The underlying pixel data slice.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len() < height * width`.
    pub fn new(width: usize, height: usize, pixels: &'a [T]) -> Self {
        assert!(pixels.len() >= height * width);
        Image2DRef {
            width,
            height,
            stride: width,
            pixels,
        }
    }

    /// Creates a new `Image2DRef` with a custom row stride.
    ///
    /// Use this when the pixel data has padding between rows, e.g. when
    /// the view represents a sub-region of a larger image.
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `pixels` - The underlying pixel data slice.
    /// * `stride` - The number of `T` elements between the start of consecutive rows.
    ///
    /// # Panics
    ///
    /// Panics if pixels is too short to contain all pixels from the specified dimensions and stride.
    pub fn with_stride(width: usize, height: usize, stride: usize, pixels: &'a [T]) -> Self {
        let plane_len = len2([width, height], stride);
        assert!(pixels.len() >= plane_len);
        Image2DRef {
            width,
            height,
            stride,
            pixels,
        }
    }

    /// Creates a new `Image2DRef` from a single row of pixels.
    pub fn from_row(pixels: &'a [T]) -> Self {
        Image2DRef {
            width: pixels.len(),
            height: 1,
            stride: pixels.len(),
            pixels,
        }
    }

    /// Returns the width of this image in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height of this image in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns a copy of this image view (equivalent to `Copy` since views are non-owning).
    pub fn as_ref(&self) -> Image2DRef<'_, T> {
        *self
    }

    /// Returns a reference to the pixel at coordinates (`x`, `y`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `y * stride + x` is out of bounds.
    pub fn get(&self, x: usize, y: usize) -> &'a T {
        assert!(x < self.width);
        assert!(y < self.height);

        &self.pixels[y * self.stride + x]
    }

    /// Returns a reference to the row at vertical coordinate `y`.
    pub fn row(&self, y: usize) -> &'a [T] {
        assert!(y < self.height);
        &self.pixels[y * self.stride..][..self.width]
    }

    /// Returns a sub-region of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range(&self, x: usize, y: usize, w: usize, h: usize) -> Image2DRef<'a, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);

        Image2DRef {
            width: w,
            height: h,
            stride: self.stride,
            pixels: &self.pixels[y * self.stride + x..],
        }
    }

    /// Returns a sub-region of this image as a new `Image2DRef`.
    ///
    /// The returned view is described by `rect`.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_rect(&self, rect: crate::math::Rect<usize>) -> Image2DRef<'a, T> {
        self.get_range(rect.x, rect.y, rect.w, rect.h)
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels(&self) -> &'a [T] {
        self.pixels
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_rows(&self) -> impl DoubleEndedIterator<Item = &'a [T]> + use<'a, T> {
        let Self {
            width,
            height,
            stride,
            pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks(stride)
            .map(move |row| &row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_pixels(&self) -> impl DoubleEndedIterator<Item = &'a T> + use<'a, T> {
        let Self {
            width,
            height,
            stride,
            pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks(stride)
            .flat_map(move |row| &row[..width])
    }

    /// Copies this image view into a fixed-size `W`×`H` array.
    ///
    /// # Panics
    ///
    /// Panics if the image dimensions do not match `W` and `H`.
    pub fn into_matrix<const W: usize, const H: usize>(self) -> [[T; W]; H]
    where
        T: Copy,
    {
        assert_eq!(self.width, W);
        assert_eq!(self.height, H);

        let mut colors = [[self.pixels[0]; W]; H];

        for (y, row) in colors.iter_mut().enumerate() {
            row.copy_from_slice(self.row(y));
        }

        colors
    }
}

/// A mutable, non-owning 2D rectangular view into a pixel buffer.
///
/// `Image2DMut` borrows a flat slice of pixel data mutably and interprets it as a 2D image
/// with the given `width`, `height`, and row `stride`. It supports reading, writing,
/// sub-region extraction, copying from an `Image2DRef`, and random/patch-based initialization.
///
/// # Type Parameters
///
/// * `T` - The pixel type. Must be `Copy` for most operations.
pub struct Image2DMut<'a, T> {
    /// The width of the image view in pixels.
    width: usize,
    /// The height of the image view in pixels.
    height: usize,
    /// The number of `T` elements between the start of consecutive rows.
    stride: usize,
    /// The underlying mutable pixel data. Length must be at least `(height - 1) * stride + width`.
    pixels: &'a mut [T],
}

impl<'a, T> Image2DMut<'a, T> {
    /// Creates a new `Image2DMut` with contiguous row storage (stride equals width).
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `pixels` - The underlying mutable pixel data slice.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len() < height * width`.
    pub fn new(width: usize, height: usize, pixels: &'a mut [T]) -> Self {
        assert!(pixels.len() >= height * width);
        Image2DMut {
            width,
            height,
            stride: width,
            pixels,
        }
    }

    /// Creates a new `Image2DMut` with a custom row stride.
    ///
    /// Use this when the pixel data has padding between rows, e.g. when
    /// the view represents a sub-region of a larger image.
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `pixels` - The underlying mutable pixel data slice.
    /// * `stride` - The number of `T` elements between the start of consecutive rows.
    ///
    /// # Panics
    ///
    /// Panics if pixels is too short to contain all pixels from the specified dimensions and stride.
    pub fn with_stride(width: usize, height: usize, stride: usize, pixels: &'a mut [T]) -> Self {
        let plane_len = len2([width, height], stride);
        assert!(pixels.len() >= plane_len);
        Image2DMut {
            width,
            height,
            stride,
            pixels,
        }
    }

    /// Creates a new `Image2DMut` from a single row of pixels.
    pub fn from_row(pixels: &'a mut [T]) -> Self {
        Image2DMut {
            width: pixels.len(),
            height: 1,
            stride: pixels.len(),
            pixels,
        }
    }

    /// Creates a new `Image2DMut` by reborrowing its pixel data mutably.
    ///
    /// The returned view has the same dimensions and stride as the input reference.
    pub fn reborrow(&mut self) -> Image2DMut<'_, T> {
        Image2DMut {
            width: self.width,
            height: self.height,
            stride: self.stride,
            pixels: &mut *self.pixels,
        }
    }

    /// Returns the width of this image in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height of this image in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns an immutable view of this image.
    pub fn as_ref(&self) -> Image2DRef<'_, T> {
        Image2DRef {
            width: self.width,
            height: self.height,
            stride: self.stride,
            pixels: &*self.pixels,
        }
    }

    /// Returns a mutable view of this image with a reborrowed lifetime.
    pub fn as_mut(&mut self) -> Image2DMut<'_, T> {
        Image2DMut {
            width: self.width,
            height: self.height,
            stride: self.stride,
            pixels: &mut *self.pixels,
        }
    }

    /// Returns a reference to the pixel at coordinates (`x`, `y`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `y * stride + x` is out of bounds.
    pub fn get(&self, x: usize, y: usize) -> &T {
        &self.pixels[y * self.stride + x]
    }

    /// Returns a reference to the row at vertical coordinate `y`.
    pub fn row(&self, y: usize) -> &'_ [T] {
        assert!(y < self.height);
        &self.pixels[y * self.stride..][..self.width]
    }

    /// Returns a reference to the pixel at coordinates (`x`, `y`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `y * stride + x` is out of bounds.
    pub fn get_mut(&mut self, x: usize, y: usize) -> &mut T {
        &mut self.pixels[y * self.stride + x]
    }

    /// Returns a reference to the row at vertical coordinate `y`.
    pub fn row_mut(&mut self, y: usize) -> &'_ mut [T] {
        assert!(y < self.height);
        &mut self.pixels[y * self.stride..][..self.width]
    }

    /// Sets the pixel at coordinates (`x`, `y`) to `value`.
    ///
    /// # Panics
    ///
    /// Panics if the computed index `y * stride + x` is out of bounds.
    pub fn set(&mut self, x: usize, y: usize, value: T) {
        self.pixels[y * self.stride + x] = value;
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels(&self) -> &[T] {
        &*self.pixels
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels_mut(&mut self) -> &mut [T] {
        &mut *self.pixels
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_rows(&self) -> impl Iterator<Item = &'_ [T]> + use<'_, T> {
        let Self {
            width,
            height,
            stride,
            ref pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks(stride)
            .map(move |row| &row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_rows_mut(&mut self) -> impl Iterator<Item = &mut [T]> + use<'_, T> {
        let Self {
            width,
            height,
            stride,
            ref mut pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks_mut(stride)
            .map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn into_iter_rows(self) -> impl Iterator<Item = &'a mut [T]> + use<'a, T> {
        let Self {
            width,
            height,
            stride,
            pixels,
        } = self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks_mut(stride)
            .map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_pixels(&self) -> impl Iterator<Item = &T> + use<'_, T> {
        let Self {
            width,
            height,
            stride,
            ref pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks(stride)
            .flat_map(move |row| &row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn iter_pixels_mut(&mut self) -> impl Iterator<Item = &'_ mut T> + use<'_, T> {
        let Self {
            width,
            height,
            stride,
            ref mut pixels,
        } = *self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks_mut(stride)
            .flat_map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    pub fn into_iter_pixels(self) -> impl Iterator<Item = &'a mut T> + use<'a, T> {
        let Self {
            width,
            height,
            stride,
            pixels,
        } = self;

        let plane_len = len2([width, height], stride);

        pixels[..plane_len]
            .chunks_mut(stride)
            .flat_map(move |row| &mut row[..width])
    }

    /// Returns a immutable sub-region of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range(&mut self, x: usize, y: usize, w: usize, h: usize) -> Image2DRef<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);

        Image2DRef {
            width: w,
            height: h,
            stride: self.stride,
            pixels: &self.pixels[y * self.stride + x..],
        }
    }

    /// Returns an immutable sub-region of this image as a new `Image2DRef`.
    ///
    /// The returned view is described by `rect`.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_rect(&mut self, rect: crate::math::Rect<usize>) -> Image2DRef<'_, T> {
        self.get_range(rect.x, rect.y, rect.w, rect.h)
    }

    /// Returns a mutable sub-region of this image as a new `Image2DMut`.
    ///
    /// The returned view starts at (`x`, `y`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_mut(&mut self, x: usize, y: usize, w: usize, h: usize) -> Image2DMut<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);

        Image2DMut {
            width: w,
            height: h,
            stride: self.stride,
            pixels: &mut self.pixels[y * self.stride + x..],
        }
    }

    /// Returns a mutable sub-region of this image as a new `Image2DMut`.
    ///
    /// The returned view is described by `rect`.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_rect_mut(&mut self, rect: crate::math::Rect<usize>) -> Image2DMut<'_, T> {
        self.get_range_mut(rect.x, rect.y, rect.w, rect.h)
    }

    /// Copies pixel data from `src` into this image.
    ///
    /// # Panics
    ///
    /// Panics if `src` and `self` have different dimensions.
    pub fn copy_from(&mut self, src: Image2DRef<'_, T>)
    where
        T: Copy,
    {
        assert_eq!(src.width, self.width);
        assert_eq!(src.height, self.height);

        for j in 0..src.height {
            self.row_mut(j).copy_from_slice(src.row(j));
        }
    }

    /// Copies pixel data from a fixed-size `W`×`H` array into this image.
    ///
    /// # Panics
    ///
    /// Panics if the image dimensions do not match `W` and `H`.
    pub fn copy_from_matrix<const W: usize, const H: usize>(&mut self, matrix: &[[T; W]; H])
    where
        T: Copy,
    {
        assert_eq!(self.width, W);
        assert_eq!(self.height, H);

        for (y, row) in matrix.iter().enumerate() {
            self.row_mut(y).copy_from_slice(row);
        }
    }
}

/// An immutable, non-owning 3D view into a pixel buffer.
///
/// `Image3DRef` borrows a flat slice of pixel data and interprets it as a 3D image
/// with the given `width`, `height`, and row `stride`. It is `Copy` and `Clone`,
/// making it cheap to pass around.
///
/// # Type Parameters
///
/// * `T` - The pixel type. Must be `Copy` for most operations.
pub struct Image3DRef<'a, T> {
    /// The width of the image view in pixels.
    width: usize,
    /// The height of the image view in pixels.
    height: usize,
    /// The depth of the image view in pixels.
    depth: usize,
    /// The number of `T` elements between the start of consecutive rows.
    row_stride: usize,
    /// The number of `T` elements between the start of consecutive planes.
    plane_stride: usize,
    /// The underlying pixel data. Length must be at least `(depth - 1) * plane_stride + (height - 1) * row_stride + width`.
    pixels: &'a [T],
}

impl<T> Copy for Image3DRef<'_, T> {}
impl<T> Clone for Image3DRef<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> Image3DRef<'a, T> {
    /// Creates a new `Image3DRef` with contiguous row storage (row stride equals width, plane stride equals width * height).
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `depth` - The depth of the image in pixels.
    /// * `pixels` - The underlying pixel data slice.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len() < height * width`.
    pub fn new(width: usize, height: usize, depth: usize, pixels: &'a [T]) -> Self {
        assert!(pixels.len() >= depth * height * width);
        Image3DRef {
            width,
            height,
            depth,
            row_stride: width,
            plane_stride: width * height,
            pixels,
        }
    }

    /// Creates a new `Image3DRef` with a custom row stride.
    ///
    /// Use this when the pixel data has padding between rows, e.g. when
    /// the view represents a sub-region of a larger image.
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `pixels` - The underlying pixel data slice.
    /// * `stride` - The number of `T` elements between the start of consecutive rows.
    ///
    /// # Panics
    ///
    /// Panics if pixels is too short to contain all pixels from the specified dimensions and stride.
    pub fn with_stride(
        width: usize,
        height: usize,
        depth: usize,
        row_stride: usize,
        plane_stride: usize,
        pixels: &'a [T],
    ) -> Self {
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);
        assert!(pixels.len() >= volume_len);
        Image3DRef {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        }
    }

    /// Creates a new `Image3DRef` from a single row of pixels.
    pub fn from_row(pixels: &'a [T]) -> Self {
        Image3DRef {
            width: pixels.len(),
            height: 1,
            depth: 1,
            row_stride: pixels.len(),
            plane_stride: pixels.len(),
            pixels,
        }
    }

    /// Creates a new `Image3DRef` from a single XY plane of pixels.
    pub fn from_plane(plane: Image2DRef<'a, T>) -> Self {
        let plane_len = len2([plane.width, plane.height], plane.stride);
        Image3DRef {
            width: plane.width,
            height: plane.height,
            depth: 1,
            row_stride: plane.stride,
            plane_stride: plane_len,
            pixels: plane.pixels,
        }
    }

    /// Returns the width of this image in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height of this image in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the depth of this image in pixels.
    pub fn depth(&self) -> usize {
        self.depth
    }

    /// Returns a reference to the pixel at coordinates (`x`, `y`, `z`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `z * plane_stride + y * row_stride + x` is out of bounds.
    pub fn get(&self, x: usize, y: usize, z: usize) -> &'a T {
        assert!(x < self.width);
        assert!(y < self.height);
        assert!(z < self.depth);

        &self.pixels[z * self.plane_stride + y * self.row_stride + x]
    }

    /// Returns a reference to the entire row at coordinates (`y`, `z`).
    pub fn row(&self, y: usize, z: usize) -> &'a [T] {
        assert!(y < self.height);
        assert!(z < self.depth);
        &self.pixels[z * self.plane_stride + y * self.row_stride..][..self.width]
    }

    /// Returns a reference to the entire XY plane at coordinate `z`.
    pub fn get_plane_xy(&self, z: usize) -> Image2DRef<'a, T> {
        assert!(z < self.depth);

        Image2DRef {
            width: self.width,
            height: self.height,
            stride: self.row_stride,
            pixels: &self.pixels[z * self.plane_stride..],
        }
    }

    /// Returns a reference to the entire XZ plane at coordinate `y`.
    pub fn get_plane_xz(&self, y: usize) -> Image2DRef<'a, T> {
        assert!(y < self.height);

        Image2DRef {
            width: self.width,
            height: self.depth,
            stride: self.plane_stride,
            pixels: &self.pixels[y * self.row_stride..],
        }
    }

    /// Returns a reference to a sub-region of XY plane of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xy(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DRef<'a, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z < self.depth);

        Image2DRef {
            width: w,
            height: h,
            stride: self.row_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a reference to a sub-region of XZ plane of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xz(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DRef<'a, T> {
        assert!(x + w <= self.width);
        assert!(y < self.height);
        assert!(z + h <= self.depth);

        Image2DRef {
            width: w,
            height: h,
            stride: self.plane_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a sub-region of this image as a new `Image3DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h` × `d`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
        d: usize,
    ) -> Image3DRef<'a, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z + d <= self.depth);

        Image3DRef {
            width: w,
            height: h,
            depth: d,
            row_stride: self.row_stride,
            plane_stride: self.plane_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels(&self) -> &'a [T] {
        self.pixels
    }

    /// Returns an iterator over all planes in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn iter_planes(&self) -> impl DoubleEndedIterator<Item = Image2DRef<'a, T>> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = *self;

        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .map(move |plane| Image2DRef {
                width,
                height,
                stride: row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn iter_rows(&self) -> impl DoubleEndedIterator<Item = &'a [T]> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks(row_stride))
            .map(move |row| &row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn iter_pixels(&self) -> impl DoubleEndedIterator<Item = &'a T> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks(row_stride))
            .flat_map(move |row| &row[..width])
    }
}

/// A mutable, non-owning 3D view into a pixel buffer.
///
/// `Image3DMut` borrows a flat slice of pixel data mutably and interprets it as a 3D image
/// with the given `width`, `height`, and row `stride`. It supports reading, writing,
/// sub-region extraction, copying from an `Image2DRef`, and random/patch-based initialization.
///
/// # Type Parameters
///
/// * `T` - The pixel type. Must be `Copy` for most operations.
pub struct Image3DMut<'a, T> {
    /// The width of the image view in pixels.
    width: usize,
    /// The height of the image view in pixels.
    height: usize,
    /// The depth of the image view in pixels.
    depth: usize,
    /// The number of `T` elements between the start of consecutive rows.
    row_stride: usize,
    /// The number of `T` elements between the start of consecutive planes.
    plane_stride: usize,
    /// The underlying mutable pixel data. Length must be at least `(depth - 1) * plane_stride + (height - 1) * row_stride + width`.
    pixels: &'a mut [T],
}

impl<'a, T> Image3DMut<'a, T> {
    /// Creates a new `Image3DMut` with contiguous row storage (stride equals width).
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `depth` - The depth of the image in pixels.
    /// * `pixels` - The underlying mutable pixel data slice.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len() < height * width * depth`.
    pub fn new(width: usize, height: usize, depth: usize, pixels: &'a mut [T]) -> Self {
        assert!(pixels.len() >= height * width * depth);
        Image3DMut {
            width,
            height,
            depth,
            row_stride: width,
            plane_stride: width * height,
            pixels,
        }
    }

    /// Creates a new `Image3DMut` with a custom row stride.
    ///
    /// Use this when the pixel data has padding between rows, e.g. when
    /// the view represents a sub-region of a larger image.
    ///
    /// # Parameters
    ///
    /// * `width` - The width of the image in pixels.
    /// * `height` - The height of the image in pixels.
    /// * `depth` - The depth of the image in pixels.
    /// * `pixels` - The underlying mutable pixel data slice.
    /// * `row_stride` - The number of `T` elements between the start of consecutive rows.
    /// * `plane_stride` - The number of `T` elements between the start of consecutive planes.
    ///
    /// # Panics
    ///
    /// Panics if pixels is too short to contain all pixels from the specified dimensions and strides.
    pub fn with_stride(
        width: usize,
        height: usize,
        depth: usize,
        row_stride: usize,
        plane_stride: usize,
        pixels: &'a mut [T],
    ) -> Self {
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);
        assert!(pixels.len() >= volume_len);
        Image3DMut {
            width,
            height,
            depth,
            pixels,
            row_stride,
            plane_stride,
        }
    }

    /// Creates a new `Image3DMut` from a single row of pixels.
    pub fn from_row(pixels: &'a mut [T]) -> Self {
        Image3DMut {
            width: pixels.len(),
            height: 1,
            depth: 1,
            row_stride: pixels.len(),
            plane_stride: pixels.len(),
            pixels,
        }
    }

    /// Creates a new `Image3DMut` from a single XY plane of pixels.
    pub fn from_plane(plane: Image2DMut<'a, T>) -> Self {
        let plane_len = len2([plane.width, plane.height], plane.stride);
        Image3DMut {
            width: plane.width,
            height: plane.height,
            depth: 1,
            row_stride: plane.stride,
            plane_stride: plane_len,
            pixels: plane.pixels,
        }
    }

    /// Returns the width of this image in pixels.
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height of this image in pixels.
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns the depth of this image in pixels.
    pub fn depth(&self) -> usize {
        self.depth
    }

    /// Creates a new `Image3DMut` by reborrowing its pixel data immutably.
    pub fn as_ref(&self) -> Image3DRef<'_, T> {
        Image3DRef {
            width: self.width,
            height: self.height,
            depth: self.depth,
            row_stride: self.row_stride,
            plane_stride: self.plane_stride,
            pixels: &*self.pixels,
        }
    }

    /// Creates a new `Image3DMut` by reborrowing its pixel data mutably.
    pub fn as_mut(&mut self) -> Image3DMut<'_, T> {
        Image3DMut {
            width: self.width,
            height: self.height,
            depth: self.depth,
            row_stride: self.row_stride,
            plane_stride: self.plane_stride,
            pixels: &mut *self.pixels,
        }
    }

    /// Returns an immutable reference to the pixel at coordinates (`x`, `y`, `z`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `z * plane_stride + y * row_stride + x` is out of bounds.
    pub fn get(&self, x: usize, y: usize, z: usize) -> &T {
        assert!(x < self.width);
        assert!(y < self.height);
        assert!(z < self.depth);

        &self.pixels[z * self.plane_stride + y * self.row_stride + x]
    }

    /// Returns a mutable reference to the pixel at coordinates (`x`, `y`, `z`).
    ///
    /// # Panics
    ///
    /// Panics if the computed index `z * plane_stride + y * row_stride + x` is out of bounds.
    pub fn get_mut(&mut self, x: usize, y: usize, z: usize) -> &mut T {
        assert!(x < self.width);
        assert!(y < self.height);
        assert!(z < self.depth);

        &mut self.pixels[z * self.plane_stride + y * self.row_stride + x]
    }

    /// Returns an immutable reference to the entire row at coordinates (`y`, `z`).
    pub fn row(&self, y: usize, z: usize) -> &[T] {
        assert!(y < self.height);
        assert!(z < self.depth);
        &self.pixels[z * self.plane_stride + y * self.row_stride..][..self.width]
    }

    /// Returns a mutable reference to the entire row at coordinates (`y`, `z`).
    pub fn row_mut(&mut self, y: usize, z: usize) -> &mut [T] {
        assert!(y < self.height);
        assert!(z < self.depth);
        &mut self.pixels[z * self.plane_stride + y * self.row_stride..][..self.width]
    }

    /// Returns an immutable reference to the entire XY plane at coordinate `z`.
    pub fn get_plane_xy(&self, z: usize) -> Image2DRef<'_, T> {
        assert!(z < self.depth);

        Image2DRef {
            width: self.width,
            height: self.height,
            stride: self.row_stride,
            pixels: &self.pixels[z * self.plane_stride..],
        }
    }

    /// Returns a mutable reference to the entire XY plane at coordinate `z`.
    pub fn get_plane_xy_mut(&mut self, z: usize) -> Image2DMut<'_, T> {
        assert!(z < self.depth);

        Image2DMut {
            width: self.width,
            height: self.height,
            stride: self.row_stride,
            pixels: &mut self.pixels[z * self.plane_stride..],
        }
    }

    /// Returns an immutable reference to the entire XZ plane at coordinate `y`.
    pub fn get_plane_xz(&self, y: usize) -> Image2DRef<'_, T> {
        assert!(y < self.height);

        Image2DRef {
            width: self.width,
            height: self.depth,
            stride: self.plane_stride,
            pixels: &self.pixels[y * self.row_stride..],
        }
    }

    /// Returns a mutable reference to the entire XZ plane at coordinate `y`.
    pub fn get_plane_xz_mut(&mut self, y: usize) -> Image2DMut<'_, T> {
        assert!(y < self.height);

        Image2DMut {
            width: self.width,
            height: self.depth,
            stride: self.plane_stride,
            pixels: &mut self.pixels[y * self.row_stride..],
        }
    }

    /// Returns an immutable reference to a sub-region of XY plane of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xy(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DRef<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z < self.depth);

        Image2DRef {
            width: w,
            height: h,
            stride: self.row_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a mutable reference to a sub-region of XY plane of this image as a new `Image2DMut`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xy_mut(
        &mut self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DMut<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z < self.depth);

        Image2DMut {
            width: w,
            height: h,
            stride: self.row_stride,
            pixels: &mut self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns an immutable reference to a sub-region of XZ plane of this image as a new `Image2DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xz(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DRef<'_, T> {
        assert!(x + w <= self.width);
        assert!(y < self.height);
        assert!(z + h <= self.depth);

        Image2DRef {
            width: w,
            height: h,
            stride: self.plane_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a mutable reference to a sub-region of XZ plane of this image as a new `Image2DMut`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_xz_mut(
        &mut self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
    ) -> Image2DMut<'_, T> {
        assert!(x + w <= self.width);
        assert!(y < self.height);
        assert!(z + h <= self.depth);

        Image2DMut {
            width: w,
            height: h,
            stride: self.plane_stride,
            pixels: &mut self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a sub-region of this image as a new `Image3DRef`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h` × `d`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range(
        &self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
        d: usize,
    ) -> Image3DRef<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z + d <= self.depth);

        Image3DRef {
            width: w,
            height: h,
            depth: d,
            row_stride: self.row_stride,
            plane_stride: self.plane_stride,
            pixels: &self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns a sub-region of this image as a new `Image3DMut`.
    ///
    /// The returned view starts at (`x`, `y`, `z`) and has dimensions `w` × `h` × `d`.
    /// It shares the same underlying pixel data and stride.
    ///
    /// # Panics
    ///
    /// Panics if the sub-region extends beyond the image bounds.
    pub fn get_range_mut(
        &mut self,
        x: usize,
        y: usize,
        z: usize,
        w: usize,
        h: usize,
        d: usize,
    ) -> Image3DMut<'_, T> {
        assert!(x + w <= self.width);
        assert!(y + h <= self.height);
        assert!(z + d <= self.depth);

        Image3DMut {
            width: w,
            height: h,
            depth: d,
            row_stride: self.row_stride,
            plane_stride: self.plane_stride,
            pixels: &mut self.pixels[z * self.plane_stride + y * self.row_stride + x..],
        }
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels(&self) -> &[T] {
        self.pixels
    }

    /// Returns the raw underlying pixel slice.
    pub fn pixels_mut(&mut self) -> &mut [T] {
        self.pixels
    }

    /// Returns an iterator over all planes in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn iter_planes(&self) -> impl DoubleEndedIterator<Item = Image2DRef<'_, T>> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref pixels,
        } = *self;

        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .map(move |plane| Image2DRef {
                width,
                height,
                stride: row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all planes in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn iter_planes_mut(
        &mut self,
    ) -> impl DoubleEndedIterator<Item = Image2DMut<'_, T>> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref mut pixels,
        } = *self;

        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .map(move |plane| Image2DMut {
                width,
                height,
                stride: row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all planes in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn into_iter_planes(
        self,
    ) -> impl DoubleEndedIterator<Item = Image2DMut<'a, T>> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = self;

        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .map(move |plane| Image2DMut {
                width,
                height,
                stride: row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn iter_rows(&self) -> impl DoubleEndedIterator<Item = &[T]> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks(row_stride))
            .map(move |row| &row[..width])
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn iter_rows_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut [T]> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref mut pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks_mut(row_stride))
            .map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn into_iter_rows(self) -> impl DoubleEndedIterator<Item = &'a mut [T]> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks_mut(row_stride))
            .map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn iter_pixels(&self) -> impl DoubleEndedIterator<Item = &T> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks(row_stride))
            .flat_map(move |row| &row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn iter_pixels_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + use<'_, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            ref mut pixels,
        } = *self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks_mut(row_stride))
            .flat_map(move |row| &mut row[..width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    pub fn into_iter_pixels(self) -> impl DoubleEndedIterator<Item = &'a mut T> + use<'a, T> {
        let Self {
            width,
            height,
            depth,
            row_stride,
            plane_stride,
            pixels,
        } = self;

        let plane_len = len2([width, height], row_stride);
        let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

        pixels[..volume_len]
            .chunks_mut(plane_stride)
            .flat_map(move |plane| plane[..plane_len].chunks_mut(row_stride))
            .flat_map(move |row| &mut row[..width])
    }
}

/// A non-owning, immutable view into a pixel buffer interpreted as an image
/// with a specific [`Dimensions`] and extent.
///
/// Combines the flexibility of arbitrary dimensionality
/// (`D1`, `D2`, `D3`, `D1Array`, `D2Array`) with a uniform interface for
/// iteration, slicing, and layer extraction.
pub struct ImageRef<'a, T> {
    dimensions: Dimensions,
    extent: [usize; 3],
    stride: [usize; 2],
    pixels: &'a [T],
}

impl<'a, T> Copy for ImageRef<'a, T> {}
impl<'a, T> Clone for ImageRef<'a, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, T> ImageRef<'a, T> {
    /// Creates a new `ImageRef` with contiguous storage.
    ///
    /// `extent` is `[width, height_or_layers, depth_or_layers]` interpreted
    /// according to `dimensions`. Unused axes must be `1`.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len()` does not equal the total element count, or if
    /// unused axes are not `1`.
    pub fn new(dimensions: Dimensions, extent: [usize; 3], pixels: &'a [T]) -> Self {
        let len = match dimensions {
            Dimensions::D1 => {
                assert_eq!(extent[1], 1);
                assert_eq!(extent[2], 1);
                extent[0]
            }
            Dimensions::D2 => {
                assert_eq!(extent[2], 1);
                extent[0] * extent[1]
            }
            Dimensions::D3 => extent[0] * extent[1] * extent[2],
            Dimensions::D1Array => {
                assert_eq!(extent[2], 1);
                extent[0] * extent[1]
            }
            Dimensions::D2Array => extent[0] * extent[1] * extent[2],
        };

        assert_eq!(pixels.len(), len);

        ImageRef {
            dimensions,
            extent,
            stride: [extent[0], extent[0] * extent[1]],
            pixels,
        }
    }

    /// Creates a new `ImageRef` with custom row and plane strides.
    ///
    /// `stride[0]` is the row stride, `stride[1]` is the plane / layer stride.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len()` does not match the computed length.
    pub fn with_stride(
        dimensions: Dimensions,
        extent: [usize; 3],
        stride: [usize; 2],
        pixels: &'a [T],
    ) -> Self {
        let len = match dimensions {
            Dimensions::D1 => {
                assert_eq!(extent[1], 1);
                assert_eq!(extent[2], 1);
                extent[0]
            }
            Dimensions::D2 | Dimensions::D1Array => {
                assert_eq!(extent[2], 1);
                len2([extent[0], extent[1]], stride[0])
            }
            Dimensions::D3 | Dimensions::D2Array => len3(extent, stride),
        };

        assert_eq!(pixels.len(), len);

        ImageRef {
            dimensions,
            extent,
            stride,
            pixels,
        }
    }

    /// Shorthand for creating a 1D image.
    pub fn new_1d(width: usize, pixels: &'a [T]) -> Self {
        ImageRef::new(Dimensions::D1, [width, 1, 1], pixels)
    }

    /// Shorthand for creating a 2D image.
    pub fn new_2d(width: usize, height: usize, pixels: &'a [T]) -> Self {
        ImageRef::new(Dimensions::D2, [width, height, 1], pixels)
    }

    /// Shorthand for creating a 3D image.
    pub fn new_3d(width: usize, height: usize, depth: usize, pixels: &'a [T]) -> Self {
        ImageRef::new(Dimensions::D3, [width, height, depth], pixels)
    }

    /// Shorthand for creating a 1D array image.
    pub fn new_1d_array(width: usize, layers: usize, pixels: &'a [T]) -> Self {
        ImageRef::new(Dimensions::D1Array, [width, layers, 1], pixels)
    }

    /// Shorthand for creating a 2D array image.
    pub fn new_2d_array(width: usize, height: usize, layers: usize, pixels: &'a [T]) -> Self {
        ImageRef::new(Dimensions::D2Array, [width, height, layers], pixels)
    }

    /// Shorthand for creating a 2D image with a custom row stride.
    pub fn with_stride_2d(width: usize, height: usize, stride: usize, pixels: &'a [T]) -> Self {
        ImageRef::with_stride(Dimensions::D2, [width, height, 1], [stride, 0], pixels)
    }

    /// Shorthand for creating a 3D image with custom strides.
    pub fn with_stride_3d(
        width: usize,
        height: usize,
        depth: usize,
        row_stride: usize,
        plane_stride: usize,
        pixels: &'a [T],
    ) -> Self {
        ImageRef::with_stride(
            Dimensions::D3,
            [width, height, depth],
            [row_stride, plane_stride],
            pixels,
        )
    }

    /// Shorthand for creating a 1D array image with a custom stride.
    pub fn with_stride_1d_array(
        width: usize,
        layers: usize,
        stride: usize,
        pixels: &'a [T],
    ) -> Self {
        ImageRef::with_stride(Dimensions::D1Array, [width, layers, 1], [stride, 0], pixels)
    }

    /// Shorthand for creating a 2D array image with custom strides.
    pub fn with_stride_2d_array(
        width: usize,
        height: usize,
        layers: usize,
        row_stride: usize,
        layer_stride: usize,
        pixels: &'a [T],
    ) -> Self {
        ImageRef::with_stride(
            Dimensions::D2Array,
            [width, height, layers],
            [row_stride, layer_stride],
            pixels,
        )
    }

    /// Returns the dimensionality of this image.
    pub fn dimensions(&self) -> Dimensions {
        self.dimensions
    }

    /// Returns the [`Extent`] of this image.
    pub fn extent(&self) -> Extent {
        match self.dimensions {
            Dimensions::D1 => Extent::D1 {
                width: self.extent[0],
            },
            Dimensions::D2 => Extent::D2 {
                width: self.extent[0],
                height: self.extent[1],
            },
            Dimensions::D3 => Extent::D3 {
                width: self.extent[0],
                height: self.extent[1],
                depth: self.extent[2],
            },
            Dimensions::D1Array => Extent::D1Array {
                width: self.extent[0],
                layers: self.extent[1],
            },
            Dimensions::D2Array => Extent::D2Array {
                width: self.extent[0],
                height: self.extent[1],
                layers: self.extent[2],
            },
        }
    }

    /// Returns the raw `[width, height_or_layers, depth_or_layers]` triple.
    pub fn raw_extent(&self) -> [usize; 3] {
        self.extent
    }

    /// Returns the image width.
    pub fn width(&self) -> usize {
        self.extent[0]
    }

    /// Returns the image height, or `1` for 1D / 1D-array types.
    pub fn height(&self) -> usize {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D1Array => 1,
            _ => self.extent[1],
        }
    }

    /// Returns the image depth, or `1` for non-volumetric types.
    pub fn depth(&self) -> usize {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D1Array | Dimensions::D2 | Dimensions::D2Array => 1,
            Dimensions::D3 => self.extent[2],
        }
    }

    /// Returns the number of layers in this image. For non-array types, this will return 1.
    pub fn layers(&self) -> usize {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D2 | Dimensions::D3 => 1,
            Dimensions::D1Array => self.extent[1],
            Dimensions::D2Array => self.extent[2],
        }
    }

    /// Returns a reference to the specified layer of this image. For non-array types, `layer` must be 0.
    /// The returned image reference is a non-array type.
    pub fn layer_ref(&self, layer: usize) -> ImageRef<'a, T> {
        match self.dimensions {
            Dimensions::D1 => {
                assert_eq!(layer, 0);
                ImageRef::new_1d(self.extent[0], self.pixels)
            }
            Dimensions::D2 => {
                assert_eq!(layer, 0);
                ImageRef::new_2d(self.extent[0], self.extent[1], self.pixels)
            }
            Dimensions::D3 => {
                assert_eq!(layer, 0);
                ImageRef::new_3d(self.extent[0], self.extent[1], self.extent[2], self.pixels)
            }
            Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                ImageRef::new_1d(
                    self.extent[0],
                    &self.pixels[layer * self.extent[0]..][..self.extent[0]],
                )
            }
            Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                ImageRef::new_2d(
                    self.extent[0],
                    self.extent[1],
                    &self.pixels[layer * self.extent[0] * self.extent[1]..]
                        [..self.extent[0] * self.extent[1]],
                )
            }
        }
    }

    /// Reinterpret this image as a 3D image, regardless of its original dimensions.
    /// 1D images will be treated as having height and depth equal to 1.
    /// 1D array images will be treated as having height equal to the number of layers and depth 1.
    /// 2D images will be treated as having depth equal to 1.
    /// 2D array images will be treated as having depth equal to the number of layers.
    ///
    /// This is useful to generically treat any image as 3D for algorithms that operate on 3D data,
    /// where the original dimensions may be ignored.
    ///
    /// Layers will be treated as depth dimension,
    /// and missing dimensions will be treated as having extent 1.
    pub fn as_ref_3d(&self) -> Image3DRef<'a, T> {
        Image3DRef {
            width: self.extent[0],
            height: self.extent[1],
            depth: self.extent[2],
            row_stride: self.stride[0],
            plane_stride: self.stride[1],
            pixels: self.pixels,
        }
    }

    /// Reinterpret this image as layered 2D image, regardless of its original dimensions
    /// and returns a reference to the specified layer.
    ///
    /// 1D, both array and non-array images will be treated as having height equal to 1.
    /// 3D images will be treated as having layers equal to the depth dimension.
    /// Which is different than reinterpretation as 3D and taking a plane.
    ///
    /// The main difference from `as_ref_3d` is that layers of D1 are interpreted as layers, not height.
    ///
    /// `self.depth() * self.layers()` must be greater than `layer`, otherwise this method will panic.
    pub fn plane_ref(&self, layer: usize) -> Image2DRef<'a, T> {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                Image2DRef {
                    width: self.extent[0],
                    height: 1,
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[0]..],
                }
            }
            Dimensions::D2 | Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                Image2DRef {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[1]..],
                }
            }
            Dimensions::D3 => {
                assert!(layer < self.extent[2]);
                Image2DRef {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[1]..],
                }
            }
        }
    }

    /// Returns an iterator over all planes in this image in row-major order.
    /// If image is 1D or 1D array, this will return a single-row planes.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn iter_planes(&self) -> impl DoubleEndedIterator<Item = Image2DRef<'a, T>> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .map(move |plane| Image2DRef {
                width: sizes.width,
                height: sizes.height,
                stride: sizes.row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn iter_rows(&self) -> impl DoubleEndedIterator<Item = &'a [T]> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks(sizes.row_stride))
            .map(move |row| &row[..sizes.width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn iter_pixels(&self) -> impl DoubleEndedIterator<Item = &'a T> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks(sizes.row_stride))
            .flat_map(move |row| &row[..sizes.width])
    }
}

/// A non-owning, mutable view into a pixel buffer interpreted as an image
/// with a specific [`Dimensions`] and extent.
pub struct ImageMut<'a, T> {
    dimensions: Dimensions,
    extent: [usize; 3],
    stride: [usize; 2],
    pixels: &'a mut [T],
}

impl<'a, T> ImageMut<'a, T> {
    /// Creates a new `ImageMut` with contiguous storage.
    ///
    /// See [`ImageRef::new`] for the meaning of `dimensions` and `extent`.
    ///
    /// # Panics
    ///
    /// Panics if `pixels.len()` does not equal the total element count.
    pub fn new(dimensions: Dimensions, extent: [usize; 3], pixels: &'a mut [T]) -> Self {
        let len = match dimensions {
            Dimensions::D1 => {
                assert_eq!(extent[1], 1);
                assert_eq!(extent[2], 1);
                extent[0]
            }
            Dimensions::D2 => {
                assert_eq!(extent[2], 1);
                extent[0] * extent[1]
            }
            Dimensions::D3 => extent[0] * extent[1] * extent[2],
            Dimensions::D1Array => {
                assert_eq!(extent[2], 1);
                extent[0] * extent[1]
            }
            Dimensions::D2Array => extent[0] * extent[1] * extent[2],
        };

        assert_eq!(pixels.len(), len);

        ImageMut {
            dimensions,
            extent,
            stride: [extent[0], extent[0] * extent[1]],
            pixels,
        }
    }

    /// Creates a new `ImageMut` with custom row and plane strides.
    ///
    /// See [`ImageRef::with_stride`] for details on stride semantics.
    pub fn with_stride(
        dimensions: Dimensions,
        extent: [usize; 3],
        stride: [usize; 2],
        pixels: &'a mut [T],
    ) -> Self {
        let len = match dimensions {
            Dimensions::D1 => {
                assert_eq!(extent[1], 1);
                assert_eq!(extent[2], 1);
                extent[0]
            }
            Dimensions::D2 | Dimensions::D1Array => {
                assert_eq!(extent[2], 1);
                if extent[1] != 0 && extent[0] != 0 {
                    (extent[1] - 1) * stride[0] + extent[0]
                } else {
                    0
                }
            }
            Dimensions::D3 | Dimensions::D2Array => {
                if extent[2] != 0 && extent[1] != 0 && extent[0] != 0 {
                    (extent[2] - 1) * stride[1] + (extent[1] - 1) * stride[0] + extent[0]
                } else {
                    0
                }
            }
        };

        assert_eq!(pixels.len(), len);

        ImageMut {
            dimensions,
            extent,
            stride,
            pixels,
        }
    }

    /// Shorthand for creating a mutable 1D image.
    pub fn new_1d(width: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::new(Dimensions::D1, [width, 1, 1], pixels)
    }

    /// Shorthand for creating a mutable 2D image.
    pub fn new_2d(width: usize, height: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::new(Dimensions::D2, [width, height, 1], pixels)
    }

    /// Shorthand for creating a mutable 3D image.
    pub fn new_3d(width: usize, height: usize, depth: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::new(Dimensions::D3, [width, height, depth], pixels)
    }

    /// Shorthand for creating a mutable 1D array image.
    pub fn new_1d_array(width: usize, layers: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::new(Dimensions::D1Array, [width, layers, 1], pixels)
    }

    /// Shorthand for creating a mutable 2D array image.
    pub fn new_2d_array(width: usize, height: usize, layers: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::new(Dimensions::D2Array, [width, height, layers], pixels)
    }

    /// Shorthand for creating a mutable 2D image with a custom row stride.
    pub fn with_stride_2d(width: usize, height: usize, stride: usize, pixels: &'a mut [T]) -> Self {
        ImageMut::with_stride(Dimensions::D2, [width, height, 1], [stride, 0], pixels)
    }

    /// Shorthand for creating a mutable 3D image with custom strides.
    pub fn with_stride_3d(
        width: usize,
        height: usize,
        depth: usize,
        row_stride: usize,
        plane_stride: usize,
        pixels: &'a mut [T],
    ) -> Self {
        ImageMut::with_stride(
            Dimensions::D3,
            [width, height, depth],
            [row_stride, plane_stride],
            pixels,
        )
    }

    /// Shorthand for creating a mutable 1D array image with a custom stride.
    pub fn with_stride_1d_array(
        width: usize,
        layers: usize,
        stride: usize,
        pixels: &'a mut [T],
    ) -> Self {
        ImageMut::with_stride(Dimensions::D1Array, [width, layers, 1], [stride, 0], pixels)
    }

    /// Shorthand for creating a mutable 2D array image with custom strides.
    pub fn with_stride_2d_array(
        width: usize,
        height: usize,
        layers: usize,
        row_stride: usize,
        layer_stride: usize,
        pixels: &'a mut [T],
    ) -> Self {
        ImageMut::with_stride(
            Dimensions::D2Array,
            [width, height, layers],
            [row_stride, layer_stride],
            pixels,
        )
    }

    /// Returns the dimensionality of this image.
    pub fn dimensions(&self) -> Dimensions {
        self.dimensions
    }

    /// Returns the raw `[width, height_or_layers, depth_or_layers]` triple.
    pub fn extent(&self) -> [usize; 3] {
        self.extent
    }

    /// Creates a new `ImageRef` by reborrowing its pixel data immutably.
    pub fn as_ref(&self) -> ImageRef<'_, T> {
        ImageRef {
            dimensions: self.dimensions,
            extent: self.extent,
            stride: self.stride,
            pixels: &*self.pixels,
        }
    }

    /// Creates a new `ImageMut` by reborrowing its pixel data mutably.
    pub fn as_mut(&mut self) -> ImageMut<'_, T> {
        ImageMut {
            dimensions: self.dimensions,
            extent: self.extent,
            stride: self.stride,
            pixels: &mut *self.pixels,
        }
    }

    /// Returns the number of layers in this image. For non-array types, this will return 1.
    pub fn layers(&self) -> usize {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D2 | Dimensions::D3 => 1,
            Dimensions::D1Array => self.extent[1],
            Dimensions::D2Array => self.extent[2],
        }
    }

    /// Returns a reference to the specified layer of this image. For non-array types, `layer` must be 0.
    /// The returned image reference is a non-array type.
    pub fn layer_ref(&self, layer: usize) -> ImageRef<'_, T> {
        match self.dimensions {
            Dimensions::D1 => {
                assert_eq!(layer, 0);
                ImageRef::new_1d(self.extent[0], self.pixels)
            }
            Dimensions::D2 => {
                assert_eq!(layer, 0);
                ImageRef::new_2d(self.extent[0], self.extent[1], self.pixels)
            }
            Dimensions::D3 => {
                assert_eq!(layer, 0);
                ImageRef::new_3d(self.extent[0], self.extent[1], self.extent[2], self.pixels)
            }
            Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                ImageRef::new_1d(
                    self.extent[0],
                    &self.pixels[layer * self.extent[0]..][..self.extent[0]],
                )
            }
            Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                ImageRef::new_2d(
                    self.extent[0],
                    self.extent[1],
                    &self.pixels[layer * self.extent[0] * self.extent[1]..]
                        [..self.extent[0] * self.extent[1]],
                )
            }
        }
    }

    /// Returns a mutable reference to the specified layer of this image. For non-array types, `layer` must be 0.
    /// The returned image reference is a non-array type.
    pub fn layer_mut(&mut self, layer: usize) -> ImageMut<'_, T> {
        match self.dimensions {
            Dimensions::D1 => {
                assert_eq!(layer, 0);
                ImageMut::new_1d(self.extent[0], &mut *self.pixels)
            }
            Dimensions::D2 => {
                assert_eq!(layer, 0);
                ImageMut::new_2d(self.extent[0], self.extent[1], &mut *self.pixels)
            }
            Dimensions::D3 => {
                assert_eq!(layer, 0);
                ImageMut::new_3d(
                    self.extent[0],
                    self.extent[1],
                    self.extent[2],
                    &mut *self.pixels,
                )
            }
            Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                ImageMut::new_1d(
                    self.extent[0],
                    &mut self.pixels[layer * self.extent[0]..][..self.extent[0]],
                )
            }
            Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                ImageMut::new_2d(
                    self.extent[0],
                    self.extent[1],
                    &mut self.pixels[layer * self.extent[0] * self.extent[1]..]
                        [..self.extent[0] * self.extent[1]],
                )
            }
        }
    }

    /// Reinterpret this image as a 3D image immutable reference, regardless of its original dimensions.
    ///
    /// This is useful to generically treat any image as 3D for algorithms that operate on 3D data,
    /// where the original dimensions may be ignored.
    ///
    /// Layers will be treated as next dimension,
    /// and missing dimensions will be treated as having extent 1.
    pub fn as_ref_3d(&self) -> Image3DRef<'_, T> {
        Image3DRef {
            width: self.extent[0],
            height: self.extent[1],
            depth: self.extent[2],
            row_stride: self.stride[0],
            plane_stride: self.stride[1],
            pixels: &*self.pixels,
        }
    }

    /// Reinterpret this image as a 3D image mutable reference, regardless of its original dimensions.
    ///
    /// This is useful to generically treat any image as 3D for algorithms that operate on 3D data,
    /// where the original dimensions may be ignored.
    ///
    /// Layers will be treated as next dimension,
    /// and missing dimensions will be treated as having extent 1.
    pub fn as_mut_3d(&mut self) -> Image3DMut<'_, T> {
        Image3DMut {
            width: self.extent[0],
            height: self.extent[1],
            depth: self.extent[2],
            row_stride: self.stride[0],
            plane_stride: self.stride[1],
            pixels: &mut *self.pixels,
        }
    }

    /// Reinterpret this image as layered 2D image, regardless of its original dimensions
    /// and returns a reference to the specified layer.
    ///
    /// 1D, both array and non-array images will be treated as having height equal to 1.
    /// 3D images will be treated as having layers equal to the depth dimension.
    /// Which is different than reinterpretation as 3D and taking a plane.
    ///
    /// The main difference from `as_ref_3d` is that layers of D1 are interpreted as layers, not height.
    ///
    /// `self.depth() * self.layers()` must be greater than `layer`, otherwise this method will panic.
    pub fn plane_ref(&self, layer: usize) -> Image2DRef<'_, T> {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                Image2DRef {
                    width: self.extent[0],
                    height: 1,
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[0]..],
                }
            }
            Dimensions::D2 | Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                Image2DRef {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[1]..],
                }
            }
            Dimensions::D3 => {
                assert!(layer < self.extent[2]);
                Image2DRef {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &self.pixels[layer * self.stride[1]..],
                }
            }
        }
    }

    /// Reinterpret this image as layered 2D image, regardless of its original dimensions
    /// and returns a reference to the specified layer.
    ///
    /// 1D, both array and non-array images will be treated as having height equal to 1.
    /// 3D images will be treated as having layers equal to the depth dimension.
    /// Which is different than reinterpretation as 3D and taking a plane.
    ///
    /// The main difference from `as_ref_3d` is that layers of D1 are interpreted as layers, not height.
    ///
    /// `self.depth() * self.layers()` must be greater than `layer`, otherwise this method will panic.
    pub fn plane_mut(&mut self, layer: usize) -> Image2DMut<'_, T> {
        match self.dimensions {
            Dimensions::D1 | Dimensions::D1Array => {
                assert!(layer < self.extent[1]);
                Image2DMut {
                    width: self.extent[0],
                    height: 1,
                    stride: self.stride[0],
                    pixels: &mut self.pixels[layer * self.stride[0]..],
                }
            }
            Dimensions::D2 | Dimensions::D2Array => {
                assert!(layer < self.extent[2]);
                Image2DMut {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &mut self.pixels[layer * self.stride[1]..],
                }
            }
            Dimensions::D3 => {
                assert!(layer < self.extent[2]);
                Image2DMut {
                    width: self.extent[0],
                    height: self.extent[1],
                    stride: self.stride[0],
                    pixels: &mut self.pixels[layer * self.stride[1]..],
                }
            }
        }
    }

    /// Returns an iterator over all planes in this image in row-major order.
    /// If image is 1D or 1D array, this will return a single-row planes.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn iter_planes(&self) -> impl DoubleEndedIterator<Item = Image2DRef<'_, T>> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .map(move |plane| Image2DRef {
                width: sizes.width,
                height: sizes.height,
                stride: sizes.row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all planes in this image in row-major order.
    /// If image is 1D or 1D array, this will return a single-row planes.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn iter_planes_mut(&mut self) -> impl DoubleEndedIterator<Item = Image2DMut<'_, T>> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .map(move |plane| Image2DMut {
                width: sizes.width,
                height: sizes.height,
                stride: sizes.row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all planes in this image in row-major order.
    /// If image is 1D or 1D array, this will return a single-row planes.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over planes in an image with arbitrary strides,
    /// use `(0..self.depth()).map(|z| self.get_plane_xy(z))` instead.
    pub fn into_iter_planes(self) -> impl DoubleEndedIterator<Item = Image2DMut<'a, T>> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .map(move |plane| Image2DMut {
                width: sizes.width,
                height: sizes.height,
                stride: sizes.row_stride,
                pixels: plane,
            })
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn iter_rows(&self) -> impl DoubleEndedIterator<Item = &'_ [T]> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks(sizes.row_stride))
            .map(move |row| &row[..sizes.width])
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn iter_rows_mut(&mut self) -> impl DoubleEndedIterator<Item = &'_ mut [T]> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks_mut(sizes.row_stride))
            .map(move |row| &mut row[..sizes.width])
    }

    /// Returns an iterator over all rows in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over rows in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_rows())` instead.
    pub fn into_iter_rows(self) -> impl DoubleEndedIterator<Item = &'a mut [T]> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks_mut(sizes.row_stride))
            .map(move |row| &mut row[..sizes.width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn iter_pixels(&self) -> impl DoubleEndedIterator<Item = &'_ T> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks(sizes.row_stride))
            .flat_map(move |row| &row[..sizes.width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn iter_pixels_mut(&mut self) -> impl DoubleEndedIterator<Item = &'_ mut T> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks_mut(sizes.row_stride))
            .flat_map(move |row| &mut row[..sizes.width])
    }

    /// Returns an iterator over all pixels in this image in row-major order.
    ///
    /// # Panics
    ///
    /// Panics if this image reference was constructed with `plane_stride < row_stride * height`.
    /// This is niche case, so this method is focused on performance instead of handling all possible stride configurations.
    ///
    /// In case you want to iterate over pixels in an image with arbitrary strides,
    /// use `(0..self.depth()).flat_map(|z| self.get_plane_xy(z).iter_pixels())` instead.
    pub fn into_iter_pixels(self) -> impl DoubleEndedIterator<Item = &'a mut T> {
        let sizes = sizes(self.dimensions, self.extent, self.stride);

        self.pixels[..sizes.total_len]
            .chunks_mut(sizes.layer_stride)
            .flat_map(move |layer| layer[..sizes.layer_len].chunks_mut(sizes.plane_stride))
            .flat_map(move |plane| plane[..sizes.plane_len].chunks_mut(sizes.row_stride))
            .flat_map(move |row| &mut row[..sizes.width])
    }
}

/// Returns the length of the slice required to store a 2D array with the given extent and stride.
fn len2(extent: [usize; 2], stride: usize) -> usize {
    if extent[0] == 0 || extent[1] == 0 {
        0
    } else {
        (extent[1] - 1) * stride + extent[0]
    }
}

/// Returns the length of the slice required to store a 3D array with the given extent and stride.
fn len3(extent: [usize; 3], stride: [usize; 2]) -> usize {
    if extent[0] == 0 || extent[1] == 0 || extent[2] == 0 {
        0
    } else {
        (extent[2] - 1) * stride[1] + (extent[1] - 1) * stride[0] + extent[0]
    }
}

struct Sizes {
    total_len: usize,
    layer_stride: usize,
    layer_len: usize,
    plane_stride: usize,
    plane_len: usize,
    row_stride: usize,
    height: usize,
    width: usize,
}

fn sizes(dimensions: Dimensions, extent: [usize; 3], stride: [usize; 2]) -> Sizes {
    let total_len = match dimensions {
        Dimensions::D1 => extent[0],
        Dimensions::D2 | Dimensions::D1Array => len2([extent[0], extent[1]], stride[0]),
        Dimensions::D3 | Dimensions::D2Array => len3(extent, stride),
    };

    let layer_stride = match dimensions {
        Dimensions::D1 | Dimensions::D2 | Dimensions::D3 => total_len,
        Dimensions::D1Array => stride[0],
        Dimensions::D2Array => stride[1],
    };

    let layer_len = match dimensions {
        Dimensions::D1 | Dimensions::D2 | Dimensions::D3 => total_len,
        Dimensions::D1Array => extent[0],
        Dimensions::D2Array => len2([extent[0], extent[1]], stride[0]),
    };

    let plane_stride = match dimensions {
        Dimensions::D1 | Dimensions::D1Array | Dimensions::D2 | Dimensions::D2Array => total_len,
        Dimensions::D3 => stride[1],
    };

    let plane_len = match dimensions {
        Dimensions::D1 | Dimensions::D1Array | Dimensions::D2 | Dimensions::D2Array => layer_len,
        Dimensions::D3 => len2([extent[0], extent[1]], stride[0]),
    };

    let row_stride = match dimensions {
        Dimensions::D1 | Dimensions::D1Array => plane_len,
        Dimensions::D2 | Dimensions::D2Array | Dimensions::D3 => stride[0],
    };

    let height = match dimensions {
        Dimensions::D1 | Dimensions::D1Array => 1,
        Dimensions::D2 | Dimensions::D2Array | Dimensions::D3 => extent[1],
    };

    let width = extent[0];

    Sizes {
        total_len,
        layer_stride,
        layer_len,
        plane_stride,
        plane_len,
        row_stride,
        height,
        width,
    }
}

// /// Returns 4 extents of the image,
// /// width, height, depth and layers
// ///
// /// While technically image can't have both depth and layers, this function returns them as if they were separate dimensions,
// fn total_extent(dimensions: Dimensions, extent: [usize; 3]) -> [usize; 4] {
//     match dimensions {
//         Dimensions::D1 => [extent[0], 1, 1, 1],
//         Dimensions::D2 => [extent[0], extent[1], 1, 1],
//         Dimensions::D3 => [extent[0], extent[1], extent[2], 1],
//         Dimensions::D1Array => [extent[0], 1, 1, extent[1]],
//         Dimensions::D2Array => [extent[0], extent[1], 1, extent[2]],
//     }
// }

// /// Returns 3 strides of the image,
// /// row stride, plane stride and layer stride
// ///
// /// For missing stride kind it takes last stride and multiplies it by the corresponding extent.
// fn total_stride(dimensions: Dimensions, extent: [usize; 3], stride: [usize; 2]) -> [usize; 3] {
//     let [width, height, depth, _] = total_extent(dimensions, extent);
//     let [row_stride, plane_stride] = stride;

//     let plane_len = len2([width, height], row_stride);
//     let volume_len = len3([width, height, depth], [row_stride, plane_stride]);

//     match dimensions {
//         Dimensions::D1 => [width; 3],
//         Dimensions::D2 => [row_stride, plane_len, plane_len],
//         Dimensions::D3 => [row_stride, plane_stride, volume_len],
//         Dimensions::D1Array => [row_stride, row_stride, row_stride],
//         Dimensions::D2Array => [row_stride, plane_stride, plane_stride],
//     }
// }

// impl<'a, T> ImageRef<'a, T> {
//     /// Calculates total error between the reference map patch and the given block using the provided error function.
//     ///
//     /// Compares each pixel in `block` against the corresponding pixel in `self` starting
//     /// at offset (`x`, `y`). The per-pixel errors are accumulated via addition.
//     ///
//     /// # Parameters
//     ///
//     /// * `x` - Left offset into `self` where the comparison starts.
//     /// * `y` - Top offset into `self` where the comparison starts.
//     /// * `block` - The block to compare against this image region.
//     /// * `error` - A function that computes the error between two pixels.
//     ///
//     /// # Panics
//     ///
//     /// Panics if the block placed at (`x`, `y`) extends beyond the image bounds.
//     pub fn match_block<'b, U>(
//         &self,
//         x: usize,
//         y: usize,
//         block: Image2DRef<'b, T>,
//         mut error: impl FnMut(T, T) -> U,
//     ) -> U
//     where
//         T: Copy + 'a + 'b,
//         U: ops::Add<Output = U> + Zero,
//     {
//         assert!(x + block.width() <= self.width());
//         assert!(y + block.height() <= self.height());

//         let mut acc = U::zero();

//         for j in 0..block.height() {
//             for i in 0..block.width() {
//                 let r = *self.get(x + i, y + j);
//                 let b = *block.get(i, j);

//                 acc = acc + error(r, b);
//             }
//         }

//         acc
//     }

//     /// Calculates total error between the reference map patch and the given block using the provided error function, but returns `None` if the error exceeds the given upper bound.
//     ///
//     /// This is an early-exit variant of [`match_block`](Self::match_block). If the accumulated
//     /// error exceeds `upper_bound` at any point during iteration, the function immediately
//     /// returns `None`, avoiding unnecessary computation.
//     ///
//     /// # Parameters
//     ///
//     /// * `x` - Left offset into `self` where the comparison starts.
//     /// * `y` - Top offset into `self` where the comparison starts.
//     /// * `block` - The block to compare against this image region.
//     /// * `upper_bound` - Maximum acceptable total error. If exceeded, returns `None`.
//     /// * `error` - A function that computes the error between two pixels.
//     ///
//     /// # Returns
//     ///
//     /// `Some(total_error)` if the total error is within the upper bound, or `None` otherwise.
//     /// Also returns `None` if the image has zero width or height.
//     ///
//     /// # Panics
//     ///
//     /// Panics if the block placed at (`x`, `y`) extends beyond the image bounds.
//     pub fn match_block_upper_bound<'b, U>(
//         &self,
//         x: usize,
//         y: usize,
//         block: Image2DRef<'b, T>,
//         upper_bound: U,
//         mut error: impl FnMut(T, T) -> U,
//     ) -> Option<U>
//     where
//         T: Copy + 'a + 'b,
//         U: ops::Add<Output = U> + PartialOrd + Zero,
//     {
//         assert!(x + block.width() <= self.width());
//         assert!(y + block.height() <= self.height());

//         let mut acc = U::zero();

//         for j in 0..block.height() {
//             for i in 0..block.width() {
//                 let a = *self.get(x + i, y + j);
//                 let b = *block.get(i, j);

//                 acc = acc + error(a, b);
//                 if acc > upper_bound {
//                     return None;
//                 }
//             }
//         }

//         Some(acc)
//     }

//     /// Finds the position within this image where the given block best matches (lowest error).
//     ///
//     /// Performs a strided exhaustive search over all valid placements of `block` within `self`,
//     /// stepping by `step_x` horizontally and `step_y` vertically. Uses early-exit upper-bound
//     /// pruning via [`match_block_upper_bound`](Self::match_block_upper_bound) to skip
//     /// positions that cannot improve on the current best.
//     ///
//     /// The search starts at position (0, 0) as the initial candidate, then scans the remainder
//     /// of the first row before proceeding to subsequent rows.
//     ///
//     /// # Parameters
//     ///
//     /// * `step_x` - Horizontal step size between candidate positions.
//     /// * `step_y` - Vertical step size between candidate positions.
//     /// * `block` - The block to search for within this image.
//     /// * `error` - A function that computes the per-pixel error between two pixels.
//     ///
//     /// # Returns
//     ///
//     /// A tuple of `(best_error, (x, y))` where `(x, y)` is the top-left position of the
//     /// best-matching region.
//     ///
//     /// # Panics
//     ///
//     /// Panics if the block dimensions exceed the image dimensions.
//     pub fn find_best_match<'b, U>(
//         &self,
//         step_x: usize,
//         step_y: usize,
//         block: Image2DRef<'b, T>,
//         mut error: impl FnMut(T, T) -> U,
//     ) -> (U, (usize, usize))
//     where
//         T: Copy + 'a + 'b,
//         U: ops::Add<Output = U> + PartialOrd + Copy + Zero,
//     {
//         assert!(block.width() <= self.width());
//         assert!(block.height() <= self.height());

//         if self.width() == 0 || self.height() == 0 {
//             return (U::zero(), (0, 0));
//         }

//         // Calculate error for the starting point.
//         let mut best_error = self.match_block(0, 0, block.as_ref(), &mut error);
//         let mut best = (0, 0);

//         for y in 0..1 {
//             for x in (1..self.width() - block.width() + 1).step_by(step_x) {
//                 if let Some(error) =
//                     self.match_block_upper_bound(x, y, block.as_ref(), best_error, &mut error)
//                 {
//                     best_error = error;
//                     best = (x, y);
//                 }
//             }
//         }

//         for y in (1..(self.height() - block.height() + 1)).step_by(step_y) {
//             for x in (0..self.width() - block.width() + 1).step_by(step_x) {
//                 if let Some(error) =
//                     self.match_block_upper_bound(x, y, block.as_ref(), best_error, &mut error)
//                 {
//                     best_error = error;
//                     best = (x, y);
//                 }
//             }
//         }

//         (best_error, best)
//     }

//     /// Returns residuals between the reference map patch and the given block using the provided residual function.
//     ///
//     /// For each pixel in `input`, computes `residual(self_pixel, input_pixel)` and writes
//     /// the result into the corresponding position of `output`. The reference patch in `self`
//     /// starts at offset (`x`, `y`).
//     ///
//     /// # Parameters
//     ///
//     /// * `x` - Left offset into `self` for the reference patch.
//     /// * `y` - Top offset into `self` for the reference patch.
//     /// * `input` - The input block to compute residuals against.
//     /// * `output` - The mutable image to write residual values into. Must have the same
//     ///   dimensions as `input`.
//     /// * `residual` - A function that computes the residual between a reference pixel and
//     ///   an input pixel.
//     ///
//     /// # Panics
//     ///
//     /// Panics if `input` and `output` dimensions do not match.
//     pub fn residual<'b, 'c>(
//         &self,
//         x: usize,
//         y: usize,
//         input: Image2DRef<'b, T>,
//         mut output: Image2DMut<'c, T>,
//         mut residual: impl FnMut(T, T) -> T,
//     ) where
//         T: Copy + 'a + 'b + 'c,
//     {
//         if self.width() == 0 || self.height() == 0 {
//             return;
//         }

//         assert_eq!(input.width(), output.width());
//         assert_eq!(input.height(), output.height());

//         for j in 0..input.height() {
//             for i in 0..input.width() {
//                 let a = *self.get(x + i, y + j);
//                 let b = *input.get(i, j);

//                 output.set(i, j, residual(a, b));
//             }
//         }
//     }
// }