hdf5-pure-rust 0.3.1

Pure Rust implementation of the HDF5 file format
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
use std::ops::{Range, RangeFrom, RangeFull, RangeTo};

use crate::{Error, Result};

const MAX_MATERIALIZED_SELECTION_POINTS: usize = 1_000_000;

/// A selection specifies which elements to read from a dataset.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Selection {
    /// No elements.
    None,
    /// All elements.
    All,
    /// Explicit point coordinates in row-major result order.
    Points(Vec<Vec<u64>>),
    /// Regular hyperslab with start, stride, count, and block per dimension.
    Hyperslab(Vec<HyperslabDim>),
    /// A contiguous range along each dimension.
    Slice(Vec<SliceInfo>),
}

/// HDF5-style selection class.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionType {
    None,
    All,
    Points,
    Hyperslab,
}

/// Slice specification for one dimension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SliceInfo {
    pub start: u64,
    pub end: u64,  // exclusive
    pub step: u64, // must be 1 for now
}

/// Regular hyperslab specification for one dimension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HyperslabDim {
    pub start: u64,
    pub stride: u64,
    pub count: u64,
    pub block: u64,
}

/// Iterator over selected coordinates in row-major order.
#[derive(Debug, Clone)]
pub struct SelectionPointIter {
    points: Vec<Vec<u64>>,
    index: usize,
}

impl Iterator for SelectionPointIter {
    type Item = Vec<u64>;

