hdf5-pure-rust 0.3.2

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
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
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![u64::try_from(points.len()).unwrap_or(u64::MAX)],
            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 rank_u64 = usize_to_u64(rank, "point selection rank")?;
        let point_count_u64 = usize_to_u64(points.len(), "point selection point count")?;
        let mut out = Vec::with_capacity(self.point_serial_size()?);
        push_u64(&mut out, rank_u64);
        push_u64(&mut out, point_count_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_usize_u64(bytes, &mut offset, "point selection rank")?;
        let count = read_usize_u64(bytes, &mut offset, "point selection point count")?;
        let expected_words = 2usize
            .checked_add(rank.checked_mul(count).ok_or_else(|| {
                Error::InvalidFormat("point selection serialization size overflow".into())
            })?)
            .ok_or_else(|| {
                Error::InvalidFormat("point selection serialization size overflow".into())
            })?;
        let expected_len = expected_words.checked_mul(8).ok_or_else(|| {
            Error::InvalidFormat("point selection serialization size overflow".into())
        })?;
        if bytes.len() != expected_len {
            return Err(Error::InvalidFormat(
                "point selection serialization has invalid length".into(),
            ));
        }
        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 == usize_to_u64(indexes.len(), "selection index count")?)
            }
        }
    }

    /// 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, usize_to_u64(dims.len(), "hyperslab rank")?);
        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_usize_u64(bytes, &mut offset, "hyperslab rank")?;
        let expected_words = 1usize
            .checked_add(rank.checked_mul(4).ok_or_else(|| {
                Error::InvalidFormat("hyperslab serialization size overflow".into())
            })?)
            .ok_or_else(|| Error::InvalidFormat("hyperslab serialization size overflow".into()))?;
        let expected_len = expected_words
            .checked_mul(8)
            .ok_or_else(|| Error::InvalidFormat("hyperslab serialization size overflow".into()))?;
        if bytes.len() != expected_len {
            return Err(Error::InvalidFormat(
                "hyperslab serialization has invalid length".into(),
            ));
        }
        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))
            }
        }
    }
}

#[allow(non_snake_case)]
pub fn H5Sselect_copy(selection: &Selection) -> Selection {
    selection.select_copy()
}

#[allow(non_snake_case)]
pub fn H5S_copy_pnt_list(points: &[Vec<u64>]) -> Vec<Vec<u64>> {
    Selection::copy_pnt_list(points)
}

#[allow(non_snake_case)]
pub fn H5S__copy_pnt_list(points: &[Vec<u64>]) -> Vec<Vec<u64>> {
    Selection::copy_pnt_list(points)
}

#[allow(non_snake_case)]
pub fn H5S__free_pnt_list(points: Vec<Vec<u64>>) {
    Selection::free_pnt_list(points)
}

