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
//! HDF5 file handle — the main entry point for the public API.
//!
//! ```no_run
//! use rust_hdf5::H5File;
//!
//! // Write
//! let file = H5File::create("example.h5").unwrap();
//! let ds = file.new_dataset::<u8>().shape(&[10, 20]).create("data").unwrap();
//! ds.write_raw(&vec![0u8; 200]).unwrap();
//! drop(file);
//!
//! // Read
//! let file = H5File::open("example.h5").unwrap();
//! let ds = file.dataset("data").unwrap();
//! let data = ds.read_raw::<u8>().unwrap();
//! assert_eq!(data.len(), 200);
//! ```
use std::path::Path;
use crate::format::messages::superblock_ext::FileSpaceStrategy;
use crate::io::locking::FileLocking;
use crate::io::reader::SuperblockExtension;
use crate::io::writer::{FileSpaceConfig, SharedMessageConfig};
use crate::io::{Hdf5Reader, Hdf5Writer};
use crate::dataset::{DatasetAccess, DatasetBuilder, H5Dataset};
use crate::error::{Hdf5Error, Result};
use crate::format::messages::datatype::{DatatypeMessage, DatatypeNodeVersion};
use crate::format::messages::filter::FilterPipeline;
use crate::format::messages::shared::MessageStorage;
use crate::format::LibverBound;
use crate::group::H5Group;
use crate::types::H5Type;
// ---------------------------------------------------------------------------
// Thread-safety: choose between Rc<RefCell<>> and Arc<Mutex<>> based on
// the `threadsafe` feature flag.
// ---------------------------------------------------------------------------
#[cfg(not(feature = "threadsafe"))]
pub(crate) type SharedInner = std::rc::Rc<std::cell::RefCell<H5FileInner>>;
#[cfg(feature = "threadsafe")]
pub(crate) type SharedInner = std::sync::Arc<std::sync::RwLock<H5FileInner>>;
/// Helper to borrow/lock the inner state immutably.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn borrow_inner(inner: &SharedInner) -> std::cell::Ref<'_, H5FileInner> {
inner.borrow()
}
/// Helper to borrow/lock the inner state mutably.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn borrow_inner_mut(inner: &SharedInner) -> std::cell::RefMut<'_, H5FileInner> {
inner.borrow_mut()
}
/// [`borrow_inner_mut`] where failing to get the lock must not panic.
///
/// Only [`H5Dataset`]'s drop uses this: a `Drop` that panics while another
/// panic unwinds aborts the process, and the one thing it does with the lock
/// — releasing cross-file handles a closed virtual dataset was holding — is
/// re-run by the next handle drop or extent resolution.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn try_borrow_inner_mut(
inner: &SharedInner,
) -> Option<std::cell::RefMut<'_, H5FileInner>> {
inner.try_borrow_mut().ok()
}
/// Helper to clone a SharedInner.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn clone_inner(inner: &SharedInner) -> SharedInner {
std::rc::Rc::clone(inner)
}
/// Helper to wrap an H5FileInner in SharedInner.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn new_shared(inner: H5FileInner) -> SharedInner {
std::rc::Rc::new(std::cell::RefCell::new(inner))
}
/// Whether two handles share one file — the same inner state, not merely
/// equal state.
#[cfg(not(feature = "threadsafe"))]
pub(crate) fn same_inner(a: &SharedInner, b: &SharedInner) -> bool {
std::rc::Rc::ptr_eq(a, b)
}
/// Acquire a shared (read) lock on the inner state. The fine-grained writer
/// (atomic allocator, positioned handle, per-dataset `Slot` mutexes) is safe to
/// drive through `&H5FileInner`, so the non-extending chunk-write path takes
/// this read guard and lets writes to different datasets proceed concurrently.
#[cfg(feature = "threadsafe")]
pub(crate) fn borrow_inner(inner: &SharedInner) -> std::sync::RwLockReadGuard<'_, H5FileInner> {
inner.read().unwrap()
}
/// Acquire an exclusive (write) lock on the inner state. Required by paths that
/// mutate shared writer state directly — create, extend/`set_extent`, append,
/// metadata, finalize/close.
#[cfg(feature = "threadsafe")]
pub(crate) fn borrow_inner_mut(
inner: &SharedInner,
) -> std::sync::RwLockWriteGuard<'_, H5FileInner> {
inner.write().unwrap()
}
/// [`borrow_inner_mut`] where failing to get the lock must not panic; see the
/// single-threaded twin for why.
#[cfg(feature = "threadsafe")]
pub(crate) fn try_borrow_inner_mut(
inner: &SharedInner,
) -> Option<std::sync::RwLockWriteGuard<'_, H5FileInner>> {
inner.write().ok()
}
/// Whether two handles share one file — the same inner state, not merely
/// equal state.
#[cfg(feature = "threadsafe")]
pub(crate) fn same_inner(a: &SharedInner, b: &SharedInner) -> bool {
std::sync::Arc::ptr_eq(a, b)
}
#[cfg(feature = "threadsafe")]
pub(crate) fn clone_inner(inner: &SharedInner) -> SharedInner {
std::sync::Arc::clone(inner)
}
#[cfg(feature = "threadsafe")]
pub(crate) fn new_shared(inner: H5FileInner) -> SharedInner {
std::sync::Arc::new(std::sync::RwLock::new(inner))
}
/// The inner state of an HDF5 file, shared with datasets via reference counting.
///
/// By default, this uses `Rc<RefCell<>>` for zero-overhead single-threaded use.
/// Enable the `threadsafe` feature to use `Arc<Mutex<>>` instead, making
/// `H5File` `Send + Sync`.
pub(crate) enum H5FileInner {
// Boxed: `Hdf5Writer` and `Hdf5Reader` are both far larger than the
// zero-sized `Closed` sentinel, and inlining either here would size
// every `H5FileInner` to that variant's footprint regardless of which
// mode a given file is actually in.
Writer(Box<Hdf5Writer>),
Reader(Box<Hdf5Reader>),
/// Sentinel value used during `close()` to take ownership of the writer.
Closed,
}
/// An HDF5 file opened for reading or writing.
///
/// Datasets created from this file hold a shared reference to the underlying
/// I/O handle, so the file does not need to outlive its datasets (they share
/// ownership via reference counting).
pub struct H5File {
pub(crate) inner: SharedInner,
}
impl H5File {
/// Create a new HDF5 file at `path`. Truncates if the file already exists.
pub fn create<P: AsRef<Path>>(path: P) -> Result<Self> {
let writer = Hdf5Writer::create(path.as_ref())?;
Ok(Self {
inner: new_shared(H5FileInner::Writer(Box::new(writer))),
})
}
/// Open an existing HDF5 file for reading.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let reader = Hdf5Reader::open(path.as_ref())?;
Ok(Self {
inner: new_shared(H5FileInner::Reader(Box::new(reader))),
})
}
/// Open an existing HDF5 file for appending new datasets.
///
/// Existing datasets are preserved. New datasets can be added and will
/// be written after the current end of file. Existing chunked datasets
/// can be extended with `write_chunk` and `extend_dataset`.
///
/// ```no_run
/// use rust_hdf5::H5File;
/// let file = H5File::open_rw("existing.h5").unwrap();
/// let ds = file.new_dataset::<f64>().shape(&[100]).create("new_data").unwrap();
/// ds.write_raw(&vec![0.0f64; 100]).unwrap();
/// file.close().unwrap();
/// ```
pub fn open_rw<P: AsRef<Path>>(path: P) -> Result<Self> {
let writer = Hdf5Writer::open_append(path.as_ref())?;
Ok(Self {
inner: new_shared(H5FileInner::Writer(Box::new(writer))),
})
}
/// Start building open options for an HDF5 file.
///
/// Use this to control file-locking behavior explicitly:
///
/// ```no_run
/// use rust_hdf5::{H5File, FileLocking};
/// // Open with locking disabled (e.g. on NFS without lock support).
/// let file = H5File::options()
/// .locking(FileLocking::Disabled)
/// .open_rw("existing.h5")
/// .unwrap();
/// # let _ = file;
/// ```
pub fn options() -> H5FileOptions {
H5FileOptions::default()
}
/// Opt in to the latest file format for datasets created after this call —
/// the equivalent of libhdf5's `H5Pset_libver_bounds(low = H5F_LIBVER_V200)`.
///
/// With `latest` set, filtered chunked datasets get a version-5 data layout
/// message, whose chunk indexes store on-disk chunk sizes in fixed-width
/// (`sizeof_size`, i.e. 8-byte) fields instead of fields sized from the
/// uncompressed chunk size. That removes the overflow risk when a filter
/// *expands* a chunk, but the file is only readable by libhdf5 ≥ 2.0
/// (h5py bundling hdf5 1.14 rejects it with "bad version number").
///
/// It also sets the file's library-version low bound, and so its
/// superblock version: version 3, where a file this crate writes without
/// it is version 2 (or 3 anyway, once it holds a chunked dataset).
///
/// Off by default; the data layout of unfiltered and contiguous datasets
/// is unaffected. Independent of this setting, a chunk larger than 4 GiB
/// forces version 5 because version 4 cannot represent its size field,
/// matching libhdf5.
///
/// `false` is not "back to the default": it is
/// [`LibverBound::Earliest`], the opposite end of the same table, where
/// the data layout message is version 3 and chunked datasets created
/// after the call go on the version-1 B-tree. A file that has never been
/// told a bound is the one at the crate default.
///
/// Errors in read mode.
pub fn set_libver_latest(&self, latest: bool) -> Result<()> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.set_libver_latest(latest)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Set the file's low libver bound — `H5Pset_libver_bounds`'s `low`
/// argument, the oldest libhdf5 release the file must stay readable by.
///
/// Objects created after this call encode their messages at the versions
/// that bound calls for: a compound, enum or array datatype message moves
/// to version 3 at [`LibverBound::V18`] and version 4 at
/// [`LibverBound::V112`], the way `H5T_set_version` upgrades a datatype,
/// while an integer or string message stays at version 1 in every file.
/// [`LibverBound::V200`] additionally selects the version-5 data layout
/// for filtered chunked datasets, as [`Self::set_libver_latest`] does.
///
/// The bound also picks the chunk index, through the data layout message
/// version `H5O_layout_ver_bounds` gives it: below [`LibverBound::V110`]
/// that version is 3, which has no index-type field, so a chunked dataset
/// created after this call is indexed by the version-1 B-tree rather than
/// by the v1.10 index its shape would otherwise select. Datasets already
/// created keep the index they were made with, exactly as libhdf5 keeps
/// what a dataset's creation property list settled.
///
/// Naming a bound is not the same as leaving it unset: a file created
/// through [`H5File::create`] names none and uses the v1.10 indexes.
///
/// Errors in read mode.
pub fn set_libver_bound(&self, libver: LibverBound) -> Result<()> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.set_libver_bound(libver)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Record creation order for the links and the attributes of every
/// object created after this call — the equivalent of h5py's
/// `h5py.get_config().track_order = True`, i.e. `H5Pset_link_creation_order`
/// and `H5Pset_attr_creation_order` set to
/// `H5P_CRT_ORDER_TRACKED | H5P_CRT_ORDER_INDEXED` on the creation
/// property lists those objects are made with.
///
/// Creation-order tracking belongs to the object, so groups and datasets
/// made before this call keep the policy they were made under — the same
/// split h5py has between its global config and each object's property
/// list. The root group is created with the file; configure it with
/// [`H5FileOptions::track_order`], h5py's `File(..., track_order=True)`.
///
/// Off by default. Errors in read mode.
pub fn set_track_order(&self, track: bool) -> Result<()> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.set_track_order(track);
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Record the times of every object created after this call —
/// `H5Pset_obj_track_times` on the creation property lists those objects
/// are made with, h5py's `track_times=` argument to `create_dataset` and
/// `create_group`.
///
/// Off by default; see [`H5FileOptions::track_times`] for why that is
/// h5py's answer and not libhdf5's. Like creation-order tracking it
/// belongs to the object, so objects made before this call keep the policy
/// they were made under, and the root group takes its own from
/// [`H5FileOptions::track_times`].
///
/// Errors in read mode.
pub fn set_track_times(&self, track: bool) -> Result<()> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.set_track_times(track);
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Return a handle to the root group.
///
/// The root group can be used to create datasets and sub-groups.
pub fn root_group(&self) -> H5Group {
H5Group::new(clone_inner(&self.inner), "/".to_string())
}
/// Create a group in the root of the file.
///
/// ```no_run
/// use rust_hdf5::H5File;
/// let file = H5File::create("groups.h5").unwrap();
/// let grp = file.create_group("detector").unwrap();
/// ```
pub fn create_group(&self, name: &str) -> Result<H5Group> {
self.root_group().create_group(name)
}
/// Create a soft link in the root of the file.
///
/// See [`H5Group::create_soft_link`](crate::group::H5Group::create_soft_link).
///
/// ```no_run
/// use rust_hdf5::H5File;
/// let file = H5File::create("soft.h5").unwrap();
/// file.new_dataset::<i32>().shape([8]).create("orig").unwrap();
/// file.create_soft_link("alias", "/orig").unwrap();
/// ```
pub fn create_soft_link(&self, link_name: &str, target_path: &str) -> Result<()> {
self.root_group().create_soft_link(link_name, target_path)
}
/// Create an external link in the root of the file.
///
/// See [`H5Group::create_external_link`](crate::group::H5Group::create_external_link).
///
/// ```no_run
/// use rust_hdf5::H5File;
/// let file = H5File::create("master.h5").unwrap();
/// file.create_external_link("ext", "payload.h5", "/data").unwrap();
/// ```
pub fn create_external_link(
&self,
link_name: &str,
target_file: &str,
target_path: &str,
) -> Result<()> {
self.root_group()
.create_external_link(link_name, target_file, target_path)
}
/// Commit a datatype in the root of the file.
///
/// See [`H5Group::commit_datatype`](crate::group::H5Group::commit_datatype).
///
/// ```no_run
/// use rust_hdf5::H5File;
/// use rust_hdf5::format::messages::datatype::DatatypeMessage;
/// let file = H5File::create("committed.h5").unwrap();
/// file.commit_datatype("temperature", DatatypeMessage::f64_type()).unwrap();
/// ```
pub fn commit_datatype(
&self,
name: &str,
datatype: crate::format::messages::datatype::DatatypeMessage,
) -> Result<()> {
self.root_group().commit_datatype(name, datatype)
}
/// Start building a new dataset with the given element type.
///
/// This returns a fluent builder. Call `.shape(...)` to set dimensions and
/// `.create("name")` to finalize.
///
/// ```no_run
/// # use rust_hdf5::H5File;
/// let file = H5File::create("build.h5").unwrap();
/// let ds = file.new_dataset::<f64>().shape(&[3, 4]).create("matrix").unwrap();
/// ```
pub fn new_dataset<T: H5Type>(&self) -> DatasetBuilder<T> {
DatasetBuilder::new(clone_inner(&self.inner))
}
/// Add a string attribute to the file (root group).
///
/// The value is stored as a variable-length UTF-8 string (read back as a
/// Python `str` by h5py), not a fixed-length string.
pub fn set_attr_string(&self, name: &str, value: &str) -> Result<()> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.set_vlen_string_attribute(
crate::io::writer::AttrTarget::Root,
name,
value,
)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Add a numeric attribute to the file (root group).
pub fn set_attr_numeric<T: crate::types::H5Type>(&self, name: &str, value: &T) -> Result<()> {
use crate::format::messages::attribute::AttributeMessage;
let es = T::element_size();
let raw = unsafe { std::slice::from_raw_parts(value as *const T as *const u8, es) };
let attr = AttributeMessage::scalar_numeric(name, T::hdf5_type(), raw.to_vec());
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.add_root_attribute(attr)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Add a scalar attribute to the file (root group) whose datatype and raw
/// value the caller supplies.
///
/// The escape hatch for a type this crate has no Rust mapping for — a
/// fixed-length string of a size the value alone does not imply, say,
/// which is what `H5Tcopy(H5T_C_S1)` plus `H5Tset_size` produces.
/// [`DatasetBuilder::datatype`](crate::dataset::DatasetBuilder::datatype)
/// is the same hatch for a dataset; every typed setter here builds one of
/// these underneath.
///
/// `value` is the raw element image and must be exactly as long as the
/// datatype's element size.
///
/// ```no_run
/// # use rust_hdf5::{DatatypeMessage, H5File};
/// let file = H5File::create("notes.h5").unwrap();
/// let mut text = vec![b'x'; 256];
/// text[255] = 0;
/// file.set_attr_typed(
/// "note",
/// DatatypeMessage::FixedString { size: 256, padding: 0, charset: 0 },
/// text,
/// )
/// .unwrap();
/// ```
pub fn set_attr_typed(
&self,
name: &str,
datatype: DatatypeMessage,
value: Vec<u8>,
) -> Result<()> {
use crate::format::messages::attribute::AttributeMessage;
if value.len() as u64 != u64::from(datatype.element_size()) {
return Err(Hdf5Error::InvalidState(format!(
"attribute '{name}' was given {} bytes for a datatype whose element is {}",
value.len(),
datatype.element_size()
)));
}
let attr = AttributeMessage::scalar_numeric(name, datatype, value);
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.add_root_attribute(attr)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Add a numeric (or bool) **array** attribute to the file (root group).
///
/// The values are written as a 1-D HDF5 array attribute (simple dataspace
/// `[values.len()]`, on-disk type `T::hdf5_type()`), read back by h5py as a
/// numpy array — the array counterpart of [`set_attr_numeric`](Self::set_attr_numeric).
/// For a multi-dimensional shape use
/// [`set_attr_array_numeric_nd`](Self::set_attr_array_numeric_nd).
pub fn set_attr_array_numeric<T: crate::types::H5Type>(
&self,
name: &str,
values: &[T],
) -> Result<()> {
self.set_attr_array_numeric_nd(name, values, &[values.len()])
}
/// Add a numeric (or bool) **N-dimensional array** attribute to the file
/// (root group).
///
/// `shape` gives the dataspace dimensions; `values` is the row-major data
/// and its length must equal the product of `shape` (an empty `shape` is a
/// scalar, requiring exactly one value). Read back by h5py as a numpy array
/// of that shape. [`set_attr_array_numeric`](Self::set_attr_array_numeric)
/// is the 1-D convenience form.
pub fn set_attr_array_numeric_nd<T: crate::types::H5Type>(
&self,
name: &str,
values: &[T],
shape: &[usize],
) -> Result<()> {
use crate::format::messages::attribute::AttributeMessage;
let n: usize = shape.iter().product();
if values.len() != n {
return Err(Hdf5Error::InvalidState(format!(
"attribute '{name}' shape {shape:?} needs {n} elements, got {}",
values.len()
)));
}
let es = T::element_size();
// Safety: `T: H5Type` is a `Copy` POD numeric whose byte width is `es`.
let raw =
unsafe { std::slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * es) };
let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
let attr = AttributeMessage::array_numeric(name, T::hdf5_type(), &dims, raw.to_vec());
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.add_root_attribute(attr)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Add a variable-length UTF-8 string **array** attribute to the file (root
/// group), read back by h5py as a 1-D array of `str` — the array counterpart
/// of [`set_attr_string`](Self::set_attr_string). For a multi-dimensional
/// shape use [`set_attr_string_array_nd`](Self::set_attr_string_array_nd).
pub fn set_attr_string_array(&self, name: &str, values: &[&str]) -> Result<()> {
self.set_attr_string_array_nd(name, values, &[values.len()])
}
/// Add a variable-length UTF-8 string **N-dimensional array** attribute to
/// the file (root group).
///
/// `shape` gives the dataspace dimensions; `values` is the row-major data
/// and its length must equal the product of `shape` (an empty `shape` is a
/// scalar, requiring exactly one value). Read back by h5py as a numpy array
/// of Python `str` with that shape.
/// [`set_attr_string_array`](Self::set_attr_string_array) is the 1-D
/// convenience form.
pub fn set_attr_string_array_nd(
&self,
name: &str,
values: &[&str],
shape: &[usize],
) -> Result<()> {
let n: usize = shape.iter().product();
if values.len() != n {
return Err(Hdf5Error::InvalidState(format!(
"attribute '{name}' shape {shape:?} needs {n} elements, got {}",
values.len()
)));
}
let dims: Vec<u64> = shape.iter().map(|&d| d as u64).collect();
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => {
writer.set_vlen_string_array_attribute(
crate::io::writer::AttrTarget::Root,
name,
values,
&dims,
)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Add (or replace) an object-reference attribute on the file (root group)
/// — h5py's `f.attrs['entry'] = f['/data'].ref`.
///
/// `path` names a dataset or a group (`/` is the root group) and must
/// already exist. The attribute takes the scalar shape h5py gives a single
/// reference; [`set_attr_object_references`](Self::set_attr_object_references)
/// is the array form. What reaches the file is the target's object header
/// address, which is assigned when the file is finalized.
pub fn set_attr_object_reference(&self, name: &str, path: &str) -> Result<()> {
self.set_root_reference_attr(name, &[path], &[])
}
/// Add (or replace) a 1-D array of object references as a file-level
/// attribute — the array counterpart of
/// [`set_attr_object_reference`](Self::set_attr_object_reference).
pub fn set_attr_object_references(&self, name: &str, paths: &[&str]) -> Result<()> {
self.set_root_reference_attr(name, paths, &[paths.len() as u64])
}
fn set_root_reference_attr(&self, name: &str, paths: &[&str], dims: &[u64]) -> Result<()> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.set_object_reference_attribute(
crate::io::writer::AttrTarget::Root,
name,
paths,
dims,
)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot write in read mode".into())),
}
}
/// Return the names of file-level (root group) attributes.
pub fn attr_names(&self) -> Result<Vec<String>> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => Ok(reader.root_attr_names()?),
_ => Ok(vec![]),
}
}
/// Why the file-level attribute `name` cannot be read, or `None` when it
/// can be. See [`H5Dataset::attr_unreadable_reason`](crate::H5Dataset::attr_unreadable_reason).
pub fn attr_unreadable_reason(&self, name: &str) -> Result<Option<String>> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => {
Ok(reader.root_attr_unreadable_reason(name).map(str::to_string))
}
_ => Err(Hdf5Error::InvalidState("not in read mode".into())),
}
}
/// Why the file-level attribute *set* cannot be listed, or `None` when it
/// can be. See
/// [`H5Dataset::attrs_unreadable_reason`](crate::H5Dataset::attrs_unreadable_reason).
pub fn attrs_unreadable_reason(&self) -> Result<Option<String>> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => {
Ok(reader.root_attrs_unreadable_reason().map(str::to_string))
}
_ => Err(Hdf5Error::InvalidState("not in read mode".into())),
}
}
/// Read a file-level string attribute.
pub fn attr_string(&self, name: &str) -> Result<String> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => {
let attr = reader.root_attr(name)?.clone();
Ok(reader.attr_string_value(&attr)?)
}
_ => Err(Hdf5Error::InvalidState("not in read mode".into())),
}
}
/// The file-level metadata carried by the superblock extension: the
/// shared-message table, the v1 B-tree K values, the driver-info block and
/// the file-space strategy.
///
/// Every field is `None` for a file written without an extension, and for
/// a file this handle has open for writing.
pub fn superblock_extension(&self) -> SuperblockExtension {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => reader.superblock_extension().clone(),
_ => SuperblockExtension::default(),
}
}
/// How the object header at `path` stores each message it does not hold
/// privately, as `(message type, storage)` in header order.
///
/// This is the flags byte `h5debug` prints as `<S>` / `<SA>`, and the
/// pointer kind beneath a shared one — the only place a file says whether
/// a message body is the message or a reference to one held elsewhere.
/// Read mode only.
pub fn object_message_storage(&self, path: &str) -> Result<Vec<(u8, MessageStorage)>> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => Ok(reader.object_message_storage(path)?),
_ => Err(Hdf5Error::InvalidState(
"object_message_storage is only available in read mode".into(),
)),
}
}
/// The flags byte of every message the object header at `path` holds, as
/// `(message type, flags)` in header order, null and continuation
/// messages left out.
///
/// What `h5debug` prints as `<C>`, `<DS>`, `<S>` and the rest
/// (`H5O__debug_real`, H5Odbg.c:409-455): which messages the library may
/// cache as never-changing, which it refuses to move to the shared-message
/// heap, and which are already there. Read mode only.
pub fn object_message_flags(&self, path: &str) -> Result<Vec<(u8, u8)>> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => Ok(reader.object_message_flags(path)?),
_ => Err(Hdf5Error::InvalidState(
"object_message_flags is only available in read mode".into(),
)),
}
}
/// The class and version of every datatype message the object at `path`
/// carries, outermost first and then depth-first through compound
/// members, an enum's base and an array's base.
///
/// The version is the one part of a datatype message a decode drops, and
/// it is not free: `H5T_set_version` (H5T.c:6584-6591) picks it from the
/// file's low libver bound and the type's own construction, so it is what
/// says which generation of library can read the type back. A
/// stored-shared datatype is followed to the committed type it names, so
/// what comes back is the version that actually describes the object.
pub fn object_datatype_versions(&self, path: &str) -> Result<Vec<DatatypeNodeVersion>> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => Ok(reader.object_datatype_versions(path)?),
_ => Err(Hdf5Error::InvalidState(
"object_datatype_versions is only available in read mode".into(),
)),
}
}
/// Whether the object at `path` records its times —
/// `H5Pget_obj_track_times` on the creation property list it was made
/// with, read back from the header that answers it.
///
/// A version-2 header says so with `H5O_HDR_STORE_TIMES` and the four
/// times behind it; a version-1 dataset says so by carrying an
/// `H5O_MTIME_NEW` message. A version-1 group or committed datatype says
/// nothing either way — it has nowhere to record a time — so this is
/// `false` for one however it was created. Read mode only.
pub fn object_records_times(&self, path: &str) -> Result<bool> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => Ok(reader.object_records_times(path)?),
_ => Err(Hdf5Error::InvalidState(
"object_records_times is only available in read mode".into(),
)),
}
}
/// Bytes this file's on-disk free-space managers record as free —
/// libhdf5's `H5Fget_freespace`, and the number `h5stat -S` prints as
/// "Amount of tracked free space".
///
/// Zero for a file that persists no managers, which is every file created
/// without [`H5FileOptions::file_space`] asking for `persist`. Read mode
/// only: an open writer's freed blocks are not on disk yet, so the two
/// would be different questions with one name.
pub fn tracked_free_space(&self) -> Result<u64> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => Ok(reader.tracked_free_space()?),
_ => Err(Hdf5Error::InvalidState(
"tracked_free_space is only available in read mode".into(),
)),
}
}
/// Size in bytes of the userblock this file was written with — the
/// application-owned prefix the superblock follows (`H5Pget_userblock`).
/// Zero for a file without one, whichever mode the handle is in.
pub fn userblock_size(&self) -> u64 {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => reader.userblock_size(),
H5FileInner::Writer(writer) => writer.userblock_size(),
H5FileInner::Closed => 0,
}
}
/// This file's on-disk superblock format version (0-3) — libhdf5's
/// `H5F_get_info2`'s `super_version`, read from the file's own header
/// rather than derived from any bound a caller asked for.
pub fn superblock_version(&self) -> Result<u8> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => Ok(reader.superblock_version()),
_ => Err(Hdf5Error::InvalidState(
"superblock_version is only available in read mode".into(),
)),
}
}
/// The lowest [`LibverBound`] consistent with this file's on-disk
/// superblock version — a *view* reconstructed from
/// [`superblock_version`](Self::superblock_version), not the bound a
/// writer may have named: [`LibverBound::superblock_version`] maps four
/// bounds onto version 3, so a version-3 file reports [`LibverBound::V110`]
/// regardless of which of the four actually wrote it.
pub fn libver_bound(&self) -> Result<LibverBound> {
self.superblock_version()
.map(LibverBound::from_superblock_version)
}
/// Check if the file is in write/append mode.
pub fn is_writable(&self) -> bool {
let inner = borrow_inner(&self.inner);
matches!(&*inner, H5FileInner::Writer(_))
}
/// Create a variable-length string dataset and write data.
///
/// This is a convenience method for writing h5py-compatible vlen string
/// datasets using global heap storage. The datatype declares UTF-8, which
/// a Rust `&str` always is; [`write_vlen_strings_ascii`] writes the same
/// dataset under an ASCII declaration, the type h5py's
/// `string_dtype("ascii")` produces.
///
/// [`write_vlen_strings_ascii`]: Self::write_vlen_strings_ascii
pub fn write_vlen_strings(&self, name: &str, strings: &[&str]) -> Result<H5Dataset> {
self.write_vlen_strings_charset(name, strings, 1)
}
/// Create a variable-length **ASCII** string dataset and write data.
///
/// The ASCII twin of [`write_vlen_strings`](Self::write_vlen_strings),
/// named after the [`DatatypeMessage::vlen_string_ascii`] /
/// [`DatatypeMessage::vlen_string_utf8`] pair it selects between. A string
/// that is not 7-bit is rejected rather than stored under a datatype that
/// misdescribes it, so the file reads the same in every library that
/// trusts the declaration.
///
/// [`DatatypeMessage::vlen_string_ascii`]: crate::DatatypeMessage::vlen_string_ascii
/// [`DatatypeMessage::vlen_string_utf8`]: crate::DatatypeMessage::vlen_string_utf8
pub fn write_vlen_strings_ascii(&self, name: &str, strings: &[&str]) -> Result<H5Dataset> {
self.write_vlen_strings_charset(name, strings, 0)
}
/// The single owner of one-call vlen-string dataset creation: the two
/// public entry points differ only in the character set they declare.
fn write_vlen_strings_charset(
&self,
name: &str,
strings: &[&str],
charset: u8,
) -> Result<H5Dataset> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let idx = writer.create_vlen_string_dataset(name, strings, charset)?;
let parts = writer.dataset_handle_parts(idx, &DatasetAccess::default())?;
Ok(H5Dataset::new_writer(clone_inner(&self.inner), idx, parts))
}
H5FileInner::Reader(_) => {
Err(Hdf5Error::InvalidState("cannot write in read mode".into()))
}
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
}
}
/// Create a variable-length byte-array dataset and write data.
///
/// Each `&[u8]` becomes one element of variable length, stored as a vlen
/// sequence of `u8` in global heap storage. h5py reads it back as an array
/// of `uint8` arrays. Returns a writer-mode handle so attributes can be
/// attached, like [`write_vlen_strings`](Self::write_vlen_strings).
///
/// The `u8` case of [`write_vlen_numeric`](Self::write_vlen_numeric).
pub fn write_vlen_bytes(&self, name: &str, items: &[&[u8]]) -> Result<H5Dataset> {
self.write_vlen_numeric(name, items)
}
/// Create a variable-length numeric-sequence dataset and write data.
///
/// Each `&[T]` becomes one element of variable length, stored as a global
/// heap object under a vlen sequence datatype over `T`; h5py reads the
/// dataset back as an array of `T`-typed arrays, the type
/// `h5py.vlen_dtype(np.dtype(...))` produces. Sequences may have any
/// length, including zero. Returns a writer-mode handle so attributes can
/// be attached, like [`write_vlen_strings`](Self::write_vlen_strings).
///
/// ```no_run
/// # use rust_hdf5::H5File;
/// let file = H5File::create("v.h5").unwrap();
/// let a: &[i32] = &[1, 2, 3];
/// let b: &[i32] = &[];
/// file.write_vlen_numeric("data", &[a, b]).unwrap();
/// ```
pub fn write_vlen_numeric<T: H5Type>(&self, name: &str, items: &[&[T]]) -> Result<H5Dataset> {
let images = crate::dataset::vlen_sequence_images(items)?;
let images: Vec<&[u8]> = images.iter().map(|c| c.as_ref()).collect();
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let idx = writer.create_vlen_sequence_dataset(name, T::hdf5_type(), &images)?;
let parts = writer.dataset_handle_parts(idx, &DatasetAccess::default())?;
Ok(H5Dataset::new_writer(clone_inner(&self.inner), idx, parts))
}
H5FileInner::Reader(_) => {
Err(Hdf5Error::InvalidState("cannot write in read mode".into()))
}
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
}
}
/// Create a chunked, compressed variable-length string dataset.
///
/// Like `write_vlen_strings`, but stores the vlen references in chunked
/// layout with the given filter pipeline (e.g., `FilterPipeline::deflate(6)`
/// or `FilterPipeline::zstd(3)`). `chunk_size` is the number of strings
/// per chunk.
pub fn write_vlen_strings_compressed(
&self,
name: &str,
strings: &[&str],
chunk_size: usize,
pipeline: FilterPipeline,
) -> Result<H5Dataset> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let idx = writer
.create_vlen_string_dataset_compressed(name, strings, chunk_size, pipeline)?;
let parts = writer.dataset_handle_parts(idx, &DatasetAccess::default())?;
Ok(H5Dataset::new_writer(clone_inner(&self.inner), idx, parts))
}
H5FileInner::Reader(_) => {
Err(Hdf5Error::InvalidState("cannot write in read mode".into()))
}
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
}
}
/// Create an empty chunked vlen string dataset ready for incremental appends.
///
/// Use `append_vlen_strings` to add data. If `pipeline` is `Some`, chunks
/// are compressed (e.g., `Some(FilterPipeline::lz4())`).
pub fn create_appendable_vlen_dataset(
&self,
name: &str,
chunk_size: usize,
pipeline: Option<FilterPipeline>,
) -> Result<H5Dataset> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let idx =
writer.create_appendable_vlen_string_dataset(name, chunk_size, pipeline)?;
let parts = writer.dataset_handle_parts(idx, &DatasetAccess::default())?;
Ok(H5Dataset::new_writer(clone_inner(&self.inner), idx, parts))
}
H5FileInner::Reader(_) => {
Err(Hdf5Error::InvalidState("cannot write in read mode".into()))
}
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
}
}
/// Append variable-length strings to an existing chunked vlen string dataset.
pub fn append_vlen_strings(&self, name: &str, strings: &[&str]) -> Result<()> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let ds_index = writer.open_dataset_index(name)?;
writer.append_vlen_strings(ds_index, strings)?;
Ok(())
}
H5FileInner::Reader(_) => {
Err(Hdf5Error::InvalidState("cannot write in read mode".into()))
}
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".into())),
}
}
/// Delete a dataset name, with libhdf5's `H5Ldelete` semantics: a
/// path naming a hard link removes just that link, and if a hard link
/// still names the object whose tree name is deleted, the dataset
/// lives on under the link. Deleting the last name unlinks the
/// dataset on close and the file space it owned — data blocks,
/// chunk-index structures, and the global-heap objects of
/// variable-length values — is freed for reuse by later writes in this
/// session (the file itself does not shrink).
pub fn delete_dataset(&self, name: &str) -> Result<()> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.delete_dataset(name)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot delete in read mode".into())),
}
}
/// Delete a group and all its child datasets/sub-groups, freeing their
/// file space the way [`delete_dataset`](Self::delete_dataset) does.
///
/// Hard links reaching in from outside the deleted subtree keep their
/// targets alive: a dataset or group named by such a link survives
/// under the link's path (a group brings its whole subtree with it),
/// and a `name` that is itself a hard link's path removes just that
/// link.
pub fn delete_group(&self, name: &str) -> Result<()> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
writer.delete_group(name)?;
Ok(())
}
_ => Err(Hdf5Error::InvalidState("cannot delete in read mode".into())),
}
}
/// Open an existing dataset by name (read mode).
///
/// Uses libhdf5's default dataset-access properties; name others with
/// [`dataset_with`](Self::dataset_with).
pub fn dataset(&self, name: &str) -> Result<H5Dataset> {
self.dataset_with(name, DatasetAccess::default())
}
/// [`dataset`](Self::dataset) under named dataset-access properties —
/// `H5Dopen2` with a dapl instead of `H5P_DEFAULT`.
///
/// Three of the properties [`DatasetAccess`] carries decide how a
/// *virtual* dataset's extent is resolved and where its sources are
/// looked for; [`DatasetAccess::efile_prefix`] says where the raw data
/// files of a dataset stored through an external file list are. For a
/// dataset that is neither, this is exactly [`dataset`](Self::dataset).
///
/// First open wins: while any handle on that dataset is alive, a later
/// open of it joins that open and its own `access` is ignored, exactly
/// as `H5Dopen2` ignores the dapl of an open that finds the dataset
/// already in `H5FO_opened` (H5Dint.c:1496-1500, :1523-1528) — only the
/// open that creates the shared info reaches `H5D__virtual_init`, which
/// is where the view and the printf gap are read out of the dapl
/// (H5Dvirtual.c:2178-2188). Once every handle is dropped the next open
/// resolves afresh under its own properties.
///
/// libhdf5 keys that shared info on the *file* rather than on one
/// `H5Fopen`, so there a second `H5Fopen` of the same path still joins
/// the first open's view; here each [`H5File`] is its own reader and
/// binds independently.
///
/// # Errors
///
/// Beyond [`dataset`](Self::dataset)'s own errors, a
/// [`DatasetAccess::virtual_printf_gap`] of `u64::MAX` — libhdf5's
/// `HSIZE_UNDEF` — is refused, as `H5Pset_virtual_printf_gap` refuses it.
///
/// The one property a joining open may not disagree about is
/// [`DatasetAccess::efile_prefix`]: `H5D__open_name` refuses an open
/// whose expanded external file prefix differs from the open dataset's
/// (H5Dint.c:1533-1545), and so does this.
pub fn dataset_with(&self, name: &str, access: DatasetAccess) -> Result<H5Dataset> {
access.validate()?;
// Mutable: a name that crosses an external link opens the file that
// link names, and the reader caches that handle for the next one.
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => {
// The reader's open gate reports *why* a name cannot be
// opened — a dangling soft link and an unsupported object are
// both present in the listing, and neither is an absence.
let (open, info) = reader.open_dataset_with(name, &access)?;
let shape: Vec<usize> = info.dataspace.dims.iter().map(|&d| d as usize).collect();
let element_size = info.datatype.element_size() as usize;
Ok(H5Dataset::new_reader(
clone_inner(&self.inner),
name.to_string(),
shape,
element_size,
open,
))
}
H5FileInner::Writer(_) => Err(Hdf5Error::InvalidState(
"cannot open a dataset by name in write mode; use new_dataset() instead"
.to_string(),
)),
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".to_string())),
}
}
/// Reopen an existing dataset by name in write mode.
///
/// [`dataset`](Self::dataset) only works in read mode; in write mode a
/// dataset is normally created via [`new_dataset`](Self::new_dataset).
/// This returns a write-mode handle to a dataset created earlier in the
/// same session, so you can attach attributes or append chunks to it
/// without keeping the original handle around — e.g. to flush cached
/// first/last values onto a dataset at file-close time.
///
/// # Errors
///
/// Returns [`Hdf5Error::NotFound`] if no live dataset with that name
/// exists, and an error in read mode (use [`dataset`](Self::dataset)).
pub fn dataset_writer(&self, name: &str) -> Result<H5Dataset> {
self.dataset_writer_with(name, DatasetAccess::default())
}
/// [`dataset_writer`](Self::dataset_writer) under named dataset-access
/// properties — `H5Dopen2` with a dapl instead of `H5P_DEFAULT`, in write
/// mode.
///
/// The one property that reaches a write is
/// [`DatasetAccess::efile_prefix`]: `H5D__efl_write` joins each slot name
/// of an external file list against `dset->shared->extfile_prefix`
/// (H5Defl.c:429-431), which the open that settled the dataset's shared
/// info built from its dapl. So this is how a dataset reopened from an
/// existing file is told where its raw data files are before being
/// written to; the other properties decide a *virtual* dataset's extent,
/// which this writer never resolves.
///
/// First open wins, and a joining open may not disagree about that
/// prefix — see
/// [`H5File::dataset_with`](Self::dataset_with) for the same rule on the
/// read side. A dataset this session created settled its prefix from
/// [`DatasetBuilder::efile_prefix`](crate::dataset::DatasetBuilder::efile_prefix),
/// so while its handle is alive this call must name the same one;
/// once every handle is dropped the next call settles it afresh.
///
/// # Errors
///
/// [`dataset_writer`](Self::dataset_writer)'s errors, plus a refusal when
/// `access` names an external file prefix that disagrees with the one an
/// open of this dataset is still holding.
pub fn dataset_writer_with(&self, name: &str, access: DatasetAccess) -> Result<H5Dataset> {
access.validate()?;
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Writer(writer) => {
let index = writer.open_dataset_index(name)?;
let parts = writer.dataset_handle_parts(index, &access)?;
Ok(H5Dataset::new_writer(
clone_inner(&self.inner),
index,
parts,
))
}
H5FileInner::Reader(_) => Err(Hdf5Error::InvalidState(
"cannot open a dataset_writer in read mode; use dataset() instead".to_string(),
)),
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".to_string())),
}
}
/// Return the names of all datasets in the root group.
///
/// Works in both read and write mode: in write mode, returns the names of
/// datasets created so far; in read mode, returns the names discovered
/// during file open.
pub fn dataset_names(&self) -> Vec<String> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => reader
.dataset_names()
.iter()
.map(|s| s.to_string())
.collect(),
H5FileInner::Writer(writer) => writer
.dataset_names()
.iter()
.map(|s| s.to_string())
.collect(),
H5FileInner::Closed => Vec::new(),
}
}
/// The paths of every committed (named) datatype in this file.
///
/// A committed datatype is an object in its own right, in neither
/// [`dataset_names`](Self::dataset_names) nor the group listing. In write
/// mode these are the types [`commit_datatype`](Self::commit_datatype)
/// committed this session.
pub fn named_datatype_names(&self) -> Vec<String> {
let inner = borrow_inner(&self.inner);
match &*inner {
H5FileInner::Reader(reader) => reader
.named_datatype_names()
.iter()
.map(|s| s.to_string())
.collect(),
H5FileInner::Writer(writer) => writer.committed_datatype_names(),
H5FileInner::Closed => Vec::new(),
}
}
/// Open a committed (named) datatype by path (read mode).
///
/// The handle opens whenever the object is there; a type this crate
/// cannot decode reports why from
/// [`H5NamedDatatype::datatype`](crate::named_datatype::H5NamedDatatype::datatype),
/// so its attributes stay reachable.
///
/// # Errors
///
/// [`Hdf5Error::NotFound`] when no committed datatype is at that path.
pub fn named_datatype(&self, path: &str) -> Result<crate::H5NamedDatatype> {
// Mutable: a path that crosses an external link opens the file that
// link names, and the reader caches that handle for the next one.
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Reader(reader) => {
reader.named_datatype_info(path)?;
drop(inner);
Ok(crate::H5NamedDatatype::new_reader(
clone_inner(&self.inner),
path.to_string(),
))
}
H5FileInner::Writer(_) => Err(Hdf5Error::InvalidState(
"committed datatypes are readable only in read mode".to_string(),
)),
H5FileInner::Closed => Err(Hdf5Error::InvalidState("file is closed".to_string())),
}
}
/// Explicitly close the file. For a writer, this finalizes the file
/// (writes superblock, headers, etc.). For a reader, this is a no-op.
///
/// The file is also auto-finalized on drop, but calling `close()` lets
/// you handle errors.
pub fn close(self) -> Result<()> {
let old = {
let mut inner = borrow_inner_mut(&self.inner);
std::mem::replace(&mut *inner, H5FileInner::Closed)
};
match old {
H5FileInner::Writer(writer) => {
writer.close()?;
Ok(())
}
H5FileInner::Reader(_) => Ok(()),
H5FileInner::Closed => Ok(()),
}
}
/// Close the file without a final `fsync` (write mode only).
///
/// Like [`close`](Self::close), this finalizes the file — object headers
/// and superblock are written, so on return it is a complete, valid HDF5
/// file readable by any process — but the trailing `sync_all` (fsync) is
/// skipped. The bytes are handed to the OS but are not guaranteed durable
/// against power loss or an OS crash until the OS flushes its page cache.
///
/// This trades durability for speed (the fsync typically dominates close
/// latency); use it for bulk output that can be regenerated. Prefer
/// [`close`](Self::close) when durability matters. Dropping the file
/// without calling either finalizes durably.
///
/// For a reader or an already-closed file this is a no-op, matching
/// [`close`](Self::close).
pub fn close_no_sync(self) -> Result<()> {
let old = {
let mut inner = borrow_inner_mut(&self.inner);
std::mem::replace(&mut *inner, H5FileInner::Closed)
};
match old {
H5FileInner::Writer(writer) => {
writer.close_no_sync()?;
Ok(())
}
H5FileInner::Reader(_) => Ok(()),
H5FileInner::Closed => Ok(()),
}
}
/// Hand every byte written so far to the operating system. Only
/// meaningful in write mode.
///
/// This empties the write accumulator, so another process reading the file
/// afterwards sees everything written up to this point. It does not
/// finalize the file — object headers and the superblock are still
/// [`close`](Self::close)'s work — and it does not `fsync`.
pub fn flush(&self) -> Result<()> {
let mut inner = borrow_inner_mut(&self.inner);
match &mut *inner {
H5FileInner::Writer(writer) => Ok(writer.handle().flush()?),
H5FileInner::Reader(_) => Ok(()),
H5FileInner::Closed => Ok(()),
}
}
}
/// Builder controlling how an [`H5File`] is opened.
///
/// The default policy follows the HDF5 C library: an exclusive lock is
/// acquired for write-mode opens and a shared lock for read-mode opens,
/// honoring the `HDF5_USE_FILE_LOCKING` environment variable. Calling
/// [`Self::locking`] overrides the env-var value.
#[derive(Debug, Default, Clone)]
pub struct H5FileOptions {
locking: Option<FileLocking>,
track_order: bool,
track_times: bool,
libver: Option<LibverBound>,
userblock: u64,
shared_messages: SharedMessageConfig,
file_space: Option<FileSpaceConfig>,
file_space_page_size: Option<u64>,
elink_prefix: Option<String>,
}
impl H5FileOptions {
/// Construct a fresh options builder with default settings.
pub fn new() -> Self {
Self::default()
}
/// Override the locking policy. Bypasses the `HDF5_USE_FILE_LOCKING`
/// environment variable for the resulting open call.
pub fn locking(mut self, policy: FileLocking) -> Self {
self.locking = Some(policy);
self
}
/// Disable OS-level file locking entirely (equivalent to
/// `HDF5_USE_FILE_LOCKING=FALSE`). Under the `mmap` feature such an open
/// reads through the descriptor rather than a map, which is taken only
/// under the shared lock, so a zero-copy view of it is refused.
pub fn no_locking(self) -> Self {
self.locking(FileLocking::Disabled)
}
/// Try to acquire the lock but do not fail if the filesystem rejects it
/// (equivalent to `HDF5_USE_FILE_LOCKING=BEST_EFFORT`).
pub fn best_effort_locking(self) -> Self {
self.locking(FileLocking::BestEffort)
}
/// `H5Pset_elink_prefix` (H5Plapl.c:923): a directory the *target file*
/// of an external link is looked for under, after `HDF5_EXT_PREFIX` and
/// before the linking file's own directory — step 3 of
/// `H5F_prefix_open_file`'s order (H5Fint.c:938-950).
///
/// Unlike [`DatasetAccess::virtual_prefix`](crate::DatasetAccess), this
/// one is *not* shadowed by its environment variable and gets no
/// `${ORIGIN}` expansion: `H5L__extern_traverse` peeks the property
/// verbatim and hands it straight to the search (H5Lexternal.c:210-215),
/// with no `H5D__build_file_prefix` step in between. Measured against
/// libhdf5 1.14.6 and 2.0.0: with `HDF5_EXT_PREFIX` naming a directory
/// that has no target, this property still resolves it, while the same
/// arrangement for a virtual source does not; and a `${ORIGIN}` written
/// here stays a literal directory name.
///
/// # Where this lives, and why not on the call
///
/// libhdf5 keeps it in a *link access* property list, an argument every
/// `H5*_by_name` call carries. Here it is a property of the open,
/// because that is the narrowest scope this crate can honour: a reader
/// resolves each external link's file name once and then holds that
/// answer for its own life, so a prefix passed per call could not change
/// a name another call had already resolved. Making it file-scoped also
/// keeps it with the one other cross-file policy libhdf5 takes from a
/// property list and applies to every file a path touches — the locking
/// mode — and, like that one, it propagates down a chain of links, which
/// is what a lapl does upstream (measured: a two-hop chain resolves its
/// second hop under the prefix given at the first).
///
/// Read-side only: nothing the writer does traverses an external link.
pub fn elink_prefix(mut self, prefix: impl Into<String>) -> Self {
self.elink_prefix = Some(prefix.into());
self
}
/// Create the file's root group with creation-order tracking, and make
/// that the policy for objects created in it — h5py's
/// `File(path, "w", track_order=True)`.
///
/// Only [`create`](Self::create) reads this; opening an existing file
/// takes the policy from the root group already on disk. Change it for
/// later objects with [`H5File::set_track_order`].
pub fn track_order(mut self, track: bool) -> Self {
self.track_order = track;
self
}
/// Create the file's root group recording its times, and make that the
/// policy for objects created in it — `H5Pset_obj_track_times`, h5py's
/// `File(path, "w", track_times=True)`.
///
/// An object recording times keeps the ones its header version can hold:
/// four in a version-2 header's prefix, one modification time in a
/// version-1 dataset's `H5O_MTIME_NEW` message, and none at all in a
/// version-1 group or committed datatype, which have nowhere to put one.
///
/// Off unless this says otherwise — h5py's default, not libhdf5's. h5py's
/// high-level API passes `track_times=False` for every object it makes
/// (`_hl/files.py:189`, `_hl/dataset.py:39`, `_hl/group.py:42`), while a
/// bare creation property list leaves it on (`H5O_CRT_OHDR_FLAGS_DEF` is
/// `H5O_HDR_STORE_TIMES`, H5Opkg.h:74), which is what `h5py.h5d.create`
/// and libhdf5's own C API get.
///
/// Only [`create`](Self::create) reads this; the root group of an existing
/// file was made under whatever created it. Change it for later objects
/// with [`H5File::set_track_times`].
pub fn track_times(mut self, track: bool) -> Self {
self.track_times = track;
self
}
/// Create the file under a library-version low bound — h5py's
/// `File(path, "w", libver=("v108", "v108"))`, libhdf5's
/// `H5Pset_libver_bounds` `low` argument.
///
/// The bound decides the superblock version the file is written with
/// ([`LibverBound::superblock_version`]) as well as the message versions
/// of the objects created in it, so unlike
/// [`H5File::set_libver_bound`] — which only reaches objects created
/// after the call — it applies to the file itself.
///
/// [`LibverBound::Earliest`] asks for the whole classic generation, the
/// file libhdf5 writes at `H5F_LIBVER_EARLIEST`: a version-0 superblock,
/// a symbol-table root group, version-1 object headers, symbol-table
/// subgroups and the version-1 B-tree chunk index. Such a file is
/// readable by libhdf5 1.6, and correspondingly gives up everything
/// newer — SWMR ([`crate::swmr`]) and virtual datasets are refused in
/// it, and a chunk larger than 4 GiB does not fit its index key.
///
/// [`LibverBound::V18`] asks for the file libhdf5 writes at
/// `H5F_LIBVER_V18`: a version-2 superblock over link-message groups and
/// version-2 object headers, but still the version-3 data layout message
/// and so still the version-1 B-tree chunk index — `H5O_layout_ver_bounds`
/// does not reach version 4 until `V110`, and the v1.10 indexes live in
/// nothing older. SWMR is refused in such a file: its status flags need a
/// version-3 superblock, which this bound's row does not reach.
///
/// Not calling this at all is *not* the same as asking for `Earliest`,
/// nor for `V18`: the default file has the version-2 superblock and
/// link-message groups of the v1.8 bound over the v1.10 chunk indexes,
/// which no single bound describes.
///
/// Only [`create`](Self::create) reads this; an existing file keeps the
/// superblock it already has.
///
/// ```no_run
/// use rust_hdf5::{H5File, LibverBound};
/// let file = H5File::options()
/// .libver(LibverBound::V110)
/// .create("v110.h5")
/// .unwrap();
/// # let _ = file;
/// ```
pub fn libver(mut self, libver: LibverBound) -> Self {
self.libver = Some(libver);
self
}
/// Reserve `size` bytes in front of the superblock for the application's
/// own use — h5py's `File(path, "w", userblock_size=512)`, libhdf5's
/// `H5Pset_userblock`.
///
/// The block is the file's first `size` bytes and belongs to whoever
/// writes it: an executable header, a checksum, a provenance record. HDF5
/// itself only skips it — the superblock and every address in the file are
/// based at `size`, and a reader finds the superblock by looking at offset
/// 0 and then at [`MIN_USERBLOCK`](crate::MIN_USERBLOCK) doubled
/// repeatedly, which is why the size must be zero (no block) or a power of
/// two of at least that many bytes. [`create`](Self::create) reports any
/// other size as an error; it is not rounded up.
///
/// This crate writes the block zero-filled and never reads it back, so
/// filling it is a plain write to the front of the file after
/// [`H5File::close`].
///
/// ```no_run
/// use rust_hdf5::H5File;
/// let file = H5File::options().userblock(512).create("prefixed.h5").unwrap();
/// assert_eq!(file.userblock_size(), 512);
/// ```
pub fn userblock(mut self, size: u64) -> Self {
self.userblock = size;
self
}
/// Create the file with shared object header messages — libhdf5's
/// `H5Pset_shared_mesg_nindexes` + `H5Pset_shared_mesg_index` +
/// `H5Pset_shared_mesg_phase_change`, which h5py exposes no binding for.
///
/// A message class covered by an index is written once into a
/// shared-message fractal heap, and every object header that would have
/// held that exact body holds a pointer to it instead. `indexes` gives
/// one `(message types, minimum message size)` pair per index, where the
/// type mask is built from
/// [`type_flag`](crate::format::sohm::type_flag); `list_max` and
/// `btree_min` are the file-wide counts at which an index changes between
/// list and v2 B-tree form.
///
/// Only [`create`](Self::create) reads this, and it refuses a
/// configuration libhdf5 would refuse: more than eight indexes, an index
/// covering no type, or thresholds that overlap.
///
/// ```no_run
/// use rust_hdf5::{H5File, format::sohm::type_flag};
/// use rust_hdf5::format::messages::{MSG_ATTRIBUTE, MSG_DATASPACE, MSG_DATATYPE};
///
/// let types = type_flag(MSG_DATATYPE).unwrap()
/// | type_flag(MSG_DATASPACE).unwrap()
/// | type_flag(MSG_ATTRIBUTE).unwrap();
/// let file = H5File::options()
/// .shared_messages(&[(types, 0)], 50, 40)
/// .create("sohm.h5")
/// .unwrap();
/// # let _ = file;
/// ```
pub fn shared_messages(
mut self,
indexes: &[(u16, u32)],
list_max: u16,
btree_min: u16,
) -> Self {
self.shared_messages = SharedMessageConfig::new(indexes, list_max, btree_min);
self
}
/// Create the file under a file-space handling strategy — libhdf5's
/// `H5Pset_file_space_strategy`, h5py's `File(..., fs_strategy=...,
/// fs_persist=..., fs_threshold=...)`.
///
/// `strategy` picks how released space is reused:
/// [`FileSpaceStrategy::FsmAggr`] keeps free-space managers and the
/// metadata/raw-data aggregators (the library default),
/// [`FileSpaceStrategy::Aggr`] the aggregators alone, and
/// [`FileSpaceStrategy::None`] neither, so every allocation comes from the
/// end of the file. [`FileSpaceStrategy::Page`] allocates on file-space
/// page boundaries instead, packing everything smaller than a page into
/// pages of its own kind; [`file_space_page_size`](Self::file_space_page_size)
/// sets how big those pages are.
///
/// `persist` writes the free-space managers into the file on close, so a
/// later session — this crate or libhdf5 — finds the space this one
/// released instead of appending past it. `threshold` is the smallest
/// section a manager records; anything smaller is space the file leaks
/// rather than tracks. Both are ignored for the two strategies that have
/// no managers, exactly as `H5P__set_file_space_strategy` ignores them.
///
/// Only [`create`](Self::create) reads this. A file that already exists
/// declares its own strategy in its superblock extension, and this crate
/// honours what it finds there.
///
/// ```no_run
/// use rust_hdf5::{FileSpaceStrategy, H5File};
/// let file = H5File::options()
/// .file_space(FileSpaceStrategy::FsmAggr, true, 1)
/// .create("persisting.h5")
/// .unwrap();
/// # let _ = file;
/// ```
pub fn file_space(
mut self,
strategy: FileSpaceStrategy,
persist: bool,
threshold: u64,
) -> Self {
self.file_space = Some(FileSpaceConfig::new(strategy, persist, threshold));
self
}
/// `H5Pset_file_space_page_size`, h5py's `File(..., fs_page_size=...)`.
///
/// The file-space page is the unit [`FileSpaceStrategy::Page`] allocates
/// in: a request smaller than one page is packed into a page holding only
/// that kind of data, and a larger one is page-aligned. `size` is between
/// 512 (`H5F_FILE_SPACE_PAGE_SIZE_MIN`) and 1 GiB — no power of two
/// required — and anything outside that is refused by
/// [`create`](Self::create), as `H5Pset_file_space_page_size` refuses it.
///
/// Setting it is enough on its own to give the file a file-space info
/// message, because the page size is one of the four properties
/// `H5F__super_init` compares against the library defaults. Under any
/// other strategy that is all it does: the file records the size and
/// allocates without it.
///
/// Only [`create`](Self::create) reads this. A reopened file keeps the
/// page size its own message carries.
///
/// ```no_run
/// use rust_hdf5::{FileSpaceStrategy, H5File};
/// let file = H5File::options()
/// .file_space(FileSpaceStrategy::Page, true, 1)
/// .file_space_page_size(8192)
/// .create("paged.h5")
/// .unwrap();
/// # let _ = file;
/// ```
pub fn file_space_page_size(mut self, size: u64) -> Self {
self.file_space_page_size = Some(size);
self
}
/// The one [`FileSpaceConfig`] the two file-space builders describe
/// between them.
///
/// They are separate properties of one property list —
/// `H5Pset_file_space_strategy` and `H5Pset_file_space_page_size` write
/// different fcpl entries and neither reads the other — so each is
/// recorded by whether it was called, and joining them here is what keeps
/// either call order meaning the same thing.
fn resolved_file_space(&self) -> FileSpaceConfig {
let config = self.file_space.unwrap_or_default();
match self.file_space_page_size {
Some(size) => config.with_page_size(size),
None => config,
}
}
fn resolved_locking(&self) -> FileLocking {
match self.locking {
Some(p) => p,
None => FileLocking::from_env_or(FileLocking::default()),
}
}
/// Refuse an `open`/`open_rw` call that set an option only [`create`]
/// reads — the fcpl/fapl split each of those setters' docs already
/// describe: `track_order`, `track_times`, `libver`, `userblock` and
/// `shared_messages` all bake into a file at creation, so an existing
/// file's root group,
/// superblock and shared-message table are already fixed by whatever
/// created it. Silently ignoring the option, the previous behavior,
/// hides a builder call that has no effect at all; one gate here checks
/// every such field instead of a scattered check per opener.
///
/// The `libver` arm tests `is_some`, not inequality against a default
/// value: [`LibverBound::default`] is `Earliest`, so a gate written as
/// `libver != default()` would let the one bound that asks for a whole
/// classic file through unrefused. Whether the builder was *called* is
/// the question, and `Option` is what records it.
///
/// [`create`]: Self::create
fn refuse_create_only_options(&self) -> Result<()> {
let mut offending = Vec::new();
if self.track_order {
offending.push("track_order");
}
if self.track_times {
offending.push("track_times");
}
if self.libver.is_some() {
offending.push("libver");
}
if self.userblock != 0 {
offending.push("userblock");
}
if self.shared_messages != SharedMessageConfig::default() {
offending.push("shared_messages");
}
if self.file_space.is_some() {
offending.push("file_space");
}
if self.file_space_page_size.is_some() {
offending.push("file_space_page_size");
}
if offending.is_empty() {
Ok(())
} else {
Err(Hdf5Error::InvalidState(format!(
"these options only take effect when creating a file, not when \
opening an existing one: {}",
offending.join(", ")
)))
}
}
/// The mirror of [`refuse_create_only_options`](Self::refuse_create_only_options)
/// for the options only a read-mode open can honour, refused by the two
/// openers that produce a writer.
///
/// [`elink_prefix`](Self::elink_prefix) is one because nothing on the
/// write side traverses an external link, so a file opened for writing
/// would silently never use it.
fn refuse_read_only_options(&self) -> Result<()> {
if self.elink_prefix.is_none() {
return Ok(());
}
Err(Hdf5Error::InvalidState(
"these options only take effect when opening a file for reading: \
elink_prefix"
.to_string(),
))
}
/// Create a new HDF5 file at `path` with the configured options.
pub fn create<P: AsRef<Path>>(self, path: P) -> Result<H5File> {
self.refuse_read_only_options()?;
let writer = Hdf5Writer::create_with_options(
path.as_ref(),
crate::io::writer::FileCreateOptions {
locking: self.resolved_locking(),
track_order: self.track_order,
track_times: self.track_times,
libver: self.libver,
userblock: self.userblock,
shared_messages: self.shared_messages,
file_space: self.resolved_file_space(),
},
)?;
Ok(H5File {
inner: new_shared(H5FileInner::Writer(Box::new(writer))),
})
}
/// Open an existing HDF5 file for reading with the configured options.
pub fn open<P: AsRef<Path>>(self, path: P) -> Result<H5File> {
self.refuse_create_only_options()?;
let mut reader = Hdf5Reader::open_with_locking(path.as_ref(), self.resolved_locking())?;
reader.set_elink_prefix(self.elink_prefix);
Ok(H5File {
inner: new_shared(H5FileInner::Reader(Box::new(reader))),
})
}
/// Open an existing HDF5 file for read/write with the configured options.
pub fn open_rw<P: AsRef<Path>>(self, path: P) -> Result<H5File> {
self.refuse_create_only_options()?;
self.refuse_read_only_options()?;
let writer = Hdf5Writer::open_append_with_locking(path.as_ref(), self.resolved_locking())?;
Ok(H5File {
inner: new_shared(H5FileInner::Writer(Box::new(writer))),
})
}
}
#[cfg(test)]
fn unique_test_path(name: &str) -> std::path::PathBuf {
// PID + atomic counter so each test invocation uses a distinct path,
// preventing collisions across concurrent cargo runs and any
// flock/LockFileEx race where a previous close()'d file's lock
// remains briefly visible when reopening the same path.
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
std::env::temp_dir().join(format!(
"rust_hdf5_test_{}_{}_{}.h5",
name,
std::process::id(),
n
))
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn temp_path(name: &str) -> PathBuf {
super::unique_test_path(name)
}
#[test]
fn create_and_close_empty() {
let path = temp_path("create_empty");
let file = H5File::create(&path).unwrap();
file.close().unwrap();
// Should be readable
let file = H5File::open(&path).unwrap();
file.close().unwrap();
std::fs::remove_file(&path).ok();
}
#[test]
fn create_and_drop_empty() {
let path = temp_path("drop_empty");
{
let _file = H5File::create(&path).unwrap();
// drop auto-finalizes
}
// Verify the file is valid by opening it
let file = H5File::open(&path).unwrap();
file.close().unwrap();
std::fs::remove_file(&path).ok();
}
#[test]
fn dataset_not_found() {
let path = temp_path("ds_not_found");
{
let _file = H5File::create(&path).unwrap();
}
let file = H5File::open(&path).unwrap();
let result = file.dataset("nonexistent");
assert!(result.is_err());
std::fs::remove_file(&path).ok();
}
#[test]
fn write_and_read_roundtrip() {
let path = temp_path("write_read_rt");
// Write
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<u8>()
.shape([4, 4])
.create("data")
.unwrap();
ds.write_raw(&[0u8; 16]).unwrap();
file.close().unwrap();
}
// Read
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.shape(), vec![4, 4]);
let data = ds.read_raw::<u8>().unwrap();
assert_eq!(data.len(), 16);
assert!(data.iter().all(|&b| b == 0));
file.close().unwrap();
}
std::fs::remove_file(&path).ok();
}
#[test]
fn close_no_sync_produces_valid_readable_file() {
let path = temp_path("close_no_sync_rt");
let payload: Vec<u8> = (0u8..16).collect();
// Write and finalize WITHOUT the trailing fsync.
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<u8>()
.shape([4, 4])
.create("data")
.unwrap();
ds.write_raw(&payload).unwrap();
// The only difference from `write_and_read_roundtrip`: no fsync.
// The file must still be a complete, valid, readable HDF5 file.
file.close_no_sync().unwrap();
}
// Reopen and verify the full content survived (same-machine reader sees
// the OS page cache regardless of whether fsync ran).
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.shape(), vec![4, 4]);
let data = ds.read_raw::<u8>().unwrap();
assert_eq!(data, payload);
file.close().unwrap();
}
std::fs::remove_file(&path).ok();
}
#[test]
fn create_over_existing_file_truncates() {
// The create path skips the ftruncate on a brand-new empty file (it
// arms ext4's auto_da_alloc and turns close(2) into an implicit
// writeback, defeating close_no_sync). This pins the other side of
// that guard: creating over an existing non-empty file must still
// truncate it, so no stale content survives.
let path = temp_path("create_truncates");
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<u8>()
.shape([4, 4])
.create("old_data")
.unwrap();
ds.write_raw(&[7u8; 16]).unwrap();
file.close().unwrap();
}
assert!(std::fs::metadata(&path).unwrap().len() > 0);
// Re-create over the non-empty file, write nothing.
{
let file = H5File::create(&path).unwrap();
file.close().unwrap();
}
// The old dataset must be gone.
let file = H5File::open(&path).unwrap();
assert!(file.dataset("old_data").is_err());
file.close().unwrap();
std::fs::remove_file(&path).ok();
}
#[test]
fn close_no_sync_chunked_dataset_valid() {
// Exercises flush_dataset_synced(sync=false): a chunked (EA-indexed)
// dataset closed with close_no_sync must skip the per-dataset
// sync_data yet still write valid index structures, so the reopened
// file reconstructs every frame.
let path = temp_path("close_no_sync_chunked");
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([0usize, 3])
.chunk(&[1, 3])
.max_shape(&[None, Some(3)])
.create("data")
.unwrap();
// 10 frames exceeds idx_blk_elmts=4, so data blocks are exercised.
for frame in 0..10u64 {
let vals: Vec<i32> = (0..3).map(|i| (frame * 3 + i) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[10, 3]).unwrap();
file.close_no_sync().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.shape(), vec![10, 3]);
let data = ds.read_raw::<i32>().unwrap();
let expected: Vec<i32> = (0..30).collect();
assert_eq!(data, expected);
file.close().unwrap();
}
std::fs::remove_file(&path).ok();
}
#[test]
fn write_and_read_f64() {
let path = temp_path("write_read_f64");
let values: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
// Write
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<f64>()
.shape([2, 3])
.create("matrix")
.unwrap();
ds.write_raw(&values).unwrap();
file.close().unwrap();
}
// Read
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("matrix").unwrap();
assert_eq!(ds.shape(), vec![2, 3]);
let readback = ds.read_raw::<f64>().unwrap();
assert_eq!(readback, values);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn multiple_datasets() {
let path = temp_path("multi_ds");
{
let file = H5File::create(&path).unwrap();
let ds1 = file.new_dataset::<i32>().shape([3]).create("ints").unwrap();
ds1.write_raw(&[10i32, 20, 30]).unwrap();
let ds2 = file
.new_dataset::<f32>()
.shape([2, 2])
.create("floats")
.unwrap();
ds2.write_raw(&[1.0f32, 2.0, 3.0, 4.0]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds_ints = file.dataset("ints").unwrap();
assert_eq!(ds_ints.shape(), vec![3]);
let ints = ds_ints.read_raw::<i32>().unwrap();
assert_eq!(ints, vec![10, 20, 30]);
let ds_floats = file.dataset("floats").unwrap();
assert_eq!(ds_floats.shape(), vec![2, 2]);
let floats = ds_floats.read_raw::<f32>().unwrap();
assert_eq!(floats, vec![1.0f32, 2.0, 3.0, 4.0]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn close_is_idempotent() {
let path = temp_path("close_idemp");
let file = H5File::create(&path).unwrap();
file.close().unwrap();
// File is consumed by close(), so no double-close possible at the type level.
std::fs::remove_file(&path).ok();
}
}
#[cfg(test)]
mod integration_tests {
use super::*;
fn temp_path(name: &str) -> std::path::PathBuf {
super::unique_test_path(name)
}
#[test]
fn write_file_for_h5dump() {
let path = temp_path("integration");
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<u8>()
.shape([4usize, 4])
.create("data_u8")
.unwrap();
let data: Vec<u8> = (0..16).collect();
ds.write_raw(&data).unwrap();
let ds2 = file
.new_dataset::<f64>()
.shape([3usize, 2])
.create("data_f64")
.unwrap();
let fdata: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
ds2.write_raw(&fdata).unwrap();
let ds3 = file
.new_dataset::<i32>()
.shape([5usize])
.create("values")
.unwrap();
let idata: Vec<i32> = vec![-10, -5, 0, 5, 10];
ds3.write_raw(&idata).unwrap();
file.close().unwrap();
// File exists
assert!(path.exists());
}
#[test]
fn write_chunked_file_for_h5dump() {
let path = temp_path("chunked");
let file = H5File::create(&path).unwrap();
// Create a chunked dataset with unlimited first dimension
let ds = file
.new_dataset::<f64>()
.shape([0usize, 4])
.chunk(&[1, 4])
.max_shape(&[None, Some(4)])
.create("streaming_data")
.unwrap();
// Write 5 frames of data
for frame in 0..5u64 {
let values: Vec<f64> = (0..4).map(|i| (frame * 4 + i) as f64).collect();
let raw: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
// Extend dimensions to reflect the 5 written frames
ds.extend(&[5, 4]).unwrap();
ds.flush().unwrap();
file.close().unwrap();
assert!(path.exists());
}
#[test]
fn write_chunked_many_frames_for_h5dump() {
let path = temp_path("chunked_many");
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([0usize, 3])
.chunk(&[1, 3])
.max_shape(&[None, Some(3)])
.create("data")
.unwrap();
// Write 10 frames (exceeds idx_blk_elmts=4, uses data blocks)
for frame in 0..10u64 {
let vals: Vec<i32> = (0..3).map(|i| (frame * 3 + i) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[10, 3]).unwrap();
file.close().unwrap();
assert!(path.exists());
}
#[test]
fn write_dataset_with_attributes() {
use crate::types::VarLenUnicode;
let path = temp_path("attributes");
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<f32>()
.shape([10usize])
.create("temperature")
.unwrap();
let data: Vec<f32> = (0..10).map(|i| i as f32 * 1.5).collect();
ds.write_raw(&data).unwrap();
// Add string attributes
let attr = ds
.new_attr::<VarLenUnicode>()
.shape(())
.create("units")
.unwrap();
attr.write_scalar(&VarLenUnicode("kelvin".to_string()))
.unwrap();
let attr2 = ds
.new_attr::<VarLenUnicode>()
.shape(())
.create("description")
.unwrap();
attr2
.write_scalar(&VarLenUnicode("Temperature measurements".to_string()))
.unwrap();
// Use write_string convenience method
let attr3 = ds
.new_attr::<VarLenUnicode>()
.shape(())
.create("source")
.unwrap();
attr3.write_string("sensor_01").unwrap();
// Also test parse -> write_scalar pattern
let attr4 = ds
.new_attr::<VarLenUnicode>()
.shape(())
.create("label")
.unwrap();
let s: VarLenUnicode = "test_label".parse().unwrap_or_default();
attr4.write_scalar(&s).unwrap();
file.close().unwrap();
assert!(path.exists());
}
#[test]
fn dataset_writer_reopens_for_attributes() {
// Reopen a dataset by name in write mode (the original handle is gone)
// and attach attributes to it — the close-time flush pattern.
let path = temp_path("dataset_writer");
{
let file = H5File::create(&path).unwrap();
{
let ds = file
.new_dataset::<u16>()
.shape([8])
.create("image")
.unwrap();
ds.write_raw(&[0u16; 8]).unwrap();
// original handle dropped here
}
// Reopen by name; dataset() would error in write mode.
assert!(file.dataset("image").is_err());
let ds = file.dataset_writer("image").unwrap();
assert_eq!(ds.shape(), vec![8]);
ds.new_attr::<i32>()
.shape([3])
.create("NDArrayDimOffset")
.unwrap()
.write_array(&[0i32, 4, 8])
.unwrap();
ds.new_attr::<i32>()
.shape(())
.create("NDUniqueId")
.unwrap()
.write_numeric(&42i32)
.unwrap();
// Missing dataset is reported.
assert!(matches!(
file.dataset_writer("nope"),
Err(crate::error::Hdf5Error::NotFound(_))
));
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("image").unwrap();
let off = ds.attr("NDArrayDimOffset").unwrap().read_raw().unwrap();
let got: Vec<i32> = off
.as_chunks::<4>()
.0
.iter()
.map(|b| i32::from_le_bytes(*b))
.collect();
assert_eq!(got, vec![0, 4, 8]);
let uid: i32 = ds.attr("NDUniqueId").unwrap().read_numeric().unwrap();
assert_eq!(uid, 42);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn chunked_write_read_roundtrip() {
let path = temp_path("chunked_roundtrip");
// Write
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([0usize, 3])
.chunk(&[1, 3])
.max_shape(&[None, Some(3)])
.create("table")
.unwrap();
for frame in 0..8u64 {
let vals: Vec<i32> = (0..3).map(|i| (frame * 3 + i) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[8, 3]).unwrap();
file.close().unwrap();
}
// Read
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("table").unwrap();
assert_eq!(ds.shape(), vec![8, 3]);
let data = ds.read_raw::<i32>().unwrap();
assert_eq!(data.len(), 24);
for (i, val) in data.iter().enumerate() {
assert_eq!(*val, i as i32);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn compressed_chunked_roundtrip() {
let path = temp_path("compressed_roundtrip");
// Write compressed
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<f64>()
.shape([0usize, 4])
.chunk(&[1, 4])
.max_shape(&[None, Some(4)])
.deflate(6)
.create("compressed")
.unwrap();
for frame in 0..10u64 {
let vals: Vec<f64> = (0..4).map(|i| (frame * 4 + i) as f64).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[10, 4]).unwrap();
file.close().unwrap();
}
// Read back and verify
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("compressed").unwrap();
assert_eq!(ds.shape(), vec![10, 4]);
let data = ds.read_raw::<f64>().unwrap();
assert_eq!(data.len(), 40);
for (i, val) in data.iter().enumerate() {
assert!(
(val - i as f64).abs() < 1e-10,
"mismatch at {}: {} != {}",
i,
val,
i
);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn compressed_chunked_many_frames() {
let path = temp_path("compressed_many");
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([0usize, 3])
.chunk(&[1, 3])
.max_shape(&[None, Some(3)])
.deflate(6)
.create("stream")
.unwrap();
for frame in 0..100u64 {
let vals: Vec<i32> = (0..3).map(|i| (frame * 3 + i) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[100, 3]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("stream").unwrap();
assert_eq!(ds.shape(), vec![100, 3]);
let data = ds.read_raw::<i32>().unwrap();
assert_eq!(data.len(), 300);
for (i, val) in data.iter().enumerate() {
assert_eq!(*val, i as i32, "mismatch at {}", i);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
fn append_mode() {
let path = temp_path("append");
// Create initial file
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([3usize])
.create("first")
.unwrap();
ds.write_raw(&[1i32, 2, 3]).unwrap();
file.close().unwrap();
}
// Append new dataset
{
let file = H5File::open_rw(&path).unwrap();
let ds = file
.new_dataset::<f64>()
.shape([2usize])
.create("second")
.unwrap();
ds.write_raw(&[4.0f64, 5.0]).unwrap();
file.close().unwrap();
}
// Read back both
{
let file = H5File::open(&path).unwrap();
let names = file.dataset_names();
assert!(names.contains(&"first".to_string()));
assert!(names.contains(&"second".to_string()));
let ds1 = file.dataset("first").unwrap();
assert_eq!(ds1.read_raw::<i32>().unwrap(), vec![1, 2, 3]);
let ds2 = file.dataset("second").unwrap();
assert_eq!(ds2.read_raw::<f64>().unwrap(), vec![4.0, 5.0]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn open_rw_set_attr_preserves_file() {
let path = temp_path("open_rw_attr");
// Create file with a dataset and an attribute
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([3usize])
.create("data")
.unwrap();
ds.write_raw(&[10i32, 20, 30]).unwrap();
file.set_attr_string("version", "1.0").unwrap();
file.close().unwrap();
}
// Open rw and modify the attribute
{
let file = H5File::open_rw(&path).unwrap();
file.set_attr_string("version", "2.0").unwrap();
file.close().unwrap();
}
// Verify: dataset intact, attribute updated
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.read_raw::<i32>().unwrap(), vec![10, 20, 30]);
let ver = file.attr_string("version").unwrap();
assert_eq!(ver, "2.0");
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn open_rw_attr_with_compressed_dataset() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("open_rw_compressed");
let input: Vec<&str> = (0..50).map(|_| "test string data").collect();
// Create file with compressed vlen strings
{
let file = H5File::create(&path).unwrap();
file.write_vlen_strings_compressed("texts", &input, 16, FilterPipeline::deflate(6))
.unwrap();
file.set_attr_string("version", "1.0").unwrap();
file.close().unwrap();
}
// Open rw and modify attribute only
{
let file = H5File::open_rw(&path).unwrap();
file.set_attr_string("version", "2.0").unwrap();
file.close().unwrap();
}
// Verify: compressed dataset still readable, attribute updated
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("texts").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 50);
assert_eq!(strings[0], "test string data");
let ver = file.attr_string("version").unwrap();
assert_eq!(ver, "2.0");
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "lz4")]
fn append_vlen_strings_basic() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("append_vlen");
{
let file = H5File::create(&path).unwrap();
file.create_appendable_vlen_dataset("names", 4, Some(FilterPipeline::lz4()))
.unwrap();
file.append_vlen_strings("names", &["alice", "bob", "charlie"])
.unwrap();
file.append_vlen_strings("names", &["dave", "eve"]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("names").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings, vec!["alice", "bob", "charlie", "dave", "eve"]);
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "lz4")]
fn append_vlen_strings_large() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("append_vlen_large");
let batch1: Vec<String> = (0..5000).map(|i| format!("node-{:06}", i)).collect();
let batch2: Vec<String> = (5000..7189).map(|i| format!("node-{:06}", i)).collect();
{
let file = H5File::create(&path).unwrap();
file.create_appendable_vlen_dataset("data", 512, Some(FilterPipeline::lz4()))
.unwrap();
let r1: Vec<&str> = batch1.iter().map(|s| s.as_str()).collect();
file.append_vlen_strings("data", &r1).unwrap();
let r2: Vec<&str> = batch2.iter().map(|s| s.as_str()).collect();
file.append_vlen_strings("data", &r2).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 7189);
assert_eq!(strings[0], "node-000000");
assert_eq!(strings[7188], "node-007188");
}
std::fs::remove_file(&path).ok();
}
#[test]
fn append_vlen_strings_uncompressed() {
let path = temp_path("append_vlen_unc");
{
let file = H5File::create(&path).unwrap();
file.create_appendable_vlen_dataset("texts", 8, None)
.unwrap();
file.append_vlen_strings("texts", &["hello", "world"])
.unwrap();
file.append_vlen_strings("texts", &["foo", "bar", "baz"])
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("texts").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings, vec!["hello", "world", "foo", "bar", "baz"]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn delete_dataset_roundtrip() {
let path = temp_path("delete_ds");
{
let file = H5File::create(&path).unwrap();
file.write_vlen_strings("keep", &["a", "b"]).unwrap();
file.write_vlen_strings("remove", &["x", "y"]).unwrap();
file.delete_dataset("remove").unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let names = file.dataset_names();
assert!(names.contains(&"keep".to_string()));
assert!(!names.contains(&"remove".to_string()));
let ds = file.dataset("keep").unwrap();
assert_eq!(ds.read_vlen_strings().unwrap(), vec!["a", "b"]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn delete_group_roundtrip() {
let path = temp_path("delete_grp");
{
let file = H5File::create(&path).unwrap();
let g1 = file.create_group("keep").unwrap();
g1.write_vlen_strings("data", &["a"]).unwrap();
let g2 = file.create_group("remove").unwrap();
g2.write_vlen_strings("data", &["x"]).unwrap();
file.delete_group("remove").unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let names = file.dataset_names();
assert!(names.contains(&"keep/data".to_string()));
assert!(!names.contains(&"remove/data".to_string()));
}
std::fs::remove_file(&path).ok();
}
#[test]
fn open_rw_delete_recreate_group() {
let path = temp_path("rw_delete_recreate");
// Step 1: create file with groups
{
let file = H5File::create(&path).unwrap();
let n = file.create_group("nodes").unwrap();
n.write_vlen_strings("id", &["a", "b", "c"]).unwrap();
let e = file.create_group("edges").unwrap();
e.write_vlen_strings("src", &["x", "y"]).unwrap();
file.close().unwrap();
}
// Step 2: open_rw, delete one group, recreate with new data
{
let file = H5File::open_rw(&path).unwrap();
file.delete_group("nodes").unwrap();
let n = file.create_group("nodes").unwrap();
n.write_vlen_strings("id", &["new1", "new2"]).unwrap();
file.close().unwrap();
}
// Step 3: verify
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("nodes/id").unwrap();
let s = ds.read_vlen_strings().unwrap();
assert_eq!(s, vec!["new1", "new2"]);
// edges should still be intact
let ds = file.dataset("edges/src").unwrap();
let s = ds.read_vlen_strings().unwrap();
assert_eq!(s, vec!["x", "y"]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn delete_and_recreate_group() {
let path = temp_path("delete_recreate");
{
let file = H5File::create(&path).unwrap();
let g = file.create_group("nodes").unwrap();
g.write_vlen_strings("id", &["old1", "old2"]).unwrap();
file.delete_group("nodes").unwrap();
let g = file.create_group("nodes").unwrap();
g.write_vlen_strings("id", &["new1", "new2", "new3"])
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("nodes/id").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings, vec!["new1", "new2", "new3"]);
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn vlen_string_compressed_large_roundtrip() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("vlen_large");
// Simulate kodex scenario: 7189 strings, chunk_size 512
let input: Vec<String> = (0..7189)
.map(|i| format!("node-{:08x}-{}", i, "a".repeat(20 + (i % 30))))
.collect();
let input_refs: Vec<&str> = input.iter().map(|s| s.as_str()).collect();
{
let file = H5File::create(&path).unwrap();
file.create_group("nodes").unwrap();
file.write_vlen_strings_compressed(
"nodes/id",
&input_refs,
512,
FilterPipeline::deflate(6),
)
.unwrap();
file.close().unwrap();
}
// Read back
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("nodes/id").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 7189);
assert_eq!(strings[0], input[0]);
assert_eq!(strings[7188], input[7188]);
}
// Also test open_rw then re-read
{
let file = H5File::open_rw(&path).unwrap();
file.set_attr_string("version", "1.0").unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("nodes/id").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 7189);
assert_eq!(strings[0], input[0]);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn vlen_string_write_read() {
let path = temp_path("vlen_wr");
{
let file = H5File::create(&path).unwrap();
file.write_vlen_strings("names", &["alice", "bob", "charlie"])
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("names").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings, vec!["alice", "bob", "charlie"]);
}
std::fs::remove_file(&path).ok();
}
/// The one-call writers declare the character set they are named for —
/// `write_vlen_strings` UTF-8, `write_vlen_strings_ascii` ASCII — and the
/// ASCII one refuses a string its declaration would misdescribe, before
/// anything reaches the file.
#[test]
fn vlen_string_writers_declare_their_character_set() {
use crate::format::messages::datatype::DatatypeMessage;
let path = temp_path("vlen_cset");
let file = H5File::create(&path).unwrap();
file.write_vlen_strings_ascii("ascii", &["alpha", "b", ""])
.unwrap();
file.write_vlen_strings("utf8", &["été", "日本"]).unwrap();
let err = file
.write_vlen_strings_ascii("rejected", &["ok", "안녕"])
.err()
.expect("a non-ASCII string was accepted under an ASCII datatype")
.to_string();
assert!(
err.contains("string 1") && err.contains("is not ASCII"),
"got: {err}"
);
file.close().unwrap();
let file = H5File::open(&path).unwrap();
let ascii = file.dataset("ascii").unwrap();
assert_eq!(
ascii.datatype().unwrap(),
DatatypeMessage::VarLenString {
padding: 0,
charset: 0,
}
);
assert_eq!(ascii.read_strings().unwrap(), vec!["alpha", "b", ""]);
let utf8 = file.dataset("utf8").unwrap();
assert_eq!(
utf8.datatype().unwrap(),
DatatypeMessage::VarLenString {
padding: 0,
charset: 1,
}
);
assert_eq!(utf8.read_strings().unwrap(), vec!["été", "日本"]);
// The refused write left nothing behind.
assert!(file.dataset("rejected").is_err());
std::fs::remove_file(&path).ok();
}
/// The group-level twin declares ASCII the same way the file-level one
/// does, for a dataset inside the group.
#[test]
fn group_vlen_string_writer_declares_ascii() {
use crate::format::messages::datatype::DatatypeMessage;
let path = temp_path("vlen_cset_group");
let file = H5File::create(&path).unwrap();
let g = file.create_group("entry").unwrap();
g.write_vlen_strings_ascii("notes", &["alpha", "b"])
.unwrap();
let err = g
.write_vlen_strings_ascii("rejected", &["안녕"])
.err()
.expect("a non-ASCII string was accepted under an ASCII datatype")
.to_string();
assert!(err.contains("is not ASCII"), "got: {err}");
file.close().unwrap();
let file = H5File::open(&path).unwrap();
let ds = file.dataset("entry/notes").unwrap();
assert_eq!(
ds.datatype().unwrap(),
DatatypeMessage::VarLenString {
padding: 0,
charset: 0,
}
);
assert_eq!(ds.read_strings().unwrap(), vec!["alpha", "b"]);
std::fs::remove_file(&path).ok();
}
#[test]
fn vlen_bytes_write_read() {
let path = temp_path("vlen_bytes_wr");
let items: [&[u8]; 4] = [b"abc", b"", &[0u8, 1, 2, 255], b"hi"];
{
let file = H5File::create(&path).unwrap();
file.write_vlen_bytes("blobs", &items).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("blobs").unwrap();
let got = ds.read_vlen_bytes().unwrap();
let expected: Vec<Vec<u8>> = items.iter().map(|s| s.to_vec()).collect();
assert_eq!(got, expected);
}
std::fs::remove_file(&path).ok();
}
/// A vlen sequence over a wider base stores element counts, not byte
/// counts, in the `H5T_VLEN` length field, and the datatype names the
/// base — so the file says what it holds for every width.
#[test]
fn vlen_numeric_write_read() {
use crate::format::global_heap::decode_vlen_reference;
use crate::format::messages::datatype::DatatypeMessage;
let path = temp_path("vlen_numeric_wr");
let a: &[i32] = &[1, 2, 3];
let b: &[i32] = &[];
let c: &[i32] = &[-7];
{
let file = H5File::create(&path).unwrap();
file.write_vlen_numeric("data", &[a, b, c]).unwrap();
let f64s: &[f64] = &[1.5, -2.5];
file.write_vlen_numeric("wide", &[f64s]).unwrap();
file.close().unwrap();
}
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(
ds.datatype().unwrap(),
DatatypeMessage::VarLenSequence {
base: Box::new(DatatypeMessage::i32_type()),
}
);
let decoded: Vec<Vec<i32>> = ds
.read_vlen_bytes()
.unwrap()
.iter()
.map(|item| {
item.as_chunks::<4>()
.0
.iter()
.map(|w| i32::from_le_bytes(*w))
.collect()
})
.collect();
assert_eq!(decoded, vec![a.to_vec(), b.to_vec(), c.to_vec()]);
// The length field counts elements: 3 i32s, not 12 bytes.
let ctx = crate::format::FormatContext::default_v3();
let raw = ds.read_raw_bytes().unwrap();
let (seq_len, _, _) = decode_vlen_reference(&raw, &ctx).unwrap();
assert_eq!(seq_len, 3);
let wide = file.dataset("wide").unwrap();
assert_eq!(
wide.datatype().unwrap(),
DatatypeMessage::VarLenSequence {
base: Box::new(DatatypeMessage::f64_type()),
}
);
let (seq_len, _, _) = decode_vlen_reference(&wide.read_raw_bytes().unwrap(), &ctx).unwrap();
assert_eq!(seq_len, 2);
drop(file);
std::fs::remove_file(&path).ok();
}
/// `write_vlen_bytes` is the `u8` case of the same writer, so the byte
/// datatype and the byte-per-element length field are unchanged.
#[test]
fn vlen_bytes_is_the_u8_case_of_vlen_numeric() {
use crate::format::messages::datatype::DatatypeMessage;
let path = temp_path("vlen_bytes_u8");
let items: [&[u8]; 2] = [b"abc", b""];
{
let file = H5File::create(&path).unwrap();
file.write_vlen_bytes("blobs", &items).unwrap();
file.close().unwrap();
}
let file = H5File::open(&path).unwrap();
let ds = file.dataset("blobs").unwrap();
assert_eq!(ds.datatype().unwrap(), DatatypeMessage::vlen_bytes());
let ctx = crate::format::FormatContext::default_v3();
let (seq_len, _, _) =
crate::format::global_heap::decode_vlen_reference(&ds.read_raw_bytes().unwrap(), &ctx)
.unwrap();
assert_eq!(seq_len, 3);
drop(file);
std::fs::remove_file(&path).ok();
}
#[test]
fn vlen_bytes_in_group_with_attribute() {
use crate::types::VarLenUnicode;
let path = temp_path("vlen_bytes_grp");
let items: [&[u8]; 2] = [&[1u8, 2, 3], &[9u8, 8, 7, 6]];
{
let file = H5File::create(&path).unwrap();
let grp = file.root_group().create_group("payloads").unwrap();
let ds = grp.write_vlen_bytes("frames", &items).unwrap();
ds.new_attr::<VarLenUnicode>()
.shape(())
.create("codec")
.unwrap()
.write_string("raw")
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("payloads/frames").unwrap();
let got = ds.read_vlen_bytes().unwrap();
let expected: Vec<Vec<u8>> = items.iter().map(|s| s.to_vec()).collect();
assert_eq!(got, expected);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn vlen_dataset_returns_handle_for_attributes() {
use crate::types::VarLenUnicode;
let path = temp_path("vlen_attr");
{
let file = H5File::create(&path).unwrap();
let grp = file.root_group().create_group("ch").unwrap();
// The vlen helper now returns the dataset handle, so attributes can
// be attached directly — the issue the mdfr reporter hit.
let ds = grp
.write_vlen_strings("labels", &["a", "bb", "ccc"])
.unwrap();
ds.new_attr::<VarLenUnicode>()
.shape(())
.create("unit")
.unwrap()
.write_string("volt")
.unwrap();
// The same dataset can also be reopened by name within the group.
let ds2 = grp.dataset_writer("labels").unwrap();
ds2.new_attr::<VarLenUnicode>()
.shape(())
.create("desc")
.unwrap()
.write_string("channel labels")
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("ch/labels").unwrap();
assert_eq!(ds.read_vlen_strings().unwrap(), vec!["a", "bb", "ccc"]);
assert_eq!(ds.attr("unit").unwrap().read_string().unwrap(), "volt");
assert_eq!(
ds.attr("desc").unwrap().read_string().unwrap(),
"channel labels"
);
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn vlen_string_deflate_roundtrip() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("vlen_deflate");
let input: Vec<&str> = (0..100)
.map(|i| match i % 3 {
0 => "hello world",
1 => "compressed vlen string test",
_ => "rust-hdf5",
})
.collect();
{
let file = H5File::create(&path).unwrap();
file.write_vlen_strings_compressed("texts", &input, 16, FilterPipeline::deflate(6))
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("texts").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 100);
for (i, s) in strings.iter().enumerate() {
assert_eq!(s, input[i]);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "zstd")]
fn vlen_string_zstd_roundtrip() {
use crate::format::messages::filter::FilterPipeline;
let path = temp_path("vlen_zstd");
let input: Vec<&str> = (0..200)
.map(|i| match i % 4 {
0 => "zstandard compression test",
1 => "variable length string",
2 => "rust-hdf5 chunked storage",
_ => "hello zstd world",
})
.collect();
{
let file = H5File::create(&path).unwrap();
file.write_vlen_strings_compressed("data", &input, 32, FilterPipeline::zstd(3))
.unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
let strings = ds.read_vlen_strings().unwrap();
assert_eq!(strings.len(), 200);
for (i, s) in strings.iter().enumerate() {
assert_eq!(s, input[i]);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
#[cfg(feature = "deflate")]
fn shuffle_deflate_roundtrip() {
let path = temp_path("shuf_defl");
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<f64>()
.shape([0usize, 4])
.chunk(&[1, 4])
.max_shape(&[None, Some(4)])
.shuffle_deflate(6)
.create("data")
.unwrap();
for frame in 0..20u64 {
let vals: Vec<f64> = (0..4).map(|i| (frame * 4 + i) as f64).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(frame as usize, &raw).unwrap();
}
ds.extend(&[20, 4]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.shape(), vec![20, 4]);
let data = ds.read_raw::<f64>().unwrap();
assert_eq!(data.len(), 80);
for (i, val) in data.iter().enumerate() {
assert!((val - i as f64).abs() < 1e-10);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
fn file_level_attributes() {
let path = temp_path("file_attr");
{
let file = H5File::create(&path).unwrap();
file.set_attr_string("title", "Test File").unwrap();
file.set_attr_numeric("version", &42i32).unwrap();
let ds = file
.new_dataset::<u8>()
.shape([1usize])
.create("dummy")
.unwrap();
ds.write_raw(&[0u8]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
assert!(file.dataset_names().contains(&"dummy".to_string()));
// Read file-level attributes
let names = file.attr_names().unwrap();
assert!(names.contains(&"title".to_string()));
let title = file.attr_string("title").unwrap();
assert_eq!(title, "Test File");
}
std::fs::remove_file(&path).ok();
}
#[test]
fn scalar_dataset_roundtrip() {
let path = temp_path("scalar");
{
let file = H5File::create(&path).unwrap();
let ds = file.new_dataset::<f64>().scalar().create("pi").unwrap();
ds.write_raw(&[std::f64::consts::PI]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("pi").unwrap();
assert_eq!(ds.shape(), Vec::<usize>::new());
assert_eq!(ds.total_elements(), 1);
let data = ds.read_raw::<f64>().unwrap();
assert_eq!(data.len(), 1);
assert!((data[0] - std::f64::consts::PI).abs() < 1e-15);
}
std::fs::remove_file(&path).ok();
}
#[test]
fn append_mode_extend_chunked() {
let path = temp_path("append_extend");
// Create with 5 frames
{
let file = H5File::create(&path).unwrap();
let ds = file
.new_dataset::<i32>()
.shape([0usize, 3])
.chunk(&[1, 3])
.max_shape(&[None, Some(3)])
.create("stream")
.unwrap();
for i in 0..5u64 {
let vals: Vec<i32> = (0..3).map(|j| (i * 3 + j) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds.write_chunk(i as usize, &raw).unwrap();
}
ds.extend(&[5, 3]).unwrap();
file.close().unwrap();
}
// Reopen and add 5 more frames
{
let file = H5File::open_rw(&path).unwrap();
// Find the stream dataset index (it's the first one)
let names = file.dataset_names();
assert!(names.contains(&"stream".to_string()));
// Write more chunks via the writer directly
let mut inner = crate::file::borrow_inner_mut(&file.inner);
if let crate::file::H5FileInner::Writer(writer) = &mut *inner {
let ds_idx = writer.dataset_index("stream").unwrap();
for i in 5..10u64 {
let vals: Vec<i32> = (0..3).map(|j| (i * 3 + j) as i32).collect();
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
writer.write_chunk(ds_idx, i, &raw).unwrap();
}
writer.extend_dataset(ds_idx, &[10, 3]).unwrap();
}
drop(inner);
file.close().unwrap();
}
// Read back all 10 frames
{
let file = H5File::open(&path).unwrap();
let ds = file.dataset("stream").unwrap();
assert_eq!(ds.shape(), vec![10, 3]);
let data = ds.read_raw::<i32>().unwrap();
assert_eq!(data.len(), 30);
for (i, val) in data.iter().enumerate() {
assert_eq!(*val, i as i32, "mismatch at {}", i);
}
}
std::fs::remove_file(&path).ok();
}
#[test]
fn group_hierarchy_roundtrip() {
let path = temp_path("groups_rt");
{
let file = H5File::create(&path).unwrap();
let root = file.root_group();
// Create groups
let det = root.create_group("detector").unwrap();
let raw = det.create_group("raw").unwrap();
// Create datasets in groups
let ds1 = det
.new_dataset::<f32>()
.shape([10usize])
.create("temperature")
.unwrap();
ds1.write_raw(&[1.0f32; 10]).unwrap();
let ds2 = raw
.new_dataset::<u16>()
.shape([4usize, 4])
.create("image")
.unwrap();
ds2.write_raw(&[42u16; 16]).unwrap();
// Root-level dataset
let ds3 = file
.new_dataset::<i32>()
.shape([3usize])
.create("version")
.unwrap();
ds3.write_raw(&[1i32, 0, 0]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let names = file.dataset_names();
assert!(names.contains(&"version".to_string()));
assert!(names.contains(&"detector/temperature".to_string()));
assert!(names.contains(&"detector/raw/image".to_string()));
// Read datasets
let ds = file.dataset("version").unwrap();
assert_eq!(ds.read_raw::<i32>().unwrap(), vec![1, 0, 0]);
let ds = file.dataset("detector/temperature").unwrap();
assert_eq!(ds.read_raw::<f32>().unwrap(), vec![1.0f32; 10]);
let ds = file.dataset("detector/raw/image").unwrap();
assert_eq!(ds.shape(), vec![4, 4]);
assert_eq!(ds.read_raw::<u16>().unwrap(), vec![42u16; 16]);
// Group traversal
let root = file.root_group();
let group_names = root.group_names().unwrap();
assert!(group_names.contains(&"detector".to_string()));
}
std::fs::remove_file(&path).ok();
}
#[test]
fn nested_groups_via_file_create_group() {
let path = temp_path("file_create_group");
{
let file = H5File::create(&path).unwrap();
// Use the H5File::create_group convenience method
let grp = file.create_group("sensors").unwrap();
let sub = grp.create_group("accel").unwrap();
let ds = sub
.new_dataset::<f64>()
.shape([3usize])
.create("xyz")
.unwrap();
ds.write_raw(&[1.0f64, 2.0, 3.0]).unwrap();
file.close().unwrap();
}
{
let file = H5File::open(&path).unwrap();
let names = file.dataset_names();
assert!(names.contains(&"sensors/accel/xyz".to_string()));
let ds = file.dataset("sensors/accel/xyz").unwrap();
assert_eq!(ds.read_raw::<f64>().unwrap(), vec![1.0, 2.0, 3.0]);
// Open group in read mode
let root = file.root_group();
let sensors = root.group("sensors").unwrap();
assert_eq!(sensors.name(), "/sensors");
let accel = sensors.group("accel").unwrap();
assert_eq!(accel.name(), "/sensors/accel");
// list_groups from root
let top_groups = root.group_names().unwrap();
assert!(top_groups.contains(&"sensors".to_string()));
// list_groups from sensors
let sub_groups = sensors.group_names().unwrap();
assert!(sub_groups.contains(&"accel".to_string()));
}
std::fs::remove_file(&path).ok();
}
}
#[cfg(test)]
mod h5py_compat_tests {
use super::*;
fn temp_path(name: &str) -> std::path::PathBuf {
super::unique_test_path(name)
}
/// Verify our files can be read by h5dump (if available).
#[test]
#[cfg(feature = "deflate")]
fn h5dump_validates_our_files() {
// Check if h5dump is available
let h5dump = std::process::Command::new("h5dump")
.arg("--version")
.output();
if h5dump.is_err() {
eprintln!("skipping: h5dump not found");
return;
}
let path = temp_path("h5dump_validate");
// Write a comprehensive test file
{
let file = H5File::create(&path).unwrap();
// Contiguous
let ds = file
.new_dataset::<f64>()
.shape([3usize, 4])
.create("matrix")
.unwrap();
let data: Vec<f64> = (0..12).map(|i| i as f64).collect();
ds.write_raw(&data).unwrap();
// Chunked + compressed
let ds2 = file
.new_dataset::<i32>()
.shape([0usize, 2])
.chunk(&[1, 2])
.max_shape(&[None, Some(2)])
.deflate(6)
.create("stream")
.unwrap();
for i in 0..5u64 {
let vals: Vec<i32> = vec![i as i32 * 2, i as i32 * 2 + 1];
let raw: Vec<u8> = vals.iter().flat_map(|v| v.to_le_bytes()).collect();
ds2.write_chunk(i as usize, &raw).unwrap();
}
ds2.extend(&[5, 2]).unwrap();
// Group
let grp = file.create_group("meta").unwrap();
let ds3 = grp
.new_dataset::<u8>()
.shape([4usize])
.create("flags")
.unwrap();
ds3.write_raw(&[1u8, 0, 1, 0]).unwrap();
// String attribute
use crate::types::VarLenUnicode;
let attr = ds
.new_attr::<VarLenUnicode>()
.shape(())
.create("units")
.unwrap();
attr.write_string("meters").unwrap();
file.close().unwrap();
}
// Run h5dump and verify exit code
let output = std::process::Command::new("h5dump")
.arg("-H") // header only (faster)
.arg(path.to_str().unwrap())
.output()
.unwrap();
assert!(
output.status.success(),
"h5dump failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
// Full dump (with data) should also work
let output2 = std::process::Command::new("h5dump")
.arg(path.to_str().unwrap())
.output()
.unwrap();
assert!(
output2.status.success(),
"h5dump (full) failed:\nstderr: {}",
String::from_utf8_lossy(&output2.stderr),
);
std::fs::remove_file(&path).ok();
}
#[test]
fn read_h5py_generated_file() {
let path = "/tmp/test_h5py_default.h5";
if !std::path::Path::new(path).exists() {
eprintln!("skipping: h5py test file not found");
return;
}
let file = H5File::open(path).unwrap();
let ds = file.dataset("data").unwrap();
assert_eq!(ds.shape(), vec![4, 5]);
let data = ds.read_raw::<f64>().unwrap();
assert_eq!(data.len(), 20);
assert!((data[0]).abs() < 1e-10);
assert!((data[19] - 19.0).abs() < 1e-10);
let ds2 = file.dataset("images").unwrap();
assert_eq!(ds2.shape(), vec![3, 64, 64]);
let images = ds2.read_raw::<u16>().unwrap();
assert_eq!(images.len(), 3 * 64 * 64);
}
/// `track_order`, `libver`, `userblock` and `shared_messages` only take
/// effect on [`H5FileOptions::create`]; setting any of them for
/// [`H5FileOptions::open_rw`] on an already-created file must be
/// refused, naming the option, rather than silently doing nothing.
#[test]
fn open_rw_refuses_every_create_only_option() {
let path = temp_path("open_rw_refuses");
H5File::create(&path).unwrap().close().unwrap();
let err = H5File::options()
.track_order(true)
.open_rw(&path)
.err()
.unwrap();
assert!(err.to_string().contains("track_order"), "{err}");
let err = H5File::options()
.libver(LibverBound::V110)
.open_rw(&path)
.err()
.unwrap();
assert!(err.to_string().contains("libver"), "{err}");
// Every bound, not just the ones that differ from `LibverBound`'s
// own default. `Earliest` *is* that default and is the bound that
// asks for a classic file, so a gate comparing against the default
// value would pass this call through as if nothing had been set.
for bound in [
LibverBound::Earliest,
LibverBound::V18,
LibverBound::V112,
LibverBound::V114,
LibverBound::V200,
] {
let err = H5File::options()
.libver(bound)
.open_rw(&path)
.err()
.unwrap();
assert!(err.to_string().contains("libver"), "{bound:?}: {err}");
}
let err = H5File::options()
.userblock(512)
.open_rw(&path)
.err()
.unwrap();
assert!(err.to_string().contains("userblock"), "{err}");
let types = crate::format::sohm::type_flag(crate::format::messages::MSG_DATATYPE).unwrap();
let err = H5File::options()
.shared_messages(&[(types, 0)], 50, 40)
.open_rw(&path)
.err()
.unwrap();
assert!(err.to_string().contains("shared_messages"), "{err}");
// A default builder — no create-only option touched — still opens.
H5File::options().open_rw(&path).unwrap().close().unwrap();
std::fs::remove_file(&path).ok();
}
/// [`H5FileOptions::open`] shares the same gate as `open_rw` — it goes
/// through the same `refuse_create_only_options` check.
#[test]
fn open_refuses_a_create_only_option() {
let path = temp_path("open_refuses");
H5File::create(&path).unwrap().close().unwrap();
let err = H5File::options()
.track_order(true)
.open(&path)
.err()
.unwrap();
assert!(err.to_string().contains("track_order"), "{err}");
H5File::options().open(&path).unwrap().close().unwrap();
std::fs::remove_file(&path).ok();
}
}