    fn next(&mut self) -> Option<Self::Item> {
        let point = self.points.get(self.index)?.clone();
        self.index += 1;
        Some(point)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.points.len().saturating_sub(self.index);
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for SelectionPointIter {}

impl SelectionPointIter {
    /// Return the number of elements remaining in this selection iterator.
    pub fn select_iter_nelmts(&self) -> usize {
        self.len()
    }

    /// Return the next selected coordinate.
    pub fn select_iter_next(&mut self) -> Option<Vec<u64>> {
        self.next()
    }

    /// Return up to `max_points` remaining selected coordinates.
    pub fn select_iter_get_seq_list(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.take(max_points).collect()
    }

    /// Reset this selection iterator to the first selected coordinate.
    pub fn select_iter_reset(&mut self) {
        self.index = 0;
    }

    /// Explicit release hook for parity with HDF5's selection iterator API.
    pub fn select_iter_release(self) {}

    /// Hyperslab-specific iterator element count alias.
    pub fn hyper_iter_nelmts(&self) -> usize {
        self.len()
    }

    /// Hyperslab-specific iterator next-coordinate alias.
    pub fn hyper_iter_next(&mut self) -> Option<Vec<u64>> {
        self.next()
    }

    /// Hyperslab-specific iterator next-block alias.
    pub fn hyper_iter_next_block(&mut self) -> Option<Vec<u64>> {
        self.next()
    }

    /// Hyperslab-specific iterator sequence-list alias.
    pub fn hyper_iter_get_seq_list(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.take(max_points).collect()
    }

    /// Hyperslab-specific optimized sequence-list alias.
    pub fn hyper_iter_get_seq_list_opt(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.hyper_iter_get_seq_list(max_points)
    }

    /// Hyperslab-specific single-block sequence-list alias.
    pub fn hyper_iter_get_seq_list_single(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.hyper_iter_get_seq_list(max_points)
    }

    /// Hyperslab-specific generic sequence-list alias.
    pub fn hyper_iter_get_seq_list_gen(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.hyper_iter_get_seq_list(max_points)
    }

    /// Hyperslab-specific iterator release alias.
    pub fn hyper_iter_release(self) {}

    /// Point-specific iterator coordinate alias.
    pub fn point_iter_coords(&self) -> Option<&[u64]> {
        self.points.get(self.index).map(Vec::as_slice)
    }

    /// Point-specific iterator element count alias.
    pub fn point_iter_nelmts(&self) -> usize {
        self.len()
    }

    /// Point-specific iterator next-coordinate alias.
    pub fn point_iter_next(&mut self) -> Option<Vec<u64>> {
        self.next()
    }

    /// Point-specific iterator next-block alias.
    pub fn point_iter_next_block(&mut self) -> Option<Vec<u64>> {
        self.next()
    }

    /// Point-specific iterator sequence-list alias.
    pub fn point_iter_get_seq_list(&mut self, max_points: usize) -> Vec<Vec<u64>> {
        self.take(max_points).collect()
    }

    /// Point-specific iterator release alias.
    pub fn point_iter_release(self) {}
}

impl HyperslabDim {
    pub fn new(start: u64, stride: u64, count: u64, block: u64) -> Self {
        Self {
            start,
            stride,
            count,
            block,
        }
    }

    pub fn output_count(&self) -> u64 {
        self.checked_output_count().unwrap_or(u64::MAX)
    }

    pub fn checked_output_count(&self) -> Result<u64> {
        self.count
            .checked_mul(self.block)
            .ok_or_else(|| Error::InvalidFormat("hyperslab output count overflow".into()))
    }
}

impl SliceInfo {
    pub fn new(start: u64, end: u64) -> Self {
        Self {
            start,
            end,
            step: 1,
        }
    }

    pub fn with_step(start: u64, end: u64, step: u64) -> Self {
        Self { start, end, step }
    }

    pub fn count(&self) -> u64 {
        if self.step == 0 {
            0
        } else if self.end > self.start {
            (self.end - self.start).div_ceil(self.step)
        } else {
            0
        }
    }
}

/// Trait for types that can be converted to a Selection.
pub trait IntoSelection {
    fn into_selection(self, shape: &[u64]) -> Selection;
}

/// Trait for one dimension of a multi-dimensional slice selection.
pub trait IntoSliceDim {
    fn into_slice_dim(self, extent: u64) -> SliceInfo;
}

impl IntoSelection for Selection {
    fn into_selection(self, _shape: &[u64]) -> Selection {
        self
    }
}

// For 1D: Range<usize>
impl IntoSelection for Range<usize> {
    fn into_selection(self, _shape: &[u64]) -> Selection {
        Selection::Slice(vec![SliceInfo::new(self.start as u64, self.end as u64)])
    }
}

impl IntoSliceDim for Range<usize> {
    fn into_slice_dim(self, _extent: u64) -> SliceInfo {
        SliceInfo::new(self.start as u64, self.end as u64)
    }
}

// For 1D: RangeFull (..)
impl IntoSelection for RangeFull {
    fn into_selection(self, _shape: &[u64]) -> Selection {
        Selection::All
    }
}

impl IntoSliceDim for RangeFull {
    fn into_slice_dim(self, extent: u64) -> SliceInfo {
        SliceInfo::new(0, extent)
    }
}

// For 1D: RangeFrom (start..)
impl IntoSelection for RangeFrom<usize> {
    fn into_selection(self, shape: &[u64]) -> Selection {
        let end = if shape.is_empty() { 0 } else { shape[0] };
        Selection::Slice(vec![SliceInfo::new(self.start as u64, end)])
    }
}

impl IntoSliceDim for RangeFrom<usize> {
    fn into_slice_dim(self, extent: u64) -> SliceInfo {
        SliceInfo::new(self.start as u64, extent)
    }
}

// For 1D: RangeTo (..end)
impl IntoSelection for RangeTo<usize> {
    fn into_selection(self, _shape: &[u64]) -> Selection {
        Selection::Slice(vec![SliceInfo::new(0, self.end as u64)])
    }
}

impl IntoSliceDim for RangeTo<usize> {
    fn into_slice_dim(self, _extent: u64) -> SliceInfo {
        SliceInfo::new(0, self.end as u64)
    }
}

// Tuples for 2D selections.
impl<A, B> IntoSelection for (A, B)
where
    A: IntoSliceDim,
    B: IntoSliceDim,
{
    fn into_selection(self, shape: &[u64]) -> Selection {
        let dim0 = shape.first().copied().unwrap_or(0);
        let dim1 = shape.get(1).copied().unwrap_or(0);
        Selection::Slice(vec![
            self.0.into_slice_dim(dim0),
            self.1.into_slice_dim(dim1),
        ])
    }
}

// Tuples for 3D selections.
impl<A, B, C> IntoSelection for (A, B, C)
where
    A: IntoSliceDim,
    B: IntoSliceDim,
    C: IntoSliceDim,
{
    fn into_selection(self, shape: &[u64]) -> Selection {
        let dim0 = shape.first().copied().unwrap_or(0);
        let dim1 = shape.get(1).copied().unwrap_or(0);
        let dim2 = shape.get(2).copied().unwrap_or(0);
        Selection::Slice(vec![
            self.0.into_slice_dim(dim0),
            self.1.into_slice_dim(dim1),
            self.2.into_slice_dim(dim2),
        ])
    }
}

impl Selection {
    /// Create a none selection.
    pub fn select_none() -> Self {
        Selection::None
    }

    /// None-selection iterator block alias.
    pub fn none_iter_block() -> Option<Vec<u64>> {
        None
    }

    /// None-selection iterator element-count alias.
    pub fn none_iter_nelmts() -> usize {
        0
    }

    /// None-selection iterator sequence-list alias.
    pub fn none_iter_get_seq_list() -> Vec<Vec<u64>> {
        Vec::new()
    }

    /// None-selection iterator release alias.
    pub fn none_iter_release() {}

    /// None-selection release alias.
    pub fn none_release() {}

    /// None-selection copy alias.
    pub fn none_copy() -> Selection {
        Selection::None
    }

    /// None-selection validity alias.
    pub fn none_is_valid() -> bool {
        true
    }

    /// Serialize a none selection.
    pub fn none_serialize() -> Vec<u8> {
        Vec::new()
    }

    /// Deserialize a none selection.
    pub fn none_deserialize(bytes: &[u8]) -> Result<Selection> {
        if bytes.is_empty() {
            Ok(Selection::None)
        } else {
            Err(Error::InvalidFormat(
                "none selection serialization must be empty".into(),
            ))
        }
    }

    /// None-selection bounds alias.
    pub fn none_bounds() -> Option<(Vec<u64>, Vec<u64>)> {
        None
    }

    /// None-selection offset alias.
    pub fn none_offset(_offsets: &[i64]) -> Selection {
        Selection::None
    }

    /// None-selection contiguous alias.
    pub fn none_is_contiguous() -> bool {
        true
    }

    /// None-selection single-element alias.
    pub fn none_is_single() -> bool {
        false
    }

    /// None-selection regularity alias.
    pub fn none_is_regular() -> bool {
        true
    }

    /// None-selection block-intersection alias.
    pub fn none_intersect_block(_start: &[u64], _end: &[u64]) -> bool {
        false
    }

    /// None-selection unsigned adjust alias.
    pub fn none_adjust_u(_offsets: &[u64]) -> Selection {
        Selection::None
    }

    /// None-selection signed adjust alias.
    pub fn none_adjust_s(_offsets: &[i64]) -> Selection {
        Selection::None
    }

    /// None-selection simple projection alias.
    pub fn none_project_simple() -> Selection {
        Selection::None
    }

    /// Public none-selection alias.
    pub fn select_none_api() -> Self {
        Self::select_none()
    }

    /// Create an all selection.
    pub fn select_all() -> Self {
        Selection::All
    }

    /// Public all-selection alias.
    pub fn select_all_api() -> Self {
        Self::select_all()
    }

    /// Initialize an all-selection iterator.
    pub fn all_iter_init(ds_shape: &[u64]) -> Result<SelectionPointIter> {
        Selection::All.iter_points(ds_shape)
    }

    /// Return the first coordinate for an all-selection iterator.
    pub fn all_iter_coords(ds_shape: &[u64]) -> Result<Option<Vec<u64>>> {
        Ok(Self::all_iter_init(ds_shape)?.next())
    }

    /// Return the first block for an all-selection iterator.
    pub fn all_iter_block(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        Selection::All.bounds(ds_shape)
    }

    /// Return the all-selection element count.
    pub fn all_iter_nelmts(ds_shape: &[u64]) -> Result<u64> {
        total_elements(ds_shape)
    }

    /// Return whether an all-selection has another block.
    pub fn all_iter_has_next_block(ds_shape: &[u64]) -> bool {
        Selection::All.bounds(ds_shape).is_some()
    }

    /// Return the next all-selection coordinate.
    pub fn all_iter_next(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
        iter.next()
    }

    /// Return the next all-selection block.
    pub fn all_iter_next_block(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        Selection::All.bounds(ds_shape)
    }

    /// Return up to `max_points` all-selection coordinates.
    pub fn all_iter_get_seq_list(ds_shape: &[u64], max_points: usize) -> Result<Vec<Vec<u64>>> {
        Ok(Self::all_iter_init(ds_shape)?.take(max_points).collect())
    }

    /// All-selection iterator release alias.
    pub fn all_iter_release(_iter: SelectionPointIter) {}

    /// All-selection release alias.
    pub fn all_release() {}

    /// All-selection copy alias.
    pub fn all_copy() -> Selection {
        Selection::All
    }

    /// All-selection validity alias.
    pub fn all_is_valid(_ds_shape: &[u64]) -> bool {
        true
    }

    /// Return the encoded size of an all-selection payload.
    pub fn all_serial_size() -> usize {
        0
    }

    /// Serialize an all selection.
    pub fn all_serialize() -> Vec<u8> {
        Vec::new()
    }

    /// Deserialize an all selection.
    pub fn all_deserialize(bytes: &[u8]) -> Result<Selection> {
        if bytes.is_empty() {
            Ok(Selection::All)
        } else {
            Err(Error::InvalidFormat(
                "all selection serialization must be empty".into(),
            ))
        }
    }

    /// All-selection bounds alias.
    pub fn all_bounds(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        Selection::All.bounds(ds_shape)
    }

    /// All-selection offset alias.
    pub fn all_offset(offsets: &[i64]) -> Result<Selection> {
        Selection::All.select_offset(offsets)
    }

    /// All-selection unlimited-dimension alias.
    pub fn all_unlim_dim(max_dims: &[u64]) -> Option<usize> {
        Selection::All.select_unlim_dim(max_dims)
    }

    /// All-selection contiguous alias.
    pub fn all_is_contiguous() -> bool {
        true
    }

    /// All-selection single-element alias.
    pub fn all_is_single(ds_shape: &[u64]) -> bool {
        total_elements(ds_shape).ok() == Some(1)
    }

    /// All-selection regularity alias.
    pub fn all_is_regular() -> bool {
        true
    }

    /// All-selection block-intersection alias.
    pub fn all_intersect_block(ds_shape: &[u64], start: &[u64], end: &[u64]) -> bool {
        block_intersects_shape(ds_shape, start, end)
    }

    /// All-selection unsigned adjust alias.
    pub fn all_adjust_u(offsets: &[u64]) -> Result<Selection> {
        Selection::All.select_adjust_unsigned(offsets)
    }

    /// All-selection signed adjust alias.
    pub fn all_adjust_s(offsets: &[i64]) -> Result<Selection> {
        Selection::All.select_adjust_signed(offsets)
    }

    /// All-selection simple projection alias.
    pub fn all_project_simple(ds_shape: &[u64], kept_dims: &[usize]) -> Result<Selection> {
        Selection::All.project(ds_shape, kept_dims)
    }

    /// Create an explicit element-point selection.
    pub fn select_elements(points: Vec<Vec<u64>>) -> Self {
        Selection::Points(points)
    }

    /// Copy a raw point-selection coordinate list.
    pub fn copy_pnt_list(points: &[Vec<u64>]) -> Vec<Vec<u64>> {
        points.to_vec()
    }

    /// Explicit point-list release alias.
    pub fn free_pnt_list(_points: Vec<Vec<u64>>) {}

    /// Public element-point selection alias.
    pub fn select_elements_api(points: Vec<Vec<u64>>) -> Self {
        Self::select_elements(points)
    }

    /// Create a regular hyperslab selection.
    pub fn select_hyperslab(dims: Vec<HyperslabDim>) -> Self {
        Selection::Hyperslab(dims)
    }

    /// Public hyperslab selection alias.
    pub fn select_hyperslab_api(dims: Vec<HyperslabDim>) -> Self {
        Self::select_hyperslab(dims)
    }

    /// Local classification equivalent of the MPI all-selection branch.
    pub fn mpio_all_type(&self) -> bool {
        matches!(self, Selection::All)
    }

    /// Local classification equivalent of the MPI none-selection branch.
    pub fn mpio_none_type(&self) -> bool {
        matches!(self, Selection::None)
    }

    /// Local classification equivalent of the MPI point-selection branch.
    pub fn mpio_point_type(&self) -> bool {
        matches!(self, Selection::Points(_))
    }

    /// Local classification equivalent of the MPI permutation branch.
    pub fn mpio_permute_type(&self) -> bool {
        false
    }

    /// Local classification equivalent of the MPI regular-hyperslab branch.
    pub fn mpio_reg_hyper_type(&self) -> bool {
        matches!(self, Selection::Hyperslab(_) | Selection::Slice(_)) && self.is_regular()
    }

    /// Local classification equivalent of the MPI span-hyperslab branch.
    pub fn mpio_span_hyper_type(&self) -> bool {
        matches!(self, Selection::Hyperslab(_) | Selection::Slice(_)) && !self.is_regular()
    }

    /// Deserialize a tagged selection payload.
    pub fn select_deserialize(bytes: &[u8]) -> Result<Selection> {
        let Some((&tag, rest)) = bytes.split_first() else {
            return Err(Error::InvalidFormat(
                "selection serialization payload is empty".into(),
            ));
        };
        match tag {
            0 => Selection::none_deserialize(rest),
            1 => Selection::all_deserialize(rest),
            2 => Selection::point_deserialize(rest),
            3 => Selection::hyper_deserialize(rest),
            _ => Err(Error::InvalidFormat(format!(
                "unknown selection serialization tag {tag}"
            ))),
        }
    }

    /// Return true if this selection selects no points.
    pub fn is_none(&self) -> bool {
        matches!(self, Selection::None)
    }

    /// Return true if this selection selects the full dataspace.
    pub fn is_all(&self) -> bool {
        matches!(self, Selection::All)
    }

    /// Return the HDF5-style selection class.
    pub fn selection_type(&self) -> SelectionType {
        match self {
            Selection::None => SelectionType::None,
            Selection::All => SelectionType::All,
            Selection::Points(_) => SelectionType::Points,
            Selection::Hyperslab(_) | Selection::Slice(_) => SelectionType::Hyperslab,
        }
    }

    /// Internal selection-type helper.
    pub fn select_type_internal(&self) -> SelectionType {
        self.selection_type()
    }

    /// Serialize this selection with an explicit class tag.
    pub fn encode1(&self) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        match self {
            Selection::None => out.push(0),
            Selection::All => out.push(1),
            Selection::Points(_) => {
                out.push(2);
                out.extend(self.point_serialize()?);
            }
            Selection::Hyperslab(_) | Selection::Slice(_) => {
                out.push(3);
                out.extend(self.hyper_serialize()?);
            }
        }
        Ok(out)
    }

    /// Explicit selection copy operation.
    pub fn select_copy(&self) -> Self {
        self.clone()
    }

    /// Compute the output shape for this selection given the dataset shape.
    pub fn output_shape(&self, ds_shape: &[u64]) -> Vec<u64> {
        match self {
            Selection::None => vec![0],
            Selection::All => ds_shape.to_vec(),
            Selection::Points(points) => vec![points.len() as u64],
            Selection::Hyperslab(dims) => dims.iter().map(HyperslabDim::output_count).collect(),
            Selection::Slice(slices) => slices.iter().map(|s| s.count()).collect(),
        }
    }

    /// Return the number of selected elements.
    pub fn selected_count(&self, ds_shape: &[u64]) -> Option<u64> {
        match self {
            Selection::None => Some(0),
            Selection::All => total_elements(ds_shape).ok(),
            Selection::Points(points) => u64::try_from(points.len()).ok(),
            Selection::Hyperslab(dims) => {
                if dims.is_empty() {
                    return Some(1);
                }
                dims.iter().try_fold(1u64, |acc, dim| {
                    dim.count
                        .checked_mul(dim.block)
                        .and_then(|dim_count| acc.checked_mul(dim_count))
                })
            }
            Selection::Slice(slices) => {
                if slices.is_empty() {
                    return Some(1);
                }
                slices
                    .iter()
                    .try_fold(1u64, |acc, slice| acc.checked_mul(slice.count()))
            }
        }
    }

    /// Internal selected-point count helper.
    pub fn select_npoints_internal(&self, ds_shape: &[u64]) -> Option<u64> {
        self.selected_count(ds_shape)
    }

    /// Return whether this selection is valid for a dataspace shape.
    pub fn select_valid(&self, ds_shape: &[u64]) -> bool {
        if let Selection::Points(points) = self {
            return points.iter().all(|point| {
                point.len() == ds_shape.len()
                    && point
                        .iter()
                        .zip(ds_shape.iter())
                        .all(|(&coord, &extent)| coord < extent)
            });
        }
        self.materialize_points(ds_shape).is_ok()
    }

    /// Return inclusive selection bounds as `(start, end)` coordinates.
    pub fn bounds(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        match self {
            Selection::None => None,
            Selection::All => {
                if ds_shape.contains(&0) {
                    None
                } else if ds_shape.is_empty() {
                    Some((Vec::new(), Vec::new()))
                } else {
                    Some((
                        vec![0; ds_shape.len()],
                        ds_shape.iter().map(|&dim| dim - 1).collect(),
                    ))
                }
            }
            Selection::Points(points) => point_bounds(points),
            Selection::Hyperslab(dims) => hyperslab_bounds(dims),
            Selection::Slice(slices) => slice_bounds(slices),
        }
    }

    /// Internal selection-bounds helper.
    pub fn select_bounds_internal(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        self.bounds(ds_shape)
    }

    /// Return the number of hyperslab blocks, if this is a hyperslab-like
    /// selection.
    pub fn hyperslab_block_count(&self, ds_shape: &[u64]) -> Option<u64> {
        match self {
            Selection::Points(_) => None,
            Selection::None => Some(0),
            Selection::All => total_elements(ds_shape)
                .ok()
                .map(|count| u64::from(count > 0)),
            Selection::Hyperslab(dims) => {
                if dims
                    .iter()
                    .any(|dim| dim.count == 0 || dim.block == 0 || dim.stride == 0)
                {
                    return Some(0);
                }
                dims.iter()
                    .try_fold(1u64, |acc, dim| acc.checked_mul(dim.count))
            }
            Selection::Slice(slices) => {
                if slices.iter().any(|slice| slice.count() == 0) {
                    return Some(0);
                }
                slices.iter().try_fold(1u64, |acc, slice| {
                    let blocks = if slice.step == 1 { 1 } else { slice.count() };
                    acc.checked_mul(blocks)
                })
            }
        }
    }

    /// Return hyperslab block start/end pairs, if this is a hyperslab-like
    /// selection.
    pub fn hyperslab_blocklist(
        &self,
        ds_shape: &[u64],
    ) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
        match self {
            Selection::Points(_) => Ok(None),
            Selection::None => Ok(Some(Vec::new())),
            Selection::All => Ok(Some(match self.bounds(ds_shape) {
                Some(bounds) => vec![bounds],
                None => Vec::new(),
            })),
            Selection::Hyperslab(dims) => hyperslab_blocklist(dims).map(Some),
            Selection::Slice(slices) => slice_blocklist(slices).map(Some),
        }
    }