#[allow(non_snake_case)]
pub fn H5Sget_select_npoints(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.selected_count(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_get_select_npoints(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    H5Sget_select_npoints(selection, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Sselect_valid(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.select_valid(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_select_deserialize(bytes: &[u8]) -> Result<Selection> {
    Selection::select_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__decode(bytes: &[u8]) -> Result<Selection> {
    Selection::select_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S_select_release(_selection: Selection) {}

#[allow(non_snake_case)]
pub fn H5S_select_serial_size(selection: &Selection) -> Result<usize> {
    Ok(selection.encode1()?.len())
}

#[allow(non_snake_case)]
pub fn H5S_select_serialize(selection: &Selection) -> Result<Vec<u8>> {
    selection.encode1()
}

#[allow(non_snake_case)]
pub fn H5S__encode(selection: &Selection) -> Result<Vec<u8>> {
    selection.encode1()
}

#[allow(non_snake_case)]
pub fn H5Sencode1(selection: &Selection) -> Result<Vec<u8>> {
    selection.encode1()
}

#[allow(non_snake_case)]
pub fn H5Sget_select_bounds(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.bounds(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_get_select_bounds(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    H5Sget_select_bounds(selection, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_get_select_unlim_dim(selection: &Selection, max_dims: &[u64]) -> Option<usize> {
    selection.select_unlim_dim(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S_get_select_num_elem_non_unlim(
    selection: &Selection,
    ds_shape: &[u64],
    max_dims: &[u64],
) -> Result<u64> {
    selection.select_num_elem_non_unlim(ds_shape, max_dims)
}

#[allow(non_snake_case)]
pub fn H5S_select_is_contiguous(selection: &Selection, ds_shape: &[u64]) -> Result<bool> {
    selection.select_is_contiguous(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_select_is_single(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.select_is_single(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_select_is_regular(selection: &Selection) -> bool {
    selection.is_regular()
}

#[allow(non_snake_case)]
pub fn H5S_select_none() -> Selection {
    Selection::select_none()
}

#[allow(non_snake_case)]
pub fn H5Sselect_none() -> Selection {
    Selection::select_none_api()
}

#[allow(non_snake_case)]
pub fn H5S_select_all() -> Selection {
    Selection::select_all()
}

#[allow(non_snake_case)]
pub fn H5Sselect_all() -> Selection {
    Selection::select_all_api()
}

#[allow(non_snake_case)]
pub fn H5S_select_elements(points: Vec<Vec<u64>>) -> Selection {
    Selection::select_elements(points)
}

#[allow(non_snake_case)]
pub fn H5Sselect_elements(points: Vec<Vec<u64>>) -> Selection {
    Selection::select_elements_api(points)
}

#[allow(non_snake_case)]
pub fn H5S_select_hyperslab(dims: Vec<HyperslabDim>) -> Selection {
    Selection::select_hyperslab(dims)
}

#[allow(non_snake_case)]
pub fn H5Sselect_hyperslab(dims: Vec<HyperslabDim>) -> Selection {
    Selection::select_hyperslab_api(dims)
}

#[allow(non_snake_case)]
pub fn H5Sget_select_hyper_nblocks(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.hyperslab_block_count(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Sget_select_hyper_blocklist(
    selection: &Selection,
    ds_shape: &[u64],
) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
    selection.hyperslab_blocklist(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Sget_select_elem_npoints(selection: &Selection) -> Option<u64> {
    selection.element_point_count()
}

#[allow(non_snake_case)]
pub fn H5Sget_select_elem_pointlist(selection: &Selection) -> Option<&[Vec<u64>]> {
    selection.element_pointlist()
}

#[allow(non_snake_case)]
pub fn H5S__get_select_elem_pointlist(selection: &Selection) -> Option<&[Vec<u64>]> {
    selection.get_select_elem_pointlist_internal()
}

#[allow(non_snake_case)]
pub fn H5S_select_intersect_block(
    selection: &Selection,
    ds_shape: &[u64],
    start: &[u64],
    end: &[u64],
) -> Result<bool> {
    Ok(selection
        .materialize_points(ds_shape)?
        .iter()
        .any(|point| point_is_inside_block(point, start, end)))
}

#[allow(non_snake_case)]
pub fn H5Sselect_intersect_block(
    selection: &Selection,
    ds_shape: &[u64],
    start: &[u64],
    end: &[u64],
) -> Result<bool> {
    H5S_select_intersect_block(selection, ds_shape, start, end)
}

#[allow(non_snake_case)]
pub fn H5S_select_adjust_u(selection: &Selection, offsets: &[u64]) -> Result<Selection> {
    selection.select_adjust_unsigned(offsets)
}

#[allow(non_snake_case)]
pub fn H5S_select_adjust_s(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.select_adjust_signed(offsets)
}

#[allow(non_snake_case)]
pub fn H5Sselect_adjust(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    H5S_select_adjust_s(selection, offsets)
}

#[allow(non_snake_case)]
pub fn H5S_select_project_simple(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.project(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S_select_project_scalar(selection: &Selection, ds_shape: &[u64]) -> Result<Selection> {
    selection.project(ds_shape, &[])
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_init(selection: &Selection, ds_shape: &[u64]) -> Result<SelectionPointIter> {
    selection.select_iter_init(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_coords(iter: &SelectionPointIter) -> Option<&[u64]> {
    iter.point_iter_coords()
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_nelmts(iter: &SelectionPointIter) -> usize {
    iter.select_iter_nelmts()
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_next(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    iter.select_iter_next()
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_get_seq_list(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.select_iter_get_seq_list(max_points)
}

#[allow(non_snake_case)]
pub fn H5Ssel_iter_reset(iter: &mut SelectionPointIter) {
    iter.select_iter_reset()
}

#[allow(non_snake_case)]
pub fn H5S_select_iter_release(iter: SelectionPointIter) {
    iter.select_iter_release()
}

#[allow(non_snake_case)]
pub fn H5S_select_iterate<F>(selection: &Selection, ds_shape: &[u64], callback: F) -> Result<()>
where
    F: FnMut(&[u64]) -> Result<()>,
{
    selection.select_iterate(ds_shape, callback)
}

#[allow(non_snake_case)]
pub fn H5Sget_select_type(selection: &Selection) -> SelectionType {
    selection.selection_type()
}

#[allow(non_snake_case)]
pub fn H5S_get_select_type(selection: &Selection) -> SelectionType {
    H5Sget_select_type(selection)
}

#[allow(non_snake_case)]
pub fn H5S_select_shape_same(left: &Selection, right: &Selection, ds_shape: &[u64]) -> bool {
    left.select_shape_same(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Sselect_shape_same(left: &Selection, right: &Selection, ds_shape: &[u64]) -> bool {
    H5S_select_shape_same(left, right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_select_construct_projection(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.select_construct_projection(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S_select_project_intersection(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    left.select_project_intersection(right, ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5Sselect_project_intersection(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    H5S_select_project_intersection(left, right, ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S_select_fill<T: Clone>(
    selection: &Selection,
    ds_shape: &[u64],
    buffer: &mut [T],
    value: T,
) -> Result<()> {
    selection.select_fill(ds_shape, buffer, value)
}

#[allow(non_snake_case)]
pub fn H5S_combine_hyperslab(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.combine_hyperslab(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Scombine_hyperslab(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    H5S_combine_hyperslab(left, right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__modify_select(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.modify_select_internal(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5Smodify_select(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.modify_select(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__mpio_all_type(selection: &Selection) -> bool {
    selection.mpio_all_type()
}

#[allow(non_snake_case)]
pub fn H5S__mpio_none_type(selection: &Selection) -> bool {
    selection.mpio_none_type()
}

#[allow(non_snake_case)]
pub fn H5S__mpio_point_type(selection: &Selection) -> bool {
    selection.mpio_point_type()
}

#[allow(non_snake_case)]
pub fn H5S__mpio_permute_type(selection: &Selection) -> bool {
    selection.mpio_permute_type()
}

#[allow(non_snake_case)]
pub fn H5S__mpio_reg_hyper_type(selection: &Selection) -> bool {
    selection.mpio_reg_hyper_type()
}

#[allow(non_snake_case)]
pub fn H5S__mpio_span_hyper_type(selection: &Selection) -> bool {
    selection.mpio_span_hyper_type()
}

#[allow(non_snake_case)]
pub fn H5S__none_iter_block() -> Option<Vec<u64>> {
    Selection::none_iter_block()
}

#[allow(non_snake_case)]
pub fn H5S__none_iter_nelmts() -> usize {
    Selection::none_iter_nelmts()
}

#[allow(non_snake_case)]
pub fn H5S__none_iter_get_seq_list() -> Vec<Vec<u64>> {
    Selection::none_iter_get_seq_list()
}

#[allow(non_snake_case)]
pub fn H5S__none_iter_release() {
    Selection::none_iter_release()
}

#[allow(non_snake_case)]
pub fn H5S__none_release() {
    Selection::none_release()
}

#[allow(non_snake_case)]
pub fn H5S__none_copy() -> Selection {
    Selection::none_copy()
}

#[allow(non_snake_case)]
pub fn H5S__none_is_valid() -> bool {
    Selection::none_is_valid()
}

#[allow(non_snake_case)]
pub fn H5S__none_serialize() -> Vec<u8> {
    Selection::none_serialize()
}

#[allow(non_snake_case)]
pub fn H5S__none_deserialize(bytes: &[u8]) -> Result<Selection> {
    Selection::none_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__none_bounds() -> Option<(Vec<u64>, Vec<u64>)> {
    Selection::none_bounds()
}

#[allow(non_snake_case)]
pub fn H5S__none_offset(offsets: &[i64]) -> Selection {
    Selection::none_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__none_is_contiguous() -> bool {
    Selection::none_is_contiguous()
}

#[allow(non_snake_case)]
pub fn H5S__none_is_single() -> bool {
    Selection::none_is_single()
}

#[allow(non_snake_case)]
pub fn H5S__none_is_regular() -> bool {
    Selection::none_is_regular()
}

#[allow(non_snake_case)]
pub fn H5S__none_intersect_block(start: &[u64], end: &[u64]) -> bool {
    Selection::none_intersect_block(start, end)
}

#[allow(non_snake_case)]
pub fn H5S__none_adjust_u(offsets: &[u64]) -> Selection {
    Selection::none_adjust_u(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__none_adjust_s(offsets: &[i64]) -> Selection {
    Selection::none_adjust_s(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__none_project_simple() -> Selection {
    Selection::none_project_simple()
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_init(ds_shape: &[u64]) -> Result<SelectionPointIter> {
    Selection::all_iter_init(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_coords(ds_shape: &[u64]) -> Result<Option<Vec<u64>>> {
    Selection::all_iter_coords(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_block(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
    Selection::all_iter_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_nelmts(ds_shape: &[u64]) -> Result<u64> {
    Selection::all_iter_nelmts(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_has_next_block(ds_shape: &[u64]) -> bool {
    Selection::all_iter_has_next_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_next(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    Selection::all_iter_next(iter)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_next_block(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
    Selection::all_iter_next_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_get_seq_list(ds_shape: &[u64], max_points: usize) -> Result<Vec<Vec<u64>>> {
    Selection::all_iter_get_seq_list(ds_shape, max_points)
}

#[allow(non_snake_case)]
pub fn H5S__all_iter_release(iter: SelectionPointIter) {
    Selection::all_iter_release(iter)
}

#[allow(non_snake_case)]
pub fn H5S__all_release() {
    Selection::all_release()
}

#[allow(non_snake_case)]
pub fn H5S__all_copy() -> Selection {
    Selection::all_copy()
}

#[allow(non_snake_case)]
pub fn H5S__all_is_valid(ds_shape: &[u64]) -> bool {
    Selection::all_is_valid(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_serial_size() -> usize {
    Selection::all_serial_size()
}

#[allow(non_snake_case)]
pub fn H5S__all_serialize() -> Vec<u8> {
    Selection::all_serialize()
}

#[allow(non_snake_case)]
pub fn H5S__all_deserialize(bytes: &[u8]) -> Result<Selection> {
    Selection::all_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__all_bounds(ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
    Selection::all_bounds(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_offset(offsets: &[i64]) -> Result<Selection> {
    Selection::all_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__all_unlim_dim(max_dims: &[u64]) -> Option<usize> {
    Selection::all_unlim_dim(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S__all_is_contiguous() -> bool {
    Selection::all_is_contiguous()
}

#[allow(non_snake_case)]
pub fn H5S__all_is_single(ds_shape: &[u64]) -> bool {
    Selection::all_is_single(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__all_is_regular() -> bool {
    Selection::all_is_regular()
}

#[allow(non_snake_case)]
pub fn H5S__all_intersect_block(ds_shape: &[u64], start: &[u64], end: &[u64]) -> bool {
    Selection::all_intersect_block(ds_shape, start, end)
}

#[allow(non_snake_case)]
pub fn H5S__all_adjust_u(offsets: &[u64]) -> Result<Selection> {
    Selection::all_adjust_u(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__all_adjust_s(offsets: &[i64]) -> Result<Selection> {
    Selection::all_adjust_s(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__all_project_simple(ds_shape: &[u64], kept_dims: &[usize]) -> Result<Selection> {
    Selection::all_project_simple(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_init(selection: &Selection, ds_shape: &[u64]) -> Result<SelectionPointIter> {
    selection.point_iter_init(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_coords(iter: &SelectionPointIter) -> Option<&[u64]> {
    iter.point_iter_coords()
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_nelmts(iter: &SelectionPointIter) -> usize {
    iter.point_iter_nelmts()
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_next(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    iter.point_iter_next()
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_next_block(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    iter.point_iter_next_block()
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_get_seq_list(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.point_iter_get_seq_list(max_points)
}

#[allow(non_snake_case)]
pub fn H5S__point_iter_release(iter: SelectionPointIter) {
    iter.point_iter_release()
}

#[allow(non_snake_case)]
pub fn H5S__point_copy(selection: &Selection) -> Result<Selection> {
    selection.point_copy()
}

#[allow(non_snake_case)]
pub fn H5S__point_add(selection: &mut Selection, point: Vec<u64>) -> Result<()> {
    selection.point_add(point)
}

#[allow(non_snake_case)]
pub fn H5S__point_get_version_enc_size(selection: &Selection) -> Result<(u8, usize)> {
    selection.point_get_version_enc_size()
}

#[allow(non_snake_case)]
pub fn H5S__point_serial_size(selection: &Selection) -> Result<usize> {
    selection.point_serial_size()
}

#[allow(non_snake_case)]
pub fn H5S__point_serialize(selection: &Selection) -> Result<Vec<u8>> {
    selection.point_serialize()
}

#[allow(non_snake_case)]
pub fn H5S__point_deserialize(bytes: &[u8]) -> Result<Selection> {
    Selection::point_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__point_offset(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.point_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__point_unlim_dim(selection: &Selection, max_dims: &[u64]) -> Option<usize> {
    selection.point_unlim_dim(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S__point_is_contiguous(selection: &Selection, ds_shape: &[u64]) -> Result<bool> {
    selection.point_is_contiguous(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__point_is_single(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.point_is_single(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__point_is_regular(selection: &Selection) -> bool {
    selection.point_is_regular()
}

#[allow(non_snake_case)]
pub fn H5S__point_shape_same(left: &Selection, right: &Selection, ds_shape: &[u64]) -> bool {
    left.point_shape_same(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__point_intersect_block(selection: &Selection, start: &[u64], end: &[u64]) -> bool {
    selection.point_intersect_block(start, end)
}

#[allow(non_snake_case)]
pub fn H5S__point_adjust_u(selection: &Selection, offsets: &[u64]) -> Result<Selection> {
    selection.point_adjust_u(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__point_adjust_s(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.point_adjust_s(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__point_project_scalar(selection: &Selection, ds_shape: &[u64]) -> Result<Selection> {
    selection.point_project_scalar(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__point_project_simple(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.point_project_simple(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_init(selection: &Selection, ds_shape: &[u64]) -> Result<SelectionPointIter> {
    selection.hyper_iter_init(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_block(selection: &Selection, ds_shape: &[u64]) -> Result<Option<Vec<u64>>> {
    selection.hyper_iter_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_has_next_block(selection: &Selection, ds_shape: &[u64]) -> Result<bool> {
    selection.hyper_iter_has_next_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_next(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    iter.hyper_iter_next()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_next_block(iter: &mut SelectionPointIter) -> Option<Vec<u64>> {
    iter.hyper_iter_next_block()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_get_seq_list(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.hyper_iter_get_seq_list(max_points)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_get_seq_list_gen(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.hyper_iter_get_seq_list_gen(max_points)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_seq_list_gen(
    selection: &Selection,
    ds_shape: &[u64],
    max_points: usize,
) -> Result<Vec<Vec<u64>>> {
    Ok(selection
        .hyper_iter_init(ds_shape)?
        .hyper_iter_get_seq_list_gen(max_points))
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_nelmts(iter: &SelectionPointIter) -> usize {
    iter.hyper_iter_nelmts()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_get_seq_list_opt(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.hyper_iter_get_seq_list_opt(max_points)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_get_seq_list_single(
    iter: &mut SelectionPointIter,
    max_points: usize,
) -> Vec<Vec<u64>> {
    iter.hyper_iter_get_seq_list_single(max_points)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_iter_release(iter: SelectionPointIter) {
    iter.hyper_iter_release()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_copy(selection: &Selection) -> Result<Selection> {
    selection.hyper_copy()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_new_span(start: u64, stride: u64, count: u64, block: u64) -> HyperslabDim {
    Selection::hyper_new_span(start, stride, count, block)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_new_span_info(dims: Vec<HyperslabDim>) -> Selection {
    Selection::hyper_new_span_info(dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_copy_span_helper(selection: &Selection) -> Result<Vec<HyperslabDim>> {
    selection.hyper_copy_span_helper()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_copy_span(selection: &Selection) -> Result<Vec<HyperslabDim>> {
    selection.hyper_copy_span()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_cmp_spans(left: &Selection, right: &Selection) -> bool {
    left.hyper_cmp_spans(right)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_spans(selection: &Selection) -> Result<String> {
    selection.hyper_print_spans()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_spans_helper(selection: &Selection) -> Result<String> {
    selection.hyper_print_spans_helper()
}

#[allow(non_snake_case)]
pub fn H5S__space_print_spans(selection: &Selection) -> Result<String> {
    selection.space_print_spans()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_diminfo(selection: &Selection) -> Result<String> {
    selection.hyper_print_diminfo()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_diminfo_helper(selection: &Selection) -> Result<String> {
    selection.hyper_print_diminfo_helper()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_spans_dfs(selection: &Selection) -> Result<String> {
    selection.hyper_print_spans_dfs()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_print_space_dfs(selection: &Selection) -> Result<String> {
    selection.hyper_print_space_dfs()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_free_span(selection: Selection) {
    selection.hyper_free_span()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_release(selection: Selection) {
    selection.hyper_release()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_enc_size_real(selection: &Selection) -> Result<usize> {
    selection.hyper_get_enc_size_real()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_version_enc_size(selection: &Selection) -> Result<(u8, usize)> {
    selection.hyper_get_version_enc_size()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_serialize(selection: &Selection) -> Result<Vec<u8>> {
    selection.hyper_serialize()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_serialize_helper(selection: &Selection) -> Result<Vec<u8>> {
    selection.hyper_serialize_helper()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_deserialize(bytes: &[u8]) -> Result<Selection> {
    Selection::hyper_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_decode(bytes: &[u8]) -> Result<Selection> {
    Selection::hyper_deserialize(bytes)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_is_valid(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.hyper_is_valid(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_span_nblocks(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.hyper_span_nblocks(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_span_blocklist(
    selection: &Selection,
    ds_shape: &[u64],
) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
    selection.hyper_span_blocklist(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__get_select_hyper_nblocks(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.get_select_hyper_nblocks_internal(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__get_select_hyper_blocklist(
    selection: &Selection,
    ds_shape: &[u64],
) -> Result<Option<Vec<(Vec<u64>, Vec<u64>)>>> {
    selection.get_select_hyper_blocklist_internal(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_intersect_block_helper(
    selection: &Selection,
    ds_shape: &[u64],
    start: &[u64],
    end: &[u64],
) -> bool {
    selection.hyper_intersect_block_helper(ds_shape, start, end)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_bounds(selection: &Selection, ds_shape: &[u64]) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.hyper_bounds(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_offset(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.hyper_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_unlim_dim(selection: &Selection, max_dims: &[u64]) -> Option<usize> {
    selection.hyper_unlim_dim(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_num_elem_non_unlim(
    selection: &Selection,
    ds_shape: &[u64],
    max_dims: &[u64],
) -> Result<u64> {
    selection.hyper_num_elem_non_unlim(ds_shape, max_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_is_contiguous(selection: &Selection, ds_shape: &[u64]) -> Result<bool> {
    selection.hyper_is_contiguous(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_is_single(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.hyper_is_single(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_is_regular(selection: &Selection) -> bool {
    selection.hyper_is_regular()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_spans_nelem(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.hyper_spans_nelem(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_spans_nelem_helper(selection: &Selection, ds_shape: &[u64]) -> Option<u64> {
    selection.hyper_spans_nelem_helper(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_shape_same(left: &Selection, right: &Selection, ds_shape: &[u64]) -> bool {
    left.hyper_shape_same(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_spans_shape_same_helper(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> bool {
    left.hyper_spans_shape_same_helper(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_spans_shape_same(left: &Selection, right: &Selection, ds_shape: &[u64]) -> bool {
    left.hyper_spans_shape_same(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_regular_and_single_block(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.hyper_regular_and_single_block(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_regular_hyperslab(selection: &Selection) -> Result<Vec<HyperslabDim>> {
    selection.hyper_copy_span_helper()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_coord_to_span(selection: &Selection, coord: &[u64], ds_shape: &[u64]) -> bool {
    selection.hyper_coord_to_span(coord, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_add_span_element(selection: &mut Selection, dim: HyperslabDim) -> Result<()> {
    selection.hyper_add_span_element(dim)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_append_span(selection: &mut Selection, dim: HyperslabDim) -> Result<()> {
    selection.hyper_append_span(dim)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_clip_spans(
    selection: &Selection,
    ds_shape: &[u64],
    start: &[u64],
    end: &[u64],
) -> Result<Selection> {
    selection.hyper_clip_spans(ds_shape, start, end)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_merge_spans_helper(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.hyper_merge_spans_helper(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_merge_spans(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.hyper_merge_spans(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_add_disjoint_spans(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<Selection> {
    left.hyper_add_disjoint_spans(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_make_spans(dims: Vec<HyperslabDim>) -> Selection {
    Selection::hyper_make_spans(dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_update_diminfo(selection: &Selection) -> Result<Vec<HyperslabDim>> {
    selection.hyper_update_diminfo()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_rebuild_helper(selection: &Selection) -> Result<Selection> {
    selection.hyper_rebuild_helper()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_rebuild(selection: &Selection) -> Result<Selection> {
    selection.hyper_rebuild()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_generate_spans(selection: &Selection) -> Result<Selection> {
    selection.hyper_generate_spans()
}

#[allow(non_snake_case)]
pub fn H5S__check_spans_overlap(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> Result<bool> {
    left.check_spans_overlap(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__fill_in_new_space(selection: &Selection, ds_shape: &[u64]) -> Result<Selection> {
    selection.fill_in_new_space(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__set_regular_hyperslab(dims: Vec<HyperslabDim>) -> Selection {
    Selection::set_regular_hyperslab(dims)
}

#[allow(non_snake_case)]
pub fn H5S__fill_in_select(selection: &Selection) -> Selection {
    selection.fill_in_select()
}

#[allow(non_snake_case)]
pub fn H5S__hyper_adjust_u(selection: &Selection, offsets: &[u64]) -> Result<Selection> {
    selection.hyper_adjust_u(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_adjust_u_helper(selection: &Selection, offsets: &[u64]) -> Result<Selection> {
    selection.hyper_adjust_u_helper(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_adjust_s(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.hyper_adjust_s(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_adjust_s_helper(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.hyper_adjust_s_helper(offsets)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_normalize_offset(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.hyper_normalize_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_denormalize_offset(selection: &Selection, offsets: &[i64]) -> Result<Selection> {
    selection.hyper_denormalize_offset(offsets)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_project_scalar(selection: &Selection, ds_shape: &[u64]) -> Result<Selection> {
    selection.hyper_project_scalar(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_project_simple(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.hyper_project_simple(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_project_simple_lower(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.hyper_project_simple_lower(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_project_simple_higher(
    selection: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    selection.hyper_project_simple_higher(ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_proj_int_build_proj(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    left.hyper_proj_int_build_proj(right, ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_proj_int_iterate(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Vec<Vec<u64>>> {
    left.hyper_proj_int_iterate(right, ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_project_intersection(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
    kept_dims: &[usize],
) -> Result<Selection> {
    left.hyper_project_intersection(right, ds_shape, kept_dims)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_clip_diminfo(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.hyper_get_clip_diminfo(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_clip_unlim(selection: &Selection, ds_shape: &[u64]) -> Result<Selection> {
    selection.hyper_clip_unlim(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_clip_extent_real(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.hyper_get_clip_extent_real(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_clip_extent(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.hyper_get_clip_extent(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_get_clip_extent(
    selection: &Selection,
    ds_shape: &[u64],
) -> Option<(Vec<u64>, Vec<u64>)> {
    selection.hyper_get_clip_extent(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_clip_extent_match(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> bool {
    left.hyper_get_clip_extent_match(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_get_clip_extent_match(
    left: &Selection,
    right: &Selection,
    ds_shape: &[u64],
) -> bool {
    left.hyper_get_clip_extent_match(right, ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__hyper_get_unlim_block(selection: &Selection, max_dims: &[u64]) -> Option<usize> {
    selection.hyper_get_unlim_block(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S_hyper_get_unlim_block(selection: &Selection, max_dims: &[u64]) -> Option<usize> {
    selection.hyper_get_unlim_block(max_dims)
}

#[allow(non_snake_case)]
pub fn H5S__get_rebuild_status_test(selection: &Selection) -> bool {
    selection.get_rebuild_status_test()
}

#[allow(non_snake_case)]
pub fn H5S__get_diminfo_status_test(selection: &Selection) -> bool {
    selection.get_diminfo_status_test()
}

#[allow(non_snake_case)]
pub fn H5S__check_spans_tail_ptr(selection: &Selection) -> bool {
    selection.check_spans_tail_ptr()
}

#[allow(non_snake_case)]
pub fn H5S__check_internal_consistency(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.check_internal_consistency(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__internal_consistency_test(selection: &Selection, ds_shape: &[u64]) -> bool {
    selection.internal_consistency_test(ds_shape)
}

#[allow(non_snake_case)]
pub fn H5S__verify_offsets(selection: &Selection, offsets: &[i64]) -> bool {
    selection.verify_offsets(offsets)
}

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 usize_to_u64(value: usize, context: &str) -> Result<u64> {
    u64::try_from(value).map_err(|_| Error::InvalidFormat(format!("{context} exceeds u64")))
}

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 read_usize_u64(bytes: &[u8], offset: &mut usize, context: &str) -> Result<usize> {
    let value = read_u64(bytes, offset)?;
    usize::try_from(value).map_err(|_| Error::InvalidFormat(format!("{context} exceeds usize")))
}

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);
        assert!(Selection::point_deserialize(&u64::MAX.to_le_bytes()).is_err());

        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!(Selection::hyper_deserialize(&u64::MAX.to_le_bytes()).is_err());
        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);
    }

    #[test]
    fn h5s_selection_aliases_dispatch_to_selection_methods() {
        let selection = Selection::select_hyperslab(vec![
            HyperslabDim::new(0, 1, 2, 1),
            HyperslabDim::new(1, 1, 2, 1),
        ]);
        let ds_shape = [4, 4];

        assert_eq!(H5Sselect_copy(&selection), selection);
        assert_eq!(
            H5S__copy_pnt_list(&[vec![0, 0], vec![1, 1]]),
            vec![vec![0, 0], vec![1, 1]]
        );
        H5S__free_pnt_list(vec![vec![0, 0]]);
        assert_eq!(H5Sget_select_npoints(&selection, &ds_shape), Some(4));
        assert_eq!(H5S_get_select_npoints(&selection, &ds_shape), Some(4));
        assert!(H5Sselect_valid(&selection, &ds_shape));
        assert_eq!(
            H5Sget_select_bounds(&selection, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(
            H5S_get_select_bounds(&selection, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(
            H5S_get_select_unlim_dim(&selection, &[4, u64::MAX]),
            Some(1)
        );
        assert_eq!(
            H5S_get_select_num_elem_non_unlim(&selection, &ds_shape, &[4, u64::MAX]).unwrap(),
            2
        );
        assert!(!H5S_select_is_contiguous(&selection, &ds_shape).unwrap());
        assert!(!H5S_select_is_single(&selection, &ds_shape));
        assert!(H5S_select_is_regular(&selection));
        assert_eq!(H5Sget_select_type(&selection), SelectionType::Hyperslab);
        assert_eq!(H5S_get_select_type(&selection), SelectionType::Hyperslab);
        assert_eq!(H5S_select_none(), Selection::None);
        assert_eq!(H5Sselect_none(), Selection::None);
        assert_eq!(H5S_select_all(), Selection::All);
        assert_eq!(H5Sselect_all(), Selection::All);
        assert_eq!(
            H5S_select_elements(vec![vec![2, 3]]),
            Selection::Points(vec![vec![2, 3]])
        );
        assert_eq!(
            H5Sselect_elements(vec![vec![3, 2]]),
            Selection::Points(vec![vec![3, 2]])
        );
        assert_eq!(
            H5S_select_hyperslab(vec![HyperslabDim::new(0, 1, 1, 1)]),
            Selection::Hyperslab(vec![HyperslabDim::new(0, 1, 1, 1)])
        );
        assert_eq!(
            H5Sselect_hyperslab(vec![HyperslabDim::new(1, 1, 1, 1)]),
            Selection::Hyperslab(vec![HyperslabDim::new(1, 1, 1, 1)])
        );
        assert_eq!(H5Sget_select_hyper_nblocks(&selection, &ds_shape), Some(4));
        assert_eq!(
            H5Sget_select_hyper_blocklist(&selection, &ds_shape).unwrap(),
            Some(vec![
                (vec![0, 1], vec![0, 1]),
                (vec![0, 2], vec![0, 2]),
                (vec![1, 1], vec![1, 1]),
                (vec![1, 2], vec![1, 2])
            ])
        );
        let point_selection = Selection::Points(vec![vec![0, 0], vec![3, 3]]);
        assert_eq!(H5Sget_select_elem_npoints(&point_selection), Some(2));
        assert_eq!(
            H5Sget_select_elem_pointlist(&point_selection),
            Some(&[vec![0, 0], vec![3, 3]][..])
        );
        assert_eq!(
            H5S__get_select_elem_pointlist(&point_selection),
            Some(&[vec![0, 0], vec![3, 3]][..])
        );
        assert!(H5S_select_intersect_block(&selection, &ds_shape, &[1, 2], &[1, 2]).unwrap());
        assert!(!H5Sselect_intersect_block(&selection, &ds_shape, &[3, 3], &[3, 3]).unwrap());

        let adjusted = H5S_select_adjust_u(&selection, &[1, 0]).unwrap();
        assert_eq!(
            H5Sget_select_bounds(&adjusted, &ds_shape),
            Some((vec![1, 1], vec![2, 2]))
        );
        let adjusted = H5Sselect_adjust(&selection, &[0, -1]).unwrap();
        assert_eq!(
            H5Sget_select_bounds(&adjusted, &ds_shape),
            Some((vec![0, 0], vec![1, 1]))
        );

        let encoded = selection.encode1().unwrap();
        assert_eq!(H5S_select_serial_size(&selection).unwrap(), encoded.len());
        assert_eq!(H5S_select_serialize(&selection).unwrap(), encoded);
        assert_eq!(H5S__encode(&selection).unwrap(), encoded);
        assert_eq!(H5Sencode1(&selection).unwrap(), encoded);
        assert_eq!(H5S_select_deserialize(&encoded).unwrap(), selection);
        assert_eq!(H5S__decode(&encoded).unwrap(), selection);
        H5S_select_release(selection.clone());
        let projected = H5S_select_project_simple(&selection, &ds_shape, &[1]).unwrap();
        assert_eq!(
            projected.materialize_points(&[4]).unwrap(),
            vec![vec![1], vec![2]]
        );
        assert_eq!(
            H5S_select_project_scalar(&selection, &ds_shape).unwrap(),
            Selection::Points(vec![vec![]])
        );
        assert_eq!(
            H5S_select_construct_projection(&selection, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![0], vec![1]])
        );
        assert!(H5Sselect_shape_same(&selection, &selection, &ds_shape));

        let mut iter = H5S_select_iter_init(&selection, &ds_shape).unwrap();
        assert_eq!(H5S_select_iter_coords(&iter), Some(&[0, 1][..]));
        assert_eq!(H5S_select_iter_nelmts(&iter), 4);
        assert_eq!(H5S_select_iter_next(&mut iter), Some(vec![0, 1]));
        assert_eq!(
            H5S_select_iter_get_seq_list(&mut iter, 2),
            vec![vec![0, 2], vec![1, 1]]
        );
        H5Ssel_iter_reset(&mut iter);
        assert_eq!(H5S_select_iter_next(&mut iter), Some(vec![0, 1]));
        H5S_select_iter_release(iter);

        let mut visited = Vec::new();
        H5S_select_iterate(&selection, &ds_shape, |point| {
            visited.push(point.to_vec());
            Ok(())
        })
        .unwrap();
        assert_eq!(visited.len(), 4);

        let other = Selection::select_hyperslab(vec![
            HyperslabDim::new(1, 1, 1, 1),
            HyperslabDim::new(2, 1, 1, 1),
        ]);
        assert_eq!(
            H5S_select_project_intersection(&selection, &other, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![1]])
        );
        assert_eq!(
            H5Sselect_project_intersection(&selection, &other, &ds_shape, &[1]).unwrap(),
            Selection::Points(vec![vec![2]])
        );
        assert_eq!(
            H5S_combine_hyperslab(&selection, &other, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(4)
        );
        assert_eq!(
            H5Scombine_hyperslab(&selection, &other, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(4)
        );
        assert_eq!(
            H5S__modify_select(&selection, &other, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(4)
        );
        assert_eq!(
            H5Smodify_select(&selection, &other, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(4)
        );
        assert!(H5S__mpio_reg_hyper_type(&selection));
        assert!(!H5S__mpio_all_type(&selection));
        assert!(!H5S__mpio_none_type(&selection));
        assert!(!H5S__mpio_point_type(&selection));
        assert!(!H5S__mpio_permute_type(&selection));
        assert!(!H5S__mpio_span_hyper_type(&selection));

        let mut buffer = vec![0u8; 16];
        H5S_select_fill(&selection, &ds_shape, &mut buffer, 7).unwrap();
        assert_eq!(buffer[1], 7);
        assert_eq!(buffer[2], 7);
        assert_eq!(buffer[5], 7);
        assert_eq!(buffer[6], 7);
    }

    #[test]
    fn h5s_selection_class_aliases_dispatch_to_selection_methods() {
        assert_eq!(H5S__none_iter_block(), None);
        assert_eq!(H5S__none_iter_nelmts(), 0);
        assert_eq!(H5S__none_iter_get_seq_list(), Vec::<Vec<u64>>::new());
        H5S__none_iter_release();
        H5S__none_release();
        assert_eq!(H5S__none_copy(), Selection::None);
        assert!(H5S__none_is_valid());
        assert_eq!(H5S__none_serialize(), Vec::<u8>::new());
        assert_eq!(H5S__none_deserialize(&[]).unwrap(), Selection::None);
        assert_eq!(H5S__none_bounds(), None);
        assert_eq!(H5S__none_offset(&[1, -1]), Selection::None);
        assert!(H5S__none_is_contiguous());
        assert!(!H5S__none_is_single());
        assert!(H5S__none_is_regular());
        assert!(!H5S__none_intersect_block(&[0], &[0]));
        assert_eq!(H5S__none_adjust_u(&[1]), Selection::None);
        assert_eq!(H5S__none_adjust_s(&[-1]), Selection::None);
        assert_eq!(H5S__none_project_simple(), Selection::None);

        let ds_shape = [2, 3];
        let mut all_iter = H5S__all_iter_init(&ds_shape).unwrap();
        assert_eq!(H5S__all_iter_coords(&ds_shape).unwrap(), Some(vec![0, 0]));
        assert_eq!(
            H5S__all_iter_block(&ds_shape),
            Some((vec![0, 0], vec![1, 2]))
        );
        assert_eq!(H5S__all_iter_nelmts(&ds_shape).unwrap(), 6);
        assert!(H5S__all_iter_has_next_block(&ds_shape));
        assert_eq!(H5S__all_iter_next(&mut all_iter), Some(vec![0, 0]));
        assert_eq!(
            H5S__all_iter_next_block(&ds_shape),
            Some((vec![0, 0], vec![1, 2]))
        );
        assert_eq!(
            H5S__all_iter_get_seq_list(&ds_shape, 3).unwrap(),
            vec![vec![0, 0], vec![0, 1], vec![0, 2]]
        );
        H5S__all_iter_release(all_iter);
        H5S__all_release();
        assert_eq!(H5S__all_copy(), Selection::All);
        assert!(H5S__all_is_valid(&ds_shape));
        assert_eq!(H5S__all_serial_size(), 0);
        assert_eq!(H5S__all_serialize(), Vec::<u8>::new());
        assert_eq!(H5S__all_deserialize(&[]).unwrap(), Selection::All);
        assert_eq!(H5S__all_bounds(&ds_shape), Some((vec![0, 0], vec![1, 2])));
        assert_eq!(H5S__all_offset(&[0, 0]).unwrap(), Selection::All);
        assert_eq!(H5S__all_unlim_dim(&[2, u64::MAX]), Some(1));
        assert!(H5S__all_is_contiguous());
        assert!(!H5S__all_is_single(&ds_shape));
        assert!(H5S__all_is_regular());
        assert!(H5S__all_intersect_block(&ds_shape, &[1, 2], &[1, 2]));
        assert_eq!(H5S__all_adjust_u(&[0, 0]).unwrap(), Selection::All);
        assert_eq!(H5S__all_adjust_s(&[0, 0]).unwrap(), Selection::All);
        assert_eq!(
            H5S__all_project_simple(&ds_shape, &[1]).unwrap(),
            Selection::Points(vec![vec![0], vec![1], vec![2]])
        );

        let mut points = Selection::Points(vec![vec![0, 1], vec![1, 2]]);
        let mut point_iter = H5S__point_iter_init(&points, &ds_shape).unwrap();
        assert_eq!(H5S__point_iter_coords(&point_iter), Some(&[0, 1][..]));
        assert_eq!(H5S__point_iter_nelmts(&point_iter), 2);
        assert_eq!(H5S__point_iter_next(&mut point_iter), Some(vec![0, 1]));
        assert_eq!(
            H5S__point_iter_next_block(&mut point_iter),
            Some(vec![1, 2])
        );
        let mut point_iter = H5S__point_iter_init(&points, &ds_shape).unwrap();
        assert_eq!(
            H5S__point_iter_get_seq_list(&mut point_iter, 2),
            vec![vec![0, 1], vec![1, 2]]
        );
        H5S__point_iter_release(point_iter);
        assert_eq!(H5S__point_copy(&points).unwrap(), points);
        H5S__point_add(&mut points, vec![0, 2]).unwrap();
        assert_eq!(points.selected_count(&ds_shape), Some(3));
        assert_eq!(H5S__point_get_version_enc_size(&points).unwrap().0, 1);
        let point_payload = H5S__point_serialize(&points).unwrap();
        assert_eq!(
            H5S__point_serial_size(&points).unwrap(),
            point_payload.len()
        );
        assert_eq!(H5S__point_deserialize(&point_payload).unwrap(), points);
        assert_eq!(
            H5S__get_select_elem_pointlist(&points),
            Some(&[vec![0, 1], vec![1, 2], vec![0, 2]][..])
        );
        assert_eq!(
            H5S__point_offset(&points, &[1, 0]).unwrap().bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(H5S__point_unlim_dim(&points, &[2, u64::MAX]), Some(1));
        assert!(!H5S__point_is_contiguous(&points, &ds_shape).unwrap());
        assert!(!H5S__point_is_single(&points, &ds_shape));
        assert!(!H5S__point_is_regular(&points));
        assert!(H5S__point_shape_same(&points, &points, &ds_shape));
        assert!(H5S__point_intersect_block(&points, &[1, 2], &[1, 2]));
        assert_eq!(
            H5S__point_adjust_u(&points, &[1, 0])
                .unwrap()
                .bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(
            H5S__point_adjust_s(&points, &[0, -1])
                .unwrap()
                .bounds(&ds_shape),
            Some((vec![0, 0], vec![1, 1]))
        );
        assert_eq!(
            H5S__point_project_scalar(&points, &ds_shape).unwrap(),
            Selection::Points(vec![vec![]])
        );
        assert_eq!(
            H5S__point_project_simple(&points, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![0], vec![1]])
        );

        let hyper = Selection::Hyperslab(vec![
            HyperslabDim::new(0, 1, 2, 1),
            HyperslabDim::new(1, 1, 2, 1),
        ]);
        let mut hyper_iter = H5S__hyper_iter_init(&hyper, &ds_shape).unwrap();
        assert_eq!(
            H5S__hyper_iter_block(&hyper, &ds_shape).unwrap(),
            Some(vec![0, 1])
        );
        assert!(H5S__hyper_iter_has_next_block(&hyper, &ds_shape).unwrap());
        assert_eq!(H5S__hyper_iter_next(&mut hyper_iter), Some(vec![0, 1]));
        assert_eq!(
            H5S__hyper_iter_next_block(&mut hyper_iter),
            Some(vec![0, 2])
        );
        let mut hyper_iter = H5S__hyper_iter_init(&hyper, &ds_shape).unwrap();
        assert_eq!(
            H5S__hyper_iter_get_seq_list(&mut hyper_iter, 2),
            vec![vec![0, 1], vec![0, 2]]
        );
        let mut hyper_iter = H5S__hyper_iter_init(&hyper, &ds_shape).unwrap();
        assert_eq!(
            H5S__hyper_iter_get_seq_list_gen(&mut hyper_iter, 1),
            vec![vec![0, 1]]
        );
        let mut hyper_iter = H5S__hyper_iter_init(&hyper, &ds_shape).unwrap();
        assert_eq!(
            H5S__hyper_iter_get_seq_list_opt(&mut hyper_iter, 1),
            vec![vec![0, 1]]
        );
        let mut hyper_iter = H5S__hyper_iter_init(&hyper, &ds_shape).unwrap();
        assert_eq!(
            H5S__hyper_iter_get_seq_list_single(&mut hyper_iter, 1),
            vec![vec![0, 1]]
        );
        assert_eq!(H5S__hyper_iter_nelmts(&hyper_iter), 3);
        H5S__hyper_iter_release(hyper_iter);
        assert_eq!(
            H5S__hyper_get_seq_list_gen(&hyper, &ds_shape, 2).unwrap(),
            vec![vec![0, 1], vec![0, 2]]
        );
        assert_eq!(H5S__hyper_copy(&hyper).unwrap(), hyper);
        assert_eq!(
            H5S__hyper_new_span(0, 1, 1, 1),
            HyperslabDim::new(0, 1, 1, 1)
        );
        assert_eq!(
            H5S__hyper_new_span_info(vec![HyperslabDim::new(0, 1, 1, 1)]),
            Selection::Hyperslab(vec![HyperslabDim::new(0, 1, 1, 1)])
        );
        assert_eq!(H5S__hyper_copy_span(&hyper).unwrap().len(), 2);
        assert_eq!(H5S__hyper_copy_span_helper(&hyper).unwrap().len(), 2);
        assert!(H5S__hyper_cmp_spans(&hyper, &hyper));
        assert!(H5S__hyper_print_spans_helper(&hyper)
            .unwrap()
            .contains("HyperslabDim"));
        assert!(H5S__hyper_print_spans(&hyper)
            .unwrap()
            .contains("HyperslabDim"));
        assert!(H5S__space_print_spans(&hyper)
            .unwrap()
            .contains("HyperslabDim"));
        assert!(H5S__hyper_print_diminfo_helper(&hyper)
            .unwrap()
            .contains("start=0"));
        assert!(H5S__hyper_print_diminfo(&hyper)
            .unwrap()
            .contains("start=0"));
        assert!(H5S__hyper_print_spans_dfs(&hyper)
            .unwrap()
            .contains("HyperslabDim"));
        assert!(H5S__hyper_print_space_dfs(&hyper)
            .unwrap()
            .contains("HyperslabDim"));
        assert_eq!(
            H5S__hyper_get_enc_size_real(&hyper).unwrap(),
            H5S__hyper_serialize(&hyper).unwrap().len()
        );
        assert_eq!(H5S__hyper_get_version_enc_size(&hyper).unwrap().0, 1);
        let hyper_payload = H5S__hyper_serialize(&hyper).unwrap();
        assert_eq!(H5S__hyper_serialize_helper(&hyper).unwrap(), hyper_payload);
        assert_eq!(H5S__hyper_deserialize(&hyper_payload).unwrap(), hyper);
        assert_eq!(H5S__hyper_decode(&hyper_payload).unwrap(), hyper);
        assert!(H5S__hyper_is_valid(&hyper, &ds_shape));
        assert_eq!(H5S__hyper_span_nblocks(&hyper, &ds_shape), Some(4));
        assert_eq!(H5S__get_select_hyper_nblocks(&hyper, &ds_shape), Some(4));
        assert_eq!(
            H5S__hyper_span_blocklist(&hyper, &ds_shape)
                .unwrap()
                .unwrap()
                .len(),
            4
        );
        assert_eq!(
            H5S__get_select_hyper_blocklist(&hyper, &ds_shape)
                .unwrap()
                .unwrap()
                .len(),
            4
        );
        assert!(H5S__hyper_intersect_block_helper(
            &hyper,
            &ds_shape,
            &[1, 2],
            &[1, 2]
        ));
        assert_eq!(
            H5S__hyper_bounds(&hyper, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(
            H5S__hyper_offset(&hyper, &[1, 0]).unwrap().bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(H5S__hyper_unlim_dim(&hyper, &[2, u64::MAX]), Some(1));
        assert_eq!(
            H5S__hyper_num_elem_non_unlim(&hyper, &ds_shape, &[2, u64::MAX]).unwrap(),
            2
        );
        assert!(!H5S__hyper_is_contiguous(&hyper, &ds_shape).unwrap());
        assert!(!H5S__hyper_is_single(&hyper, &ds_shape));
        assert!(H5S__hyper_is_regular(&hyper));
        assert_eq!(H5S__hyper_spans_nelem(&hyper, &ds_shape), Some(4));
        assert_eq!(H5S__hyper_spans_nelem_helper(&hyper, &ds_shape), Some(4));
        assert!(H5S__hyper_shape_same(&hyper, &hyper, &ds_shape));
        assert!(H5S__hyper_spans_shape_same_helper(
            &hyper, &hyper, &ds_shape
        ));
        assert!(H5S__hyper_spans_shape_same(&hyper, &hyper, &ds_shape));
        assert!(!H5S__hyper_regular_and_single_block(&hyper, &ds_shape));
        assert_eq!(H5S__hyper_get_regular_hyperslab(&hyper).unwrap().len(), 2);
        assert!(H5S__hyper_coord_to_span(&hyper, &[0, 1], &ds_shape));
        let mut editable_hyper = H5S__hyper_make_spans(vec![HyperslabDim::new(0, 1, 1, 1)]);
        H5S_hyper_add_span_element(&mut editable_hyper, HyperslabDim::new(1, 1, 1, 1)).unwrap();
        H5S__hyper_append_span(&mut editable_hyper, HyperslabDim::new(2, 1, 1, 1)).unwrap();
        assert_eq!(H5S__hyper_update_diminfo(&editable_hyper).unwrap().len(), 3);
        assert_eq!(H5S__hyper_rebuild_helper(&hyper).unwrap(), hyper);
        assert_eq!(H5S__hyper_rebuild(&hyper).unwrap(), hyper);
        assert_eq!(H5S__hyper_generate_spans(&hyper).unwrap(), hyper);
        assert_eq!(H5S__fill_in_select(&hyper), hyper);
        assert_eq!(H5S__fill_in_new_space(&hyper, &ds_shape).unwrap(), hyper);
        assert_eq!(
            H5S__set_regular_hyperslab(vec![HyperslabDim::new(0, 1, 1, 1)]),
            Selection::Hyperslab(vec![HyperslabDim::new(0, 1, 1, 1)])
        );
        let disjoint = Selection::Hyperslab(vec![
            HyperslabDim::new(0, 1, 1, 1),
            HyperslabDim::new(0, 1, 1, 1),
        ]);
        assert!(H5S__check_spans_overlap(&hyper, &hyper, &ds_shape).unwrap());
        assert_eq!(
            H5S__hyper_clip_spans(&hyper, &ds_shape, &[1, 2], &[1, 2]).unwrap(),
            Selection::Points(vec![vec![1, 2]])
        );
        assert_eq!(
            H5S__hyper_merge_spans_helper(&disjoint, &hyper, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(5)
        );
        assert_eq!(
            H5S__hyper_merge_spans(&disjoint, &hyper, &ds_shape)
                .unwrap()
                .selected_count(&ds_shape),
            Some(5)
        );
        assert_eq!(
            H5S__hyper_add_disjoint_spans(
                &disjoint,
                &Selection::Hyperslab(vec![
                    HyperslabDim::new(1, 1, 1, 1),
                    HyperslabDim::new(2, 1, 1, 1),
                ]),
                &ds_shape
            )
            .unwrap()
            .selected_count(&ds_shape),
            Some(2)
        );
        assert_eq!(
            H5S__hyper_adjust_u(&hyper, &[1, 0])
                .unwrap()
                .bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(
            H5S__hyper_adjust_s(&hyper, &[0, -1])
                .unwrap()
                .bounds(&ds_shape),
            Some((vec![0, 0], vec![1, 1]))
        );
        assert_eq!(
            H5S__hyper_adjust_u_helper(&hyper, &[1, 0])
                .unwrap()
                .bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(
            H5S__hyper_adjust_s_helper(&hyper, &[0, -1])
                .unwrap()
                .bounds(&ds_shape),
            Some((vec![0, 0], vec![1, 1]))
        );
        assert_eq!(
            H5S_hyper_normalize_offset(&hyper, &[1, 0])
                .unwrap()
                .bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(
            H5S_hyper_denormalize_offset(&hyper, &[1, 0])
                .unwrap()
                .bounds(&[3, 3]),
            Some((vec![1, 1], vec![2, 2]))
        );
        assert_eq!(
            H5S__hyper_project_scalar(&hyper, &ds_shape).unwrap(),
            Selection::Points(vec![vec![]])
        );
        assert_eq!(
            H5S__hyper_project_simple(&hyper, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![0], vec![1]])
        );
        assert_eq!(
            H5S__hyper_project_simple_lower(&hyper, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![0], vec![1]])
        );
        assert_eq!(
            H5S__hyper_project_simple_higher(&hyper, &ds_shape, &[1]).unwrap(),
            Selection::Points(vec![vec![1], vec![2]])
        );
        assert_eq!(
            H5S__hyper_proj_int_build_proj(&hyper, &hyper, &ds_shape, &[0]).unwrap(),
            Selection::Points(vec![vec![0], vec![1]])
        );
        assert_eq!(
            H5S__hyper_proj_int_iterate(&hyper, &hyper, &ds_shape, &[1]).unwrap(),
            vec![vec![1], vec![2]]
        );
        assert_eq!(
            H5S__hyper_project_intersection(&hyper, &hyper, &ds_shape, &[1]).unwrap(),
            Selection::Points(vec![vec![1], vec![2]])
        );
        assert_eq!(
            H5S__hyper_get_clip_diminfo(&hyper, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(H5S_hyper_clip_unlim(&hyper, &ds_shape).unwrap(), hyper);
        assert_eq!(
            H5S__hyper_get_clip_extent_real(&hyper, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(
            H5S__hyper_get_clip_extent(&hyper, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert_eq!(
            H5S_hyper_get_clip_extent(&hyper, &ds_shape),
            Some((vec![0, 1], vec![1, 2]))
        );
        assert!(H5S__hyper_get_clip_extent_match(&hyper, &hyper, &ds_shape));
        assert!(H5S_hyper_get_clip_extent_match(&hyper, &hyper, &ds_shape));
        assert_eq!(H5S__hyper_get_unlim_block(&hyper, &[2, u64::MAX]), Some(1));
        assert_eq!(H5S_hyper_get_unlim_block(&hyper, &[2, u64::MAX]), Some(1));
        assert!(H5S__get_rebuild_status_test(&hyper));
        assert!(H5S__get_diminfo_status_test(&hyper));
        assert!(H5S__check_spans_tail_ptr(&hyper));
        assert!(H5S__check_internal_consistency(&hyper, &ds_shape));
        assert!(H5S__internal_consistency_test(&hyper, &ds_shape));
        assert!(H5S__verify_offsets(&hyper, &[0, 0]));
        H5S__hyper_free_span(hyper.clone());
        H5S__hyper_release(hyper);
    }
}