    /// Return the number of explicit element-selection points.
    pub fn element_point_count(&self) -> Option<u64> {
        match self {
            Selection::Points(points) => u64::try_from(points.len()).ok(),
            _ => None,
        }
    }

    /// Return explicit element-selection points.
    pub fn element_pointlist(&self) -> Option<&[Vec<u64>]> {
        match self {
            Selection::Points(points) => Some(points),
            _ => None,
        }
    }

    /// Return encoded size/version metadata for a point selection.
    pub fn point_get_version_enc_size(&self) -> Result<(u8, usize)> {
        Ok((1, self.point_serial_size()?))
    }

    /// Return serialized point-selection payload size.
    pub fn point_serial_size(&self) -> Result<usize> {
        match self {
            Selection::Points(points) => {
                let rank = points.first().map_or(0, Vec::len);
                let words = 2usize
                    .checked_add(points.len().checked_mul(rank).ok_or_else(|| {
                        Error::InvalidFormat("point selection size overflow".into())
                    })?)
                    .ok_or_else(|| Error::InvalidFormat("point selection size overflow".into()))?;
                words
                    .checked_mul(8)
                    .ok_or_else(|| Error::InvalidFormat("point selection size overflow".into()))
            }
            _ => Err(Error::InvalidFormat(
                "selection is not a point selection".into(),
            )),
        }
    }

    /// Serialize an explicit point selection.
    pub fn point_serialize(&self) -> Result<Vec<u8>> {
        let Selection::Points(points) = self else {
            return Err(Error::InvalidFormat(
                "selection is not a point selection".into(),
            ));
        };
        let rank = points.first().map_or(0, Vec::len);
        let mut out = Vec::with_capacity(self.point_serial_size()?);
        push_u64(&mut out, rank as u64);
        push_u64(&mut out, points.len() as u64);
        for point in points {
            if point.len() != rank {
                return Err(Error::InvalidFormat(
                    "point selection contains mixed ranks".into(),
                ));
            }
            for &coord in point {
                push_u64(&mut out, coord);
            }
        }
        Ok(out)
    }

    /// Deserialize an explicit point selection.
    pub fn point_deserialize(bytes: &[u8]) -> Result<Selection> {
        let mut offset = 0;
        let rank = read_u64(bytes, &mut offset)? as usize;
        let count = read_u64(bytes, &mut offset)? as usize;
        let mut points = Vec::with_capacity(count);
        for _ in 0..count {
            let mut point = Vec::with_capacity(rank);
            for _ in 0..rank {
                point.push(read_u64(bytes, &mut offset)?);
            }
            points.push(point);
        }
        if offset != bytes.len() {
            return Err(Error::InvalidFormat(
                "point selection serialization has trailing bytes".into(),
            ));
        }
        Ok(Selection::Points(points))
    }

    /// Return true if the selection is representable as regular hyperslabs.
    pub fn is_regular(&self) -> bool {
        matches!(
            self,
            Selection::All | Selection::None | Selection::Slice(_) | Selection::Hyperslab(_)
        )
    }

    /// Return the inclusive row-major linear bounds of this selection.
    ///
    /// Returns `Ok(None)` for empty selections. Non-trivial selections are
    /// bounded by the same materialization cap as set-combine helpers.
    pub fn linear_bounds(&self, ds_shape: &[u64]) -> Result<Option<(u64, u64)>> {
        match self {
            Selection::None => Ok(None),
            Selection::All => {
                let total = total_elements(ds_shape)?;
                if total == 0 {
                    Ok(None)
                } else {
                    Ok(Some((0, total - 1)))
                }
            }
            _ => {
                let points = self.materialize_points(ds_shape)?;
                let mut min = None::<u64>;
                let mut max = None::<u64>;
                for point in &points {
                    let idx = linear_index(point, ds_shape)?;
                    min = Some(min.map_or(idx, |value| value.min(idx)));
                    max = Some(max.map_or(idx, |value| value.max(idx)));
                }
                Ok(min.zip(max))
            }
        }
    }

    /// Return true if selected points form one contiguous row-major span.
    ///
    /// Empty selections are considered contiguous. Non-trivial selections are
    /// bounded by the same materialization cap as set-combine helpers.
    pub fn is_contiguous(&self, ds_shape: &[u64]) -> Result<bool> {
        match self {
            Selection::None => Ok(true),
            Selection::All => Ok(true),
            _ => {
                let mut indexes = Vec::new();
                for point in self.materialize_points(ds_shape)? {
                    indexes.push(linear_index(&point, ds_shape)?);
                }
                if indexes.is_empty() {
                    return Ok(true);
                }
                indexes.sort_unstable();
                if indexes.windows(2).any(|pair| pair[0] == pair[1]) {
                    return Ok(false);
                }
                let first = indexes[0];
                let last = indexes[indexes.len() - 1];
                Ok(last - first + 1 == indexes.len() as u64)
            }
        }
    }

    /// Internal contiguous-selection helper.
    pub fn select_is_contiguous(&self, ds_shape: &[u64]) -> Result<bool> {
        self.is_contiguous(ds_shape)
    }

    /// Return whether this selection contains exactly one element.
    pub fn select_is_single(&self, ds_shape: &[u64]) -> bool {
        self.selected_count(ds_shape) == Some(1)
    }

    /// Return whether two selections produce the same selected shape.
    pub fn select_shape_same(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        self.output_shape(ds_shape) == other.output_shape(ds_shape)
    }

    /// Public selected-shape comparison alias.
    pub fn select_shape_same_api(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        self.select_shape_same(other, ds_shape)
    }

    /// Combine two selections with set union, returning explicit points.
    pub fn combine_or(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        use std::collections::BTreeSet;

        let mut points: BTreeSet<_> = self.materialize_points(ds_shape)?.into_iter().collect();
        points.extend(other.materialize_points(ds_shape)?);
        Ok(points_to_selection(points.into_iter().collect()))
    }

    /// Public hyperslab-combine alias.
    pub fn combine_hyperslab(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        require_hyperslab_like(other)?;
        self.combine_or(other, ds_shape)
    }

    /// Internal hyperslab-combine alias.
    pub fn combine_hyperslab_internal(
        &self,
        other: &Selection,
        ds_shape: &[u64],
    ) -> Result<Selection> {
        self.combine_hyperslab(other, ds_shape)
    }

    /// Combine two selections with set intersection, returning explicit points.
    pub fn combine_and(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        use std::collections::BTreeSet;

        let lhs: BTreeSet<_> = self.materialize_points(ds_shape)?.into_iter().collect();
        let rhs: BTreeSet<_> = other.materialize_points(ds_shape)?.into_iter().collect();
        Ok(points_to_selection(
            lhs.intersection(&rhs).cloned().collect(),
        ))
    }

    /// Public modify-selection alias. This applies the same union operation
    /// used by the default HDF5 hyperslab OR combine path.
    pub fn modify_select(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        self.combine_or(other, ds_shape)
    }

    /// Internal modify-selection alias.
    pub fn modify_select_internal(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        self.modify_select(other, ds_shape)
    }

    /// Combine two selections with symmetric difference, returning explicit points.
    pub fn combine_xor(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        let lhs: std::collections::BTreeSet<_> =
            self.materialize_points(ds_shape)?.into_iter().collect();
        let rhs: std::collections::BTreeSet<_> =
            other.materialize_points(ds_shape)?.into_iter().collect();
        Ok(points_to_selection(
            lhs.symmetric_difference(&rhs).cloned().collect(),
        ))
    }

    /// Subtract `other` from this selection, returning explicit points.
    pub fn combine_and_not(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        use std::collections::BTreeSet;

        let lhs: BTreeSet<_> = self.materialize_points(ds_shape)?.into_iter().collect();
        let rhs: BTreeSet<_> = other.materialize_points(ds_shape)?.into_iter().collect();
        Ok(points_to_selection(lhs.difference(&rhs).cloned().collect()))
    }

    /// Materialize selected coordinates in row-major order.
    pub fn materialize_points(&self, ds_shape: &[u64]) -> Result<Vec<Vec<u64>>> {
        let count = self
            .selected_count(ds_shape)
            .ok_or_else(|| Error::InvalidFormat("selection point count overflow".into()))?;
        let count = usize::try_from(count)
            .map_err(|_| Error::InvalidFormat("selection point count does not fit usize".into()))?;
        if count > MAX_MATERIALIZED_SELECTION_POINTS {
            return Err(Error::Unsupported(format!(
                "selection materialization exceeds {MAX_MATERIALIZED_SELECTION_POINTS} points"
            )));
        }

        match self {
            Selection::None => Ok(Vec::new()),
            Selection::All => materialize_all_points(ds_shape),
            Selection::Points(points) => Ok(points.clone()),
            Selection::Slice(slices) => materialize_slice_points(slices),
            Selection::Hyperslab(dims) => materialize_hyperslab_points(dims),
        }
    }

    /// Return a bounded iterator over selected coordinates in row-major order.
    pub fn iter_points(&self, ds_shape: &[u64]) -> Result<SelectionPointIter> {
        Ok(SelectionPointIter {
            points: self.materialize_points(ds_shape)?,
            index: 0,
        })
    }

    /// Initialize a bounded HDF5-style selection iterator.
    pub fn select_iter_init(&self, ds_shape: &[u64]) -> Result<SelectionPointIter> {
        self.iter_points(ds_shape)
    }

    /// Initialize a hyperslab-specific iterator.
    pub fn hyper_iter_init(&self, ds_shape: &[u64]) -> Result<SelectionPointIter> {
        require_hyperslab_like(self)?;
        self.iter_points(ds_shape)
    }

    /// Return the first point of a hyperslab iterator block.
    pub fn hyper_iter_block(&self, ds_shape: &[u64]) -> Result<Option<Vec<u64>>> {
        require_hyperslab_like(self)?;
        Ok(self.materialize_points(ds_shape)?.into_iter().next())
    }

    /// Return whether a hyperslab iterator has another block.
    pub fn hyper_iter_has_next_block(&self, ds_shape: &[u64]) -> Result<bool> {
        require_hyperslab_like(self)?;
        Ok(!self.materialize_points(ds_shape)?.is_empty())
    }

    /// Initialize a point-specific iterator.
    pub fn point_iter_init(&self, ds_shape: &[u64]) -> Result<SelectionPointIter> {
        require_point_selection(self)?;
        self.iter_points(ds_shape)
    }

    /// Visit each selected coordinate in row-major order.
    pub fn select_iterate<F>(&self, ds_shape: &[u64], mut callback: F) -> Result<()>
    where
        F: FnMut(&[u64]) -> Result<()>,
    {
        for point in self.materialize_points(ds_shape)? {
            callback(&point)?;
        }
        Ok(())
    }

    /// Project this selection onto a subset of dimensions.
    ///
    /// `kept_dims` contains dimension indexes from the original dataspace.
    /// Duplicate projected points are collapsed, matching set-style
    /// dataspace projection semantics.
    pub fn project(&self, ds_shape: &[u64], kept_dims: &[usize]) -> Result<Selection> {
        use std::collections::BTreeSet;

        for &dim in kept_dims {
            if dim >= ds_shape.len() {
                return Err(Error::InvalidFormat(format!(
                    "projected dimension {dim} is out of bounds for rank {}",
                    ds_shape.len()
                )));
            }
        }

        let points = self.materialize_points(ds_shape)?;
        let projected: BTreeSet<Vec<u64>> = points
            .into_iter()
            .map(|point| kept_dims.iter().map(|&dim| point[dim]).collect())
            .collect();
        Ok(points_to_selection(projected.into_iter().collect()))
    }

    /// Construct a projected selection on a subset of dimensions.
    pub fn select_construct_projection(
        &self,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.project(ds_shape, kept_dims)
    }

    /// Intersect two selections and project the intersection.
    pub fn select_project_intersection(
        &self,
        other: &Selection,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.combine_and(other, ds_shape)?
            .project(ds_shape, kept_dims)
    }

    /// Public intersection-projection alias.
    pub fn select_project_intersection_api(
        &self,
        other: &Selection,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.select_project_intersection(other, ds_shape, kept_dims)
    }

    /// Hyperslab-specific selection copy alias.
    pub fn hyper_copy(&self) -> Result<Selection> {
        require_hyperslab_like(self)?;
        Ok(self.clone())
    }

    /// Point-specific selection copy alias.
    pub fn point_copy(&self) -> Result<Selection> {
        require_point_selection(self)?;
        Ok(self.clone())
    }

    /// Add one coordinate to an explicit point selection.
    pub fn point_add(&mut self, point: Vec<u64>) -> Result<()> {
        match self {
            Selection::Points(points) => {
                if points
                    .first()
                    .is_some_and(|first| first.len() != point.len())
                {
                    return Err(Error::InvalidFormat(format!(
                        "point rank {} does not match existing point rank {}",
                        point.len(),
                        points[0].len()
                    )));
                }
                points.push(point);
                Ok(())
            }
            _ => Err(Error::InvalidFormat(
                "selection is not a point selection".into(),
            )),
        }
    }

    /// Hyperslab-specific validity alias.
    pub fn hyper_is_valid(&self, ds_shape: &[u64]) -> bool {
        is_hyperslab_like(self) && self.select_valid(ds_shape)
    }

    /// Create one hyperslab span from start/stride/count/block.
    pub fn hyper_new_span(start: u64, stride: u64, count: u64, block: u64) -> HyperslabDim {
        HyperslabDim::new(start, stride, count, block)
    }

    /// Create one hyperslab span-info value.
    pub fn hyper_new_span_info(dims: Vec<HyperslabDim>) -> Selection {
        Selection::Hyperslab(dims)
    }

    /// Copy hyperslab span dimensions.
    pub fn hyper_copy_span_helper(&self) -> Result<Vec<HyperslabDim>> {
        match self {
            Selection::Hyperslab(dims) => Ok(dims.clone()),
            Selection::Slice(slices) => Ok(slices
                .iter()
                .map(|slice| HyperslabDim::new(slice.start, slice.step, slice.count(), 1))
                .collect()),
            _ => Err(Error::InvalidFormat(
                "selection is not hyperslab-like".into(),
            )),
        }
    }

    /// Copy hyperslab span dimensions.
    pub fn hyper_copy_span(&self) -> Result<Vec<HyperslabDim>> {
        self.hyper_copy_span_helper()
    }

    /// Compare hyperslab span dimensions for equality.
    pub fn hyper_cmp_spans(&self, other: &Selection) -> bool {
        self.hyper_copy_span_helper().ok() == other.hyper_copy_span_helper().ok()
    }

    /// Render hyperslab span dimensions for diagnostics.
    pub fn hyper_print_spans_helper(&self) -> Result<String> {
        Ok(format!("{:?}", self.hyper_copy_span_helper()?))
    }

    /// Render hyperslab spans for diagnostics.
    pub fn hyper_print_spans(&self) -> Result<String> {
        self.hyper_print_spans_helper()
    }

    /// Render selection spans for diagnostics.
    pub fn space_print_spans(&self) -> Result<String> {
        match self {
            Selection::Hyperslab(_) | Selection::Slice(_) => self.hyper_print_spans(),
            _ => Ok(format!("{:?}", self.selection_type())),
        }
    }

    /// Render hyperslab dimension info for diagnostics.
    pub fn hyper_print_diminfo_helper(&self) -> Result<String> {
        let dims = self.hyper_copy_span_helper()?;
        Ok(dims
            .iter()
            .enumerate()
            .map(|(idx, dim)| {
                format!(
                    "{idx}:start={},stride={},count={},block={}",
                    dim.start, dim.stride, dim.count, dim.block
                )
            })
            .collect::<Vec<_>>()
            .join(";"))
    }

    /// Render hyperslab dimension info for diagnostics.
    pub fn hyper_print_diminfo(&self) -> Result<String> {
        self.hyper_print_diminfo_helper()
    }

    /// Depth-first span diagnostic alias.
    pub fn hyper_print_spans_dfs(&self) -> Result<String> {
        self.hyper_print_spans()
    }

    /// Depth-first space diagnostic alias.
    pub fn hyper_print_space_dfs(&self) -> Result<String> {
        self.space_print_spans()
    }

    /// Release hyperslab span state. The pure Rust selection is consumed.
    pub fn hyper_free_span(self) {}

    /// Release hyperslab selection state. The pure Rust selection is consumed.
    pub fn hyper_release(self) {}

    /// Point-specific validity alias.
    pub fn point_is_valid(&self, ds_shape: &[u64]) -> bool {
        matches!(self, Selection::Points(_)) && self.select_valid(ds_shape)
    }

    /// Hyperslab-specific selected-block count alias.
    pub fn hyper_span_nblocks(&self, ds_shape: &[u64]) -> Option<u64> {
        if is_hyperslab_like(self) {
            self.hyperslab_block_count(ds_shape)
        } else {
            None
        }
    }

    /// Internal selected-hyperslab block-count alias.
    pub fn get_select_hyper_nblocks_internal(&self, ds_shape: &[u64]) -> Option<u64> {
        self.hyper_span_nblocks(ds_shape)
    }

    /// Hyperslab-specific blocklist alias.
    pub fn hyper_span_blocklist(
        &self,
        ds_shape: &[u64],
    ) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
        require_hyperslab_like(self)?;
        self.hyperslab_blocklist(ds_shape)
    }

    /// Hyperslab block-intersection helper.
    pub fn hyper_intersect_block_helper(
        &self,
        ds_shape: &[u64],
        start: &[u64],
        end: &[u64],
    ) -> bool {
        is_hyperslab_like(self)
            && self
                .materialize_points(ds_shape)
                .map(|points| {
                    points
                        .iter()
                        .any(|point| point_is_inside_block(point, start, end))
                })
                .unwrap_or(false)
    }

    /// Internal selected-hyperslab blocklist alias.
    pub fn get_select_hyper_blocklist_internal(
        &self,
        ds_shape: &[u64],
    ) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
        self.hyper_span_blocklist(ds_shape)
    }

    /// Internal selected-element pointlist alias.
    pub fn get_select_elem_pointlist_internal(&self) -> Option<&[Vec<u64>]> {
        self.element_pointlist()
    }

    /// Hyperslab-specific bounds alias.
    pub fn hyper_bounds(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        if is_hyperslab_like(self) {
            self.bounds(ds_shape)
        } else {
            None
        }
    }

    /// Hyperslab-specific offset alias.
    pub fn hyper_offset(&self, offsets: &[i64]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        self.select_offset(offsets)
    }

    /// Point-specific offset alias.
    pub fn point_offset(&self, offsets: &[i64]) -> Result<Selection> {
        require_point_selection(self)?;
        self.select_offset(offsets)
    }

    /// Hyperslab-specific unlimited-dimension alias.
    pub fn hyper_unlim_dim(&self, max_dims: &[u64]) -> Option<usize> {
        if is_hyperslab_like(self) {
            self.select_unlim_dim(max_dims)
        } else {
            None
        }
    }

    /// Point-specific unlimited-dimension alias.
    pub fn point_unlim_dim(&self, max_dims: &[u64]) -> Option<usize> {
        if matches!(self, Selection::Points(_)) {
            self.select_unlim_dim(max_dims)
        } else {
            None
        }
    }

    /// Hyperslab-specific non-unlimited element-count alias.
    pub fn hyper_num_elem_non_unlim(&self, ds_shape: &[u64], max_dims: &[u64]) -> Result<u64> {
        require_hyperslab_like(self)?;
        self.select_num_elem_non_unlim(ds_shape, max_dims)
    }

    /// Hyperslab-specific contiguous-selection alias.
    pub fn hyper_is_contiguous(&self, ds_shape: &[u64]) -> Result<bool> {
        require_hyperslab_like(self)?;
        self.is_contiguous(ds_shape)
    }

    /// Point-specific contiguous-selection alias.
    pub fn point_is_contiguous(&self, ds_shape: &[u64]) -> Result<bool> {
        require_point_selection(self)?;
        self.is_contiguous(ds_shape)
    }

    /// Hyperslab-specific single-element alias.
    pub fn hyper_is_single(&self, ds_shape: &[u64]) -> bool {
        is_hyperslab_like(self) && self.select_is_single(ds_shape)
    }

    /// Point-specific single-element alias.
    pub fn point_is_single(&self, ds_shape: &[u64]) -> bool {
        matches!(self, Selection::Points(_)) && self.select_is_single(ds_shape)
    }

    /// Hyperslab-specific regularity alias.
    pub fn hyper_is_regular(&self) -> bool {
        is_hyperslab_like(self) && self.is_regular()
    }

    /// Point-specific regularity alias.
    pub fn point_is_regular(&self) -> bool {
        false
    }

    /// Hyperslab-specific shape comparison alias.
    pub fn hyper_shape_same(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        is_hyperslab_like(self)
            && is_hyperslab_like(other)
            && self.select_shape_same(other, ds_shape)
    }

    /// Internal hyperslab-shape comparison helper.
    pub fn hyper_spans_shape_same_helper(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        self.hyper_shape_same(other, ds_shape)
    }

    /// Hyperslab-shape comparison helper.
    pub fn hyper_spans_shape_same(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        self.hyper_shape_same(other, ds_shape)
    }

    /// Point-specific shape comparison alias.
    pub fn point_shape_same(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        matches!(self, Selection::Points(_))
            && matches!(other, Selection::Points(_))
            && self.select_shape_same(other, ds_shape)
    }

    /// Point-specific block-intersection alias.
    pub fn point_intersect_block(&self, start: &[u64], end: &[u64]) -> bool {
        match self {
            Selection::Points(points) => points
                .iter()
                .any(|point| point_is_inside_block(point, start, end)),
            _ => false,
        }
    }

    /// Hyperslab-specific unsigned adjust alias.
    pub fn hyper_adjust_u(&self, offsets: &[u64]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        self.select_adjust_unsigned(offsets)
    }

    /// Hyperslab coordinate-to-span alias.
    pub fn hyper_coord_to_span(&self, coord: &[u64], ds_shape: &[u64]) -> bool {
        is_hyperslab_like(self)
            && self
                .materialize_points(ds_shape)
                .map(|points| points.iter().any(|point| point == coord))
                .unwrap_or(false)
    }

    /// Hyperslab add-span-element alias.
    pub fn hyper_add_span_element(&mut self, dim: HyperslabDim) -> Result<()> {
        match self {
            Selection::Hyperslab(dims) => {
                dims.push(dim);
                Ok(())
            }
            _ => Err(Error::InvalidFormat(
                "selection is not a hyperslab selection".into(),
            )),
        }
    }

    /// Append a hyperslab span element.
    pub fn hyper_append_span(&mut self, dim: HyperslabDim) -> Result<()> {
        self.hyper_add_span_element(dim)
    }

    /// Clip this hyperslab selection to an inclusive block.
    pub fn hyper_clip_spans(
        &self,
        ds_shape: &[u64],
        start: &[u64],
        end: &[u64],
    ) -> Result<Selection> {
        require_hyperslab_like(self)?;
        let points = self
            .materialize_points(ds_shape)?
            .into_iter()
            .filter(|point| point_is_inside_block(point, start, end))
            .collect();
        Ok(points_to_selection(points))
    }

    /// Merge two hyperslab selections.
    pub fn hyper_merge_spans_helper(
        &self,
        other: &Selection,
        ds_shape: &[u64],
    ) -> Result<Selection> {
        self.combine_hyperslab(other, ds_shape)
    }

    /// Merge two hyperslab selections.
    pub fn hyper_merge_spans(&self, other: &Selection, ds_shape: &[u64]) -> Result<Selection> {
        self.hyper_merge_spans_helper(other, ds_shape)
    }

    /// Add disjoint hyperslab spans.
    pub fn hyper_add_disjoint_spans(
        &self,
        other: &Selection,
        ds_shape: &[u64],
    ) -> Result<Selection> {
        if self.combine_and(other, ds_shape)?.selected_count(ds_shape) != Some(0) {
            return Err(Error::InvalidFormat(
                "hyperslab selections are not disjoint".into(),
            ));
        }
        self.combine_hyperslab(other, ds_shape)
    }

    /// Build a hyperslab selection from span dimensions.
    pub fn hyper_make_spans(dims: Vec<HyperslabDim>) -> Selection {
        Selection::Hyperslab(dims)
    }

    /// Update derived hyperslab dimension info.
    pub fn hyper_update_diminfo(&self) -> Result<Vec<HyperslabDim>> {
        self.hyper_copy_span_helper()
    }

    /// Rebuild hyperslab spans.
    pub fn hyper_rebuild_helper(&self) -> Result<Selection> {
        require_hyperslab_like(self)?;
        Ok(self.clone())
    }

    /// Rebuild hyperslab spans.
    pub fn hyper_rebuild(&self) -> Result<Selection> {
        self.hyper_rebuild_helper()
    }

    /// Generate hyperslab spans.
    pub fn hyper_generate_spans(&self) -> Result<Selection> {
        self.hyper_rebuild_helper()
    }

    /// Return whether two selections overlap.
    pub fn check_spans_overlap(&self, other: &Selection, ds_shape: &[u64]) -> Result<bool> {
        Ok(self.combine_and(other, ds_shape)?.selected_count(ds_shape) != Some(0))
    }

    /// Fill new-space selection metadata.
    pub fn fill_in_new_space(&self, ds_shape: &[u64]) -> Result<Selection> {
        if self.select_valid(ds_shape) {
            Ok(self.clone())
        } else {
            Err(Error::InvalidFormat(
                "selection is invalid for dataspace".into(),
            ))
        }
    }

    /// Set a regular hyperslab selection.
    pub fn set_regular_hyperslab(dims: Vec<HyperslabDim>) -> Selection {
        Selection::Hyperslab(dims)
    }

    /// Fill selection metadata.
    pub fn fill_in_select(&self) -> Selection {
        self.clone()
    }

    /// Hyperslab unsigned-adjust helper alias.
    pub fn hyper_adjust_u_helper(&self, offsets: &[u64]) -> Result<Selection> {
        self.hyper_adjust_u(offsets)
    }

    /// Point-specific unsigned adjust alias.
    pub fn point_adjust_u(&self, offsets: &[u64]) -> Result<Selection> {
        require_point_selection(self)?;
        self.select_adjust_unsigned(offsets)
    }

    /// Hyperslab-specific signed adjust alias.
    pub fn hyper_adjust_s(&self, offsets: &[i64]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        self.select_adjust_signed(offsets)
    }

    /// Hyperslab signed-adjust helper alias.
    pub fn hyper_adjust_s_helper(&self, offsets: &[i64]) -> Result<Selection> {
        self.hyper_adjust_s(offsets)
    }

    /// Normalize a hyperslab offset into a shifted selection.
    pub fn hyper_normalize_offset(&self, offsets: &[i64]) -> Result<Selection> {
        self.hyper_offset(offsets)
    }

    /// Denormalize a hyperslab offset into a shifted selection.
    pub fn hyper_denormalize_offset(&self, offsets: &[i64]) -> Result<Selection> {
        self.hyper_offset(offsets)
    }

    /// Point-specific signed adjust alias.
    pub fn point_adjust_s(&self, offsets: &[i64]) -> Result<Selection> {
        require_point_selection(self)?;
        self.select_adjust_signed(offsets)
    }

    /// Hyperslab-specific scalar projection alias.
    pub fn hyper_project_scalar(&self, ds_shape: &[u64]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        self.project(ds_shape, &[])
    }

    /// Point-specific scalar projection alias.
    pub fn point_project_scalar(&self, ds_shape: &[u64]) -> Result<Selection> {
        require_point_selection(self)?;
        self.project(ds_shape, &[])
    }

    /// Hyperslab-specific simple projection alias.
    pub fn hyper_project_simple(&self, ds_shape: &[u64], kept_dims: &[usize]) -> Result<Selection> {
        require_hyperslab_like(self)?;
        self.project(ds_shape, kept_dims)
    }

    /// Lower-dimensional hyperslab projection alias.
    pub fn hyper_project_simple_lower(
        &self,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.hyper_project_simple(ds_shape, kept_dims)
    }

    /// Higher-dimensional hyperslab projection alias.
    pub fn hyper_project_simple_higher(
        &self,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.hyper_project_simple(ds_shape, kept_dims)
    }

    /// Build a projected intersection.
    pub fn hyper_proj_int_build_proj(
        &self,
        other: &Selection,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.select_project_intersection(other, ds_shape, kept_dims)
    }

    /// Iterate a projected intersection into explicit points.
    pub fn hyper_proj_int_iterate(
        &self,
        other: &Selection,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Vec<Vec<u64>>> {
        self.hyper_proj_int_build_proj(other, ds_shape, kept_dims)?
            .materialize_points(&projected_shape(ds_shape, kept_dims))
    }

    /// Hyperslab-specific projected intersection alias.
    pub fn hyper_project_intersection(
        &self,
        other: &Selection,
        ds_shape: &[u64],
        kept_dims: &[usize],
    ) -> Result<Selection> {
        self.select_project_intersection(other, ds_shape, kept_dims)
    }

    /// Return clip dimension bounds.
    pub fn hyper_get_clip_diminfo(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        self.hyper_bounds(ds_shape)
    }

    /// Clip unlimited dimensions to finite extents.
    pub fn hyper_clip_unlim(&self, ds_shape: &[u64]) -> Result<Selection> {
        self.fill_in_new_space(ds_shape)
    }

    /// Return real clip extent.
    pub fn hyper_get_clip_extent_real(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        self.hyper_bounds(ds_shape)
    }

    /// Return clip extent.
    pub fn hyper_get_clip_extent(&self, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
        self.hyper_get_clip_extent_real(ds_shape)
    }

    /// Return whether the clip extent matches another selection.
    pub fn hyper_get_clip_extent_match(&self, other: &Selection, ds_shape: &[u64]) -> bool {
        self.hyper_get_clip_extent(ds_shape) == other.hyper_get_clip_extent(ds_shape)
    }

    /// Return the selected block that touches an unlimited dimension.
    pub fn hyper_get_unlim_block(&self, max_dims: &[u64]) -> Option<usize> {
        self.hyper_unlim_dim(max_dims)
    }

    /// Test hook for rebuild status.
    pub fn get_rebuild_status_test(&self) -> bool {
        is_hyperslab_like(self)
    }

    /// Test hook for dimension-info status.
    pub fn get_diminfo_status_test(&self) -> bool {
        self.hyper_copy_span_helper().is_ok()
    }

    /// Check internal span-tail consistency.
    pub fn check_spans_tail_ptr(&self) -> bool {
        true
    }

    /// Check internal hyperslab consistency.
    pub fn check_internal_consistency(&self, ds_shape: &[u64]) -> bool {
        self.select_valid(ds_shape)
    }

    /// Internal consistency test alias.
    pub fn internal_consistency_test(&self, ds_shape: &[u64]) -> bool {
        self.check_internal_consistency(ds_shape)
    }

    /// Verify an offset vector against this selection's rank.
    pub fn verify_offsets(&self, offsets: &[i64]) -> bool {
        self.shift(offsets).is_ok()
    }

    /// Return encoded size/version metadata for a hyperslab selection.
    pub fn hyper_get_version_enc_size(&self) -> Result<(u8, usize)> {
        Ok((1, self.hyper_get_enc_size_real()?))
    }

    /// Return serialized hyperslab payload size.
    pub fn hyper_get_enc_size_real(&self) -> Result<usize> {
        let dims = self.hyper_copy_span_helper()?;
        let words = 1usize
            .checked_add(dims.len().checked_mul(4).ok_or_else(|| {
                Error::InvalidFormat("hyperslab serialization size overflow".into())
            })?)
            .ok_or_else(|| Error::InvalidFormat("hyperslab serialization size overflow".into()))?;
        words
            .checked_mul(8)
            .ok_or_else(|| Error::InvalidFormat("hyperslab serialization size overflow".into()))
    }

    /// Serialize hyperslab span dimensions.
    pub fn hyper_serialize_helper(&self) -> Result<Vec<u8>> {
        self.hyper_serialize()
    }

    /// Serialize hyperslab span dimensions.
    pub fn hyper_serialize(&self) -> Result<Vec<u8>> {
        let dims = self.hyper_copy_span_helper()?;
        let mut out = Vec::with_capacity(self.hyper_get_enc_size_real()?);
        push_u64(&mut out, dims.len() as u64);
        for dim in dims {
            push_u64(&mut out, dim.start);
            push_u64(&mut out, dim.stride);
            push_u64(&mut out, dim.count);
            push_u64(&mut out, dim.block);
        }
        Ok(out)
    }

    /// Deserialize hyperslab span dimensions.
    pub fn hyper_deserialize(bytes: &[u8]) -> Result<Selection> {
        let mut offset = 0;
        let rank = read_u64(bytes, &mut offset)? as usize;
        let mut dims = Vec::with_capacity(rank);
        for _ in 0..rank {
            dims.push(HyperslabDim::new(
                read_u64(bytes, &mut offset)?,
                read_u64(bytes, &mut offset)?,
                read_u64(bytes, &mut offset)?,
                read_u64(bytes, &mut offset)?,
            ));
        }
        if offset != bytes.len() {
            return Err(Error::InvalidFormat(
                "hyperslab serialization has trailing bytes".into(),
            ));
        }
        Ok(Selection::Hyperslab(dims))
    }

    /// Return the number of points represented by hyperslab spans.
    pub fn hyper_spans_nelem(&self, ds_shape: &[u64]) -> Option<u64> {
        self.hyper_span_nblocks(ds_shape)
            .and_then(|_| self.selected_count(ds_shape))
    }

    /// Internal point-count helper for hyperslab spans.
    pub fn hyper_spans_nelem_helper(&self, ds_shape: &[u64]) -> Option<u64> {
        self.hyper_spans_nelem(ds_shape)
    }

    /// Return true for a regular hyperslab with a single selected block.
    pub fn hyper_regular_and_single_block(&self, ds_shape: &[u64]) -> bool {
        self.hyper_is_regular() && self.hyper_span_nblocks(ds_shape) == Some(1)
    }

    /// Point-specific simple projection alias.
    pub fn point_project_simple(&self, ds_shape: &[u64], kept_dims: &[usize]) -> Result<Selection> {
        require_point_selection(self)?;
        self.project(ds_shape, kept_dims)
    }

    /// Return the first unlimited dimension touched by this selection.
    pub fn select_unlim_dim(&self, max_dims: &[u64]) -> Option<usize> {
        let touched = self.touched_dims(max_dims.len());
        touched
            .into_iter()
            .find(|&dim| max_dims.get(dim).copied() == Some(u64::MAX))
    }

    /// Count selected elements after dropping unlimited dimensions.
    pub fn select_num_elem_non_unlim(&self, ds_shape: &[u64], max_dims: &[u64]) -> Result<u64> {
        use std::collections::BTreeSet;

        if ds_shape.len() != max_dims.len() {
            return Err(Error::InvalidFormat(format!(
                "dataspace rank {} does not match max-dims rank {}",
                ds_shape.len(),
                max_dims.len()
            )));
        }

        let kept_dims: Vec<_> = max_dims
            .iter()
            .enumerate()
            .filter_map(|(idx, &max_dim)| (max_dim != u64::MAX).then_some(idx))
            .collect();
        let points = self.materialize_points(ds_shape)?;
        let projected: BTreeSet<Vec<u64>> = points
            .into_iter()
            .map(|point| kept_dims.iter().map(|&dim| point[dim]).collect())
            .collect();
        u64::try_from(projected.len())
            .map_err(|_| Error::InvalidFormat("non-unlimited element count overflow".into()))
    }

    /// Apply signed per-dimension offsets to this finite selection.
    pub fn select_offset(&self, offsets: &[i64]) -> Result<Selection> {
        self.shift(offsets)
    }

    /// Apply unsigned per-dimension offsets to this finite selection.
    pub fn select_adjust_unsigned(&self, offsets: &[u64]) -> Result<Selection> {
        let offsets: Result<Vec<_>> = offsets
            .iter()
            .map(|&offset| {
                i64::try_from(offset)
                    .map_err(|_| Error::InvalidFormat("selection offset exceeds i64".into()))
            })
            .collect();
        self.shift(&offsets?)
    }

    /// Apply signed per-dimension offsets to this finite selection.
    pub fn select_adjust_signed(&self, offsets: &[i64]) -> Result<Selection> {
        self.shift(offsets)
    }

    /// Public selection-adjust alias.
    pub fn select_adjust_api(&self, offsets: &[i64]) -> Result<Selection> {
        self.select_adjust_signed(offsets)
    }

    /// Fill selected elements in a row-major buffer.
    pub fn select_fill<T: Clone>(
        &self,
        ds_shape: &[u64],
        buffer: &mut [T],
        value: T,
    ) -> Result<()> {
        let total = usize::try_from(total_elements(ds_shape)?)
            .map_err(|_| Error::InvalidFormat("dataspace element count exceeds usize".into()))?;
        if buffer.len() < total {
            return Err(Error::InvalidFormat(format!(
                "selection fill buffer has {} elements, expected at least {total}",
                buffer.len()
            )));
        }
        for point in self.materialize_points(ds_shape)? {
            let idx = usize::try_from(linear_index(&point, ds_shape)?)
                .map_err(|_| Error::InvalidFormat("selection linear index exceeds usize".into()))?;
            buffer[idx] = value.clone();
        }
        Ok(())
    }

    /// Normalize into concrete SliceInfo per dimension.
    pub fn to_slices(&self, ds_shape: &[u64]) -> Vec<SliceInfo> {
        match self {
            Selection::None => Vec::new(),
            Selection::All => ds_shape.iter().map(|&d| SliceInfo::new(0, d)).collect(),
            Selection::Points(_) => Vec::new(),
            Selection::Hyperslab(_) => Vec::new(),
            Selection::Slice(slices) => slices.clone(),
        }
    }

    fn touched_dims(&self, rank: usize) -> Vec<usize> {
        match self {
            Selection::None => Vec::new(),
            Selection::All => (0..rank).collect(),
            Selection::Points(points) => points
                .first()
                .map(|point| (0..point.len()).collect())
                .unwrap_or_default(),
            Selection::Hyperslab(dims) => (0..dims.len()).collect(),
            Selection::Slice(slices) => (0..slices.len()).collect(),
        }
    }

    fn shift(&self, offsets: &[i64]) -> Result<Selection> {
        match self {
            Selection::None => Ok(Selection::None),
            Selection::All => {
                if offsets.iter().all(|&offset| offset == 0) {
                    Ok(Selection::All)
                } else {
                    Err(Error::Unsupported(
                        "nonzero offset for an all-selection requires persistent offset state"
                            .into(),
                    ))
                }
            }
            Selection::Points(points) => {
                let shifted = points
                    .iter()
                    .map(|point| shift_coords(point, offsets))
                    .collect::<Result<Vec<_>>>()?;
                Ok(Selection::Points(shifted))
            }
            Selection::Hyperslab(dims) => {
                check_rank("hyperslab selection", dims.len(), offsets.len())?;
                let shifted = dims
                    .iter()
                    .zip(offsets)
                    .map(|(dim, &offset)| {
                        Ok(HyperslabDim {
                            start: shift_coord(dim.start, offset)?,
                            stride: dim.stride,
                            count: dim.count,
                            block: dim.block,
                        })
                    })
                    .collect::<Result<Vec<_>>>()?;
                Ok(Selection::Hyperslab(shifted))
            }
            Selection::Slice(slices) => {
                check_rank("slice selection", slices.len(), offsets.len())?;
                let shifted = slices
                    .iter()
                    .zip(offsets)
                    .map(|(slice, &offset)| {
                        Ok(SliceInfo {
                            start: shift_coord(slice.start, offset)?,
                            end: shift_coord(slice.end, offset)?,
                            step: slice.step,
                        })
                    })
                    .collect::<Result<Vec<_>>>()?;
                Ok(Selection::Slice(shifted))
            }
        }
    }
}

fn is_hyperslab_like(selection: &Selection) -> bool {
    matches!(
        selection,
        Selection::All | Selection::None | Selection::Hyperslab(_) | Selection::Slice(_)
    )
}

fn require_hyperslab_like(selection: &Selection) -> Result<()> {
    if is_hyperslab_like(selection) {
        Ok(())
    } else {
        Err(Error::InvalidFormat(
            "selection is not hyperslab-like".into(),
        ))
    }
}

fn require_point_selection(selection: &Selection) -> Result<()> {
    if matches!(selection, Selection::Points(_)) {
        Ok(())
    } else {
        Err(Error::InvalidFormat(
            "selection is not a point selection".into(),
        ))
    }
}

fn check_rank(kind: &str, rank: usize, offset_rank: usize) -> Result<()> {
    if rank != offset_rank {
        return Err(Error::InvalidFormat(format!(
            "{kind} rank {rank} does not match offset rank {offset_rank}"
        )));
    }
    Ok(())
}

fn shift_coords(point: &[u64], offsets: &[i64]) -> Result<Vec<u64>> {
    check_rank("point selection", point.len(), offsets.len())?;
    point
        .iter()
        .zip(offsets)
        .map(|(&coord, &offset)| shift_coord(coord, offset))
        .collect()
}

fn shift_coord(coord: u64, offset: i64) -> Result<u64> {
    if offset >= 0 {
        coord
            .checked_add(offset as u64)
            .ok_or_else(|| Error::InvalidFormat("selection coordinate overflow".into()))
    } else {
        coord
            .checked_sub(offset.unsigned_abs())
            .ok_or_else(|| Error::InvalidFormat("selection coordinate underflow".into()))
    }
}

fn push_u64(out: &mut Vec<u8>, value: u64) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn read_u64(bytes: &[u8], offset: &mut usize) -> Result<u64> {
    let end = offset
        .checked_add(8)
        .ok_or_else(|| Error::InvalidFormat("selection serialization offset overflow".into()))?;
    let word = bytes.get(*offset..end).ok_or_else(|| {
        Error::InvalidFormat("selection serialization ended before u64 field".into())
    })?;
    *offset = end;
    Ok(u64::from_le_bytes(
        word.try_into().expect("slice length checked"),
    ))
}

fn projected_shape(ds_shape: &[u64], kept_dims: &[usize]) -> Vec<u64> {
    kept_dims
        .iter()
        .filter_map(|&dim| ds_shape.get(dim).copied())
        .collect()
}

fn block_intersects_shape(ds_shape: &[u64], start: &[u64], end: &[u64]) -> bool {
    if start.len() != ds_shape.len() || end.len() != ds_shape.len() {
        return false;
    }
    start
        .iter()
        .zip(end)
        .zip(ds_shape)
        .all(|((&lo, &hi), &extent)| lo <= hi && extent > 0 && lo < extent)
}

fn point_is_inside_block(point: &[u64], start: &[u64], end: &[u64]) -> bool {
    point.len() == start.len()
        && point.len() == end.len()
        && point
            .iter()
            .zip(start)
            .zip(end)
            .all(|((&coord, &lo), &hi)| lo <= hi && coord >= lo && coord <= hi)
}

fn points_to_selection(points: Vec<Vec<u64>>) -> Selection {
    if points.is_empty() {
        Selection::None
    } else {
        Selection::Points(points)
    }
}

fn total_elements(ds_shape: &[u64]) -> Result<u64> {
    if ds_shape.is_empty() {
        return Ok(1);
    }
    ds_shape.iter().try_fold(1u64, |acc, &dim| {
        acc.checked_mul(dim)
            .ok_or_else(|| Error::InvalidFormat("dataspace element count overflow".into()))
    })
}

fn linear_index(point: &[u64], ds_shape: &[u64]) -> Result<u64> {
    if point.len() != ds_shape.len() {
        return Err(Error::InvalidFormat(format!(
            "selection point rank {} does not match dataspace rank {}",
            point.len(),
            ds_shape.len()
        )));
    }
    if ds_shape.is_empty() {
        return Ok(0);
    }

    let mut idx = 0u64;
    for (&coord, &extent) in point.iter().zip(ds_shape) {
        if coord >= extent {
            return Err(Error::InvalidFormat(format!(
                "selection coordinate {coord} is out of bounds for extent {extent}"
            )));
        }
        idx = idx
            .checked_mul(extent)
            .and_then(|value| value.checked_add(coord))
            .ok_or_else(|| Error::InvalidFormat("selection linear index overflow".into()))?;
    }
    Ok(idx)
}

fn materialize_all_points(ds_shape: &[u64]) -> Result<Vec<Vec<u64>>> {
    if ds_shape.contains(&0) {
        return Ok(Vec::new());
    }
    if ds_shape.is_empty() {
        return Ok(vec![Vec::new()]);
    }
    let slices: Vec<_> = ds_shape.iter().map(|&dim| SliceInfo::new(0, dim)).collect();
    materialize_slice_points(&slices)
}

fn materialize_slice_points(slices: &[SliceInfo]) -> Result<Vec<Vec<u64>>> {
    if slices.iter().any(|slice| slice.count() == 0) {
        return Ok(Vec::new());
    }
    let mut points = Vec::new();
    let mut current = vec![0u64; slices.len()];
    push_slice_points(slices, 0, &mut current, &mut points)?;
    Ok(points)
}

fn push_slice_points(
    slices: &[SliceInfo],
    dim: usize,
    current: &mut [u64],
    points: &mut Vec<Vec<u64>>,
) -> Result<()> {
    if dim == slices.len() {
        points.push(current.to_vec());
        return Ok(());
    }
    let slice = &slices[dim];
    let mut coord = slice.start;
    while coord < slice.end {
        current[dim] = coord;
        push_slice_points(slices, dim + 1, current, points)?;
        coord = coord
            .checked_add(slice.step)
            .ok_or_else(|| Error::InvalidFormat("selection coordinate overflow".into()))?;
    }
    Ok(())
}

fn materialize_hyperslab_points(dims: &[HyperslabDim]) -> Result<Vec<Vec<u64>>> {
    if dims
        .iter()
        .any(|dim| dim.count == 0 || dim.block == 0 || dim.stride == 0)
    {
        return Ok(Vec::new());
    }
    let mut points = Vec::new();
    let mut current = vec![0u64; dims.len()];
    push_hyperslab_points(dims, 0, &mut current, &mut points)?;
    Ok(points)
}

fn push_hyperslab_points(
    dims: &[HyperslabDim],
    dim: usize,
    current: &mut [u64],
    points: &mut Vec<Vec<u64>>,
) -> Result<()> {
    if dim == dims.len() {
        points.push(current.to_vec());
        return Ok(());
    }
    let selection = &dims[dim];
    for block_idx in 0..selection.count {
        let block_start = selection
            .start
            .checked_add(
                block_idx
                    .checked_mul(selection.stride)
                    .ok_or_else(|| Error::InvalidFormat("hyperslab coordinate overflow".into()))?,
            )
            .ok_or_else(|| Error::InvalidFormat("hyperslab coordinate overflow".into()))?;
        for offset in 0..selection.block {
            current[dim] = block_start
                .checked_add(offset)
                .ok_or_else(|| Error::InvalidFormat("hyperslab coordinate overflow".into()))?;
            push_hyperslab_points(dims, dim + 1, current, points)?;
        }
    }
    Ok(())
}

fn slice_blocklist(slices: &[SliceInfo]) -> Result<Vec<(Vec<u64>, Vec<u64>)>> {
    if slices.iter().any(|slice| slice.count() == 0) {
        return Ok(Vec::new());
    }
    let mut blocks = Vec::new();
    let mut start = vec![0u64; slices.len()];
    let mut end = vec![0u64; slices.len()];
    push_slice_blocks(slices, 0, &mut start, &mut end, &mut blocks)?;
    Ok(blocks)
}

fn push_slice_blocks(
    slices: &[SliceInfo],
    dim: usize,
    start: &mut [u64],
    end: &mut [u64],
    blocks: &mut Vec<(Vec<u64>, Vec<u64>)>,
) -> Result<()> {
    if dim == slices.len() {
        blocks.push((start.to_vec(), end.to_vec()));
        return Ok(());
    }

    let slice = &slices[dim];
    if slice.step == 1 {
        start[dim] = slice.start;
        end[dim] = slice
            .end
            .checked_sub(1)
            .ok_or_else(|| Error::InvalidFormat("slice block end underflow".into()))?;
        push_slice_blocks(slices, dim + 1, start, end, blocks)?;
        return Ok(());
    }

    let mut coord = slice.start;
    while coord < slice.end {
        start[dim] = coord;
        end[dim] = coord;
        push_slice_blocks(slices, dim + 1, start, end, blocks)?;
        coord = coord
            .checked_add(slice.step)
            .ok_or_else(|| Error::InvalidFormat("slice block coordinate overflow".into()))?;
    }
    Ok(())
}

fn hyperslab_blocklist(dims: &[HyperslabDim]) -> Result<Vec<(Vec<u64>, Vec<u64>)>> {
    if dims
        .iter()
        .any(|dim| dim.count == 0 || dim.block == 0 || dim.stride == 0)
    {
        return Ok(Vec::new());
    }
    let mut blocks = Vec::new();
    let mut start = vec![0u64; dims.len()];
    let mut end = vec![0u64; dims.len()];
    push_hyperslab_blocks(dims, 0, &mut start, &mut end, &mut blocks)?;
    Ok(blocks)
}

fn push_hyperslab_blocks(
    dims: &[HyperslabDim],
    dim: usize,
    start: &mut [u64],
    end: &mut [u64],
    blocks: &mut Vec<(Vec<u64>, Vec<u64>)>,
) -> Result<()> {
    if dim == dims.len() {
        blocks.push((start.to_vec(), end.to_vec()));
        return Ok(());
    }

    let selection = &dims[dim];
    for block_idx in 0..selection.count {
        let block_start = selection
            .start
            .checked_add(
                block_idx
                    .checked_mul(selection.stride)
                    .ok_or_else(|| Error::InvalidFormat("hyperslab block overflow".into()))?,
            )
            .ok_or_else(|| Error::InvalidFormat("hyperslab block overflow".into()))?;
        let block_end = block_start
            .checked_add(selection.block)
            .and_then(|value| value.checked_sub(1))
            .ok_or_else(|| Error::InvalidFormat("hyperslab block overflow".into()))?;
        start[dim] = block_start;
        end[dim] = block_end;
        push_hyperslab_blocks(dims, dim + 1, start, end, blocks)?;
    }
    Ok(())
}

fn slice_bounds(slices: &[SliceInfo]) -> Option<(Vec<u64>, Vec<u64>)> {
    if slices.iter().any(|slice| slice.count() == 0) {
        return None;
    }
    let mut end = Vec::with_capacity(slices.len());
    for slice in slices {
        end.push(
            slice
                .count()
                .checked_sub(1)?
                .checked_mul(slice.step)?
                .checked_add(slice.start)?,
        );
    }
    Some((slices.iter().map(|slice| slice.start).collect(), end))
}

fn hyperslab_bounds(dims: &[HyperslabDim]) -> Option<(Vec<u64>, Vec<u64>)> {
    if dims
        .iter()
        .any(|dim| dim.count == 0 || dim.block == 0 || dim.stride == 0)
    {
        return None;
    }
    let mut end = Vec::with_capacity(dims.len());
    for dim in dims {
        end.push(
            dim.count
                .checked_sub(1)?
                .checked_mul(dim.stride)?
                .checked_add(dim.block)?
                .checked_sub(1)?
                .checked_add(dim.start)?,
        );
    }
    Some((dims.iter().map(|dim| dim.start).collect(), end))
}

fn point_bounds(points: &[Vec<u64>]) -> Option<(Vec<u64>, Vec<u64>)> {
    let first = points.first()?;
    let mut start = first.clone();
    let mut end = first.clone();
    for point in &points[1..] {
        if point.len() != start.len() {
            return None;
        }
        for (dim, &coord) in point.iter().enumerate() {
            start[dim] = start[dim].min(coord);
            end[dim] = end[dim].max(coord);
        }
    }
    Some((start, end))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hyperslab_selected_count_reports_overflow() {
        let selection = Selection::Hyperslab(vec![HyperslabDim::new(0, 1, u64::MAX, 2)]);
        assert_eq!(selection.selected_count(&[u64::MAX]), None);
    }

    #[test]
    fn hyperslab_selected_count_uses_checked_cross_dimension_product() {
        let selection = Selection::Hyperslab(vec![
            HyperslabDim::new(0, 1, u64::MAX, 1),
            HyperslabDim::new(0, 1, 2, 1),
        ]);
        assert_eq!(selection.selected_count(&[u64::MAX, 2]), None);
    }

    #[test]
    fn hyperslab_dim_checked_output_count_rejects_overflow() {
        let dim = HyperslabDim::new(0, 1, u64::MAX, 2);
        let err = dim.checked_output_count().unwrap_err();
        assert!(
            err.to_string().contains("hyperslab output count overflow"),
            "unexpected error: {err}"
        );
        assert_eq!(dim.output_count(), u64::MAX);
    }

    #[test]
    fn selection_reset_and_combine_aliases_work() {
        let left = Selection::select_hyperslab(vec![HyperslabDim::new(0, 1, 2, 1)]);
        let right = Selection::select_hyperslab(vec![HyperslabDim::new(2, 1, 1, 1)]);
        let combined = left.combine_hyperslab(&right, &[4]).unwrap();
        assert_eq!(combined.selected_count(&[4]), Some(3));
        assert_eq!(left.modify_select(&right, &[4]).unwrap(), combined);

        let mut iter = combined.select_iter_init(&[4]).unwrap();
        assert_eq!(iter.select_iter_next(), Some(vec![0]));
        assert_eq!(iter.select_iter_next(), Some(vec![1]));
        iter.select_iter_reset();
        assert_eq!(iter.select_iter_next(), Some(vec![0]));
    }

    #[test]
    fn selection_serialization_aliases_roundtrip() {
        let points = Selection::select_elements(vec![vec![1, 2], vec![3, 4]]);
        assert!(points.mpio_point_type());
        let encoded_points = points.encode1().unwrap();
        assert_eq!(
            Selection::select_deserialize(&encoded_points).unwrap(),
            points
        );
        assert_eq!(
            Selection::point_deserialize(&points.point_serialize().unwrap()).unwrap(),
            points
        );
        assert_eq!(points.point_get_version_enc_size().unwrap().0, 1);

        let hyper = Selection::select_hyperslab(vec![
            HyperslabDim::new(0, 2, 2, 1),
            HyperslabDim::new(1, 1, 3, 1),
        ]);
        assert!(hyper.mpio_reg_hyper_type());
        let encoded_hyper = hyper.encode1().unwrap();
        assert_eq!(
            Selection::select_deserialize(&encoded_hyper).unwrap(),
            hyper
        );
        assert_eq!(
            Selection::hyper_deserialize(&hyper.hyper_serialize().unwrap()).unwrap(),
            hyper
        );
        assert_eq!(hyper.hyper_get_version_enc_size().unwrap().0, 1);
        assert_eq!(hyper.hyper_spans_nelem(&[4, 4]), Some(6));
        assert!(hyper.hyper_coord_to_span(&[0, 1], &[4, 4]));
        assert!(hyper.hyper_spans_shape_same(&hyper, &[4, 4]));
        assert!(hyper.hyper_print_diminfo().unwrap().contains("start=0"));
        assert!(hyper.space_print_spans().unwrap().contains("HyperslabDim"));

        let mut editable = Selection::select_hyperslab(vec![Selection::hyper_new_span(0, 1, 1, 1)]);
        editable
            .hyper_add_span_element(HyperslabDim::new(1, 1, 1, 1))
            .unwrap();
        assert_eq!(editable.hyper_copy_span().unwrap().len(), 2);
    }
}