readcon-core 0.25.0

An oxidized single and multiple CON file reader and writer with FFI bindings for ergonomic C/C++ usage. Implements CON spec v4.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
//! CON-bin: one page of header, then every frame's positions as one run
//! of little-endian values, then the velocities the same way.
//!
//! [`map_file`] maps that file and faults it in place. The runs are the
//! columns: the caller does not allocate a second buffer, so the read does
//! not take a write fault per destination page. [`read_into_threads`] is the
//! `pread` fill of a caller-owned slice, kept so a measurement can pair the
//! two on the same file.

use std::cell::RefCell;
use std::fs::File;
use std::io::{IoSlice, Read, Write};
#[cfg(unix)]
use std::os::fd::AsRawFd;
use std::path::Path;

use crate::error::ParseError;
use crate::iterators::ConFrameIterator;

const MAGIC: &[u8; 8] = b"CONBIN01";
const VERSION_1: u32 = 1;
const VERSION_2: u32 = 2;
const FLAG_F32: u32 = 1;
const FLAG_VELOCITY: u32 = 2;
const FLAG_FORCE: u32 = 4;
const FLAG_MASS: u32 = 8;
const FLAG_FIXED: u32 = 16;
const FLAG_CELL: u32 = 32;
const FLAG_IDS: u32 = 64;

/// Magic, version, flags, frame count, atom count, payload offset.
/// 8 + 4 + 4 + 8 + 8 + 8.
const FIELD_BYTES: usize = 40;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConBinHeader {
    pub version: u32,
    pub n_frames: u64,
    pub n_atoms: u64,
    pub binary32: bool,
    pub velocities: bool,
    pub forces: bool,
    pub masses: bool,
    pub fixed: bool,
    pub cell: bool,
    pub atom_ids: bool,
}

impl ConBinHeader {
    /// Version 1: positions, and velocities when `velocities` is set.
    pub fn version1(n_frames: u64, n_atoms: u64, binary32: bool, velocities: bool) -> Self {
        Self {
            version: VERSION_1,
            n_frames,
            n_atoms,
            binary32,
            velocities,
            forces: false,
            masses: false,
            fixed: false,
            cell: false,
            atom_ids: false,
        }
    }

    fn flags(&self) -> u32 {
        let mut flags = 0u32;
        if self.binary32 {
            flags |= FLAG_F32;
        }
        if self.velocities {
            flags |= FLAG_VELOCITY;
        }
        if self.version >= VERSION_2 {
            if self.forces {
                flags |= FLAG_FORCE;
            }
            if self.masses {
                flags |= FLAG_MASS;
            }
            if self.fixed {
                flags |= FLAG_FIXED;
            }
            if self.cell {
                flags |= FLAG_CELL;
            }
            if self.atom_ids {
                flags |= FLAG_IDS;
            }
        }
        flags
    }

    fn elem_width(&self) -> usize {
        if self.binary32 { 4 } else { 8 }
    }

    pub fn position_len(&self) -> Result<usize, ParseError> {
        (self.n_frames as usize)
            .checked_mul(self.n_atoms as usize)
            .and_then(|n| n.checked_mul(3))
            .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))
    }
}

/// How the mapped pages are made resident before the caller reads them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Prefetch {
    /// One `MADV_POPULATE_READ` per worker, covering that worker's span.
    Span,
    /// `MADV_POPULATE_READ` in queue-sized pieces of each worker's span.
    ChunkPopulate,
    /// `posix_fadvise(POSIX_FADV_WILLNEED)` of the next queue-sized piece
    /// on a private file descriptor, issued before the caller reads.
    ChunkWillneed,
    /// Will-need the next piece, then `MADV_POPULATE_READ` the current one.
    Hybrid,
}

/// Limits read from the block queue that holds `path`.
///
/// `max_request` is `max_sectors_kb` times 1024, the largest request that
/// queue accepts
/// (<https://docs.kernel.org/admin-guide/abi-stable.html#abi-sys-block-disk-queue-max-sectors-kb>).
/// `nr_requests` is how many requests the queue can hold
/// (<https://docs.kernel.org/admin-guide/abi-stable.html#abi-sys-block-disk-queue-nr-requests>).
/// `read_ahead` is `read_ahead_kb`
/// times 1024, the kernel readahead window. A partition is walked to its
/// parent disk, which is the sysfs node that holds `queue/`. A missing
/// queue file yields the page size, the unit `madvise` accepts, and a
/// missing `nr_requests` yields 1. `rotational` is recorded and does not
/// select the plan.
#[derive(Debug, Clone, Copy)]
pub struct QueueLimits {
    pub page: usize,
    pub logical_block: usize,
    pub max_request: usize,
    pub nr_requests: usize,
    pub read_ahead: usize,
    /// Hardware queues. blk-mq applies `nr_requests` to each one.
    pub nr_hw_queues: usize,
    /// `queue/rotational` is 1 when the queue file says so.
    /// The flag is recorded. It does not select the read plan.
    pub rotational: bool,
}

impl QueueLimits {
    /// Page-sized stand-in used when the file has no block queue.
    ///
    /// btrfs, tmpfs, overlayfs and NFS have no `queue/` directory.
    /// The page is the unit `madvise` accepts, so one request of one
    /// page is the stand-in.
    pub fn page_default(page: usize) -> Self {
        Self {
            page,
            logical_block: page,
            max_request: page,
            nr_requests: 1,
            read_ahead: page,
            nr_hw_queues: 1,
            rotational: false,
        }
    }

    pub fn of(path: &Path) -> Result<Self, ParseError> {
        let page = page_size()?;
        #[cfg(target_os = "linux")]
        {
            let file =
                File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
            let dev = std::os::unix::fs::MetadataExt::dev(
                &file
                    .metadata()
                    .map_err(|err| ParseError::ValidationError(err.to_string()))?,
            );
            Ok(Self::from_sysfs(dev, page))
        }
        #[cfg(not(target_os = "linux"))]
        {
            let _ = path;
            Ok(Self::page_default(page))
        }
    }

    #[cfg(target_os = "linux")]
    fn from_sysfs(dev: u64, page: usize) -> Self {
        let num =
            |name: &str| queue_text(dev, name).and_then(|text| text.trim().parse::<usize>().ok());
        let logical = num("logical_block_size").unwrap_or(page).max(1);
        let max_request = num("max_sectors_kb")
            .map(|kb| kb.saturating_mul(1024))
            .unwrap_or(page)
            .max(page);
        let nr_requests = num("nr_requests").unwrap_or(1).max(1);
        let read_ahead = num("read_ahead_kb")
            .map(|kb| kb.saturating_mul(1024))
            .unwrap_or(page)
            .max(page);
        let rotational = num("rotational").unwrap_or(0) != 0;
        Self {
            page,
            logical_block: logical,
            max_request,
            nr_requests,
            read_ahead,
            nr_hw_queues: hw_queue_count(dev),
            rotational,
        }
    }

    /// Bytes one worker submits while the others share the same queue.
    ///
    /// The queue holds `nr_requests` requests of `max_request` bytes.
    /// `workers` share it, so each gets `nr_requests / workers` requests,
    /// or one request when the queue is shorter than the worker count.
    /// The span is at least the kernel readahead window, because a shorter
    /// hint still pulls that window, and it is aligned down to the page.
    pub fn worker_span(&self, workers: usize) -> usize {
        let workers = workers.max(1);
        let requests = (self.nr_requests / workers).max(1);
        let queued = requests.saturating_mul(self.max_request);
        let span = queued.max(self.read_ahead).max(self.page);
        let aligned = span & !(self.page - 1);
        aligned.max(self.page)
    }
}

#[cfg(target_os = "linux")]
pub(crate) fn dev_nums(dev: u64) -> (u64, u64) {
    // glibc `sys/sysmacros.h`, the encoding major(3) documents.
    let major = ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0xfff);
    let minor = ((dev >> 12) & 0xffff_ff00) | (dev & 0xff);
    (major, minor)
}

/// `queue/nr_hw_queues` when the file exists. Otherwise the number of
/// directories under `mq/`, which blk-mq creates, one per hardware queue.
/// A missing tree means one queue.
#[cfg(target_os = "linux")]
fn hw_queue_count(dev: u64) -> usize {
    if let Some(text) = queue_text(dev, "nr_hw_queues")
        && let Ok(count) = text.trim().parse::<usize>()
    {
        return count.max(1);
    }
    let (major, minor) = dev_nums(dev);
    let mut dir = std::path::PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
    if dir.join("partition").is_file() {
        dir.push("..");
    }
    let mq = dir.join("mq");
    let count = std::fs::read_dir(&mq)
        .ok()
        .map(|entries| entries.filter_map(|entry| entry.ok()).count())
        .unwrap_or(0);
    count.max(1)
}

/// Read one queue file. A partition node has `partition` and no `queue`.
/// Its parent is the disk, and that directory holds `queue/`.
/// `Documentation/admin-guide/devices.rst` describes the block sysfs tree.
#[cfg(target_os = "linux")]
fn queue_text(dev: u64, name: &str) -> Option<String> {
    let (major, minor) = dev_nums(dev);
    let dir = std::path::PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
    let own = dir.join("queue").join(name);
    if let Ok(text) = std::fs::read_to_string(&own) {
        return Some(text);
    }
    if dir.join("partition").is_file() {
        let parent = dir.join("..").join("queue").join(name);
        if let Ok(text) = std::fs::read_to_string(&parent) {
            return Some(text);
        }
    }
    None
}

/// Host page size. `madvise` rejects an address that is not a multiple of it.
fn page_size() -> Result<usize, ParseError> {
    #[cfg(unix)]
    let page = {
        let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
        if page <= 0 {
            return Err(ParseError::ValidationError(
                "sysconf(SC_PAGESIZE) failed".into(),
            ));
        }
        page as usize
    };
    #[cfg(windows)]
    let page = {
        // dwPageSize is the DWORD after the 4-byte architecture union in
        // SYSTEM_INFO, on both 32-bit and 64-bit Windows.
        // https://learn.microsoft.com/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
        #[link(name = "kernel32")]
        unsafe extern "system" {
            fn GetSystemInfo(info: *mut std::ffi::c_void);
        }
        let mut info = [0u8; 64];
        unsafe { GetSystemInfo(info.as_mut_ptr().cast()) };
        u32::from_ne_bytes(info[4..8].try_into().unwrap()) as usize
    };
    if !page.is_power_of_two() || page == 0 {
        return Err(ParseError::ValidationError(
            "the host page size is not a power of two".into(),
        ));
    }
    Ok(page)
}

fn header_fields(header: &ConBinHeader, payload_off: u64) -> [u8; FIELD_BYTES] {
    let mut out = [0u8; FIELD_BYTES];
    out[..8].copy_from_slice(MAGIC);
    out[8..12].copy_from_slice(&header.version.to_le_bytes());
    out[12..16].copy_from_slice(&header.flags().to_le_bytes());
    out[16..24].copy_from_slice(&header.n_frames.to_le_bytes());
    out[24..32].copy_from_slice(&header.n_atoms.to_le_bytes());
    out[32..40].copy_from_slice(&payload_off.to_le_bytes());
    out
}

fn parse_fields(bytes: &[u8]) -> Result<(ConBinHeader, u64), ParseError> {
    if bytes.len() < FIELD_BYTES || &bytes[..8] != MAGIC {
        return Err(ParseError::ValidationError(
            "CON-bin header is not CONBIN01".into(),
        ));
    }
    let version = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
    if version != VERSION_1 && version != VERSION_2 {
        return Err(ParseError::ValidationError(format!(
            "CON-bin version {version} is not {VERSION_1} or {VERSION_2}"
        )));
    }
    let flags = u32::from_le_bytes(bytes[12..16].try_into().unwrap());
    let offset = u64::from_le_bytes(bytes[32..40].try_into().unwrap());
    let v2 = version >= VERSION_2;
    Ok((
        ConBinHeader {
            version,
            n_frames: u64::from_le_bytes(bytes[16..24].try_into().unwrap()),
            n_atoms: u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
            binary32: flags & FLAG_F32 != 0,
            velocities: flags & FLAG_VELOCITY != 0,
            forces: v2 && flags & FLAG_FORCE != 0,
            masses: v2 && flags & FLAG_MASS != 0,
            fixed: v2 && flags & FLAG_FIXED != 0,
            cell: v2 && flags & FLAG_CELL != 0,
            atom_ids: v2 && flags & FLAG_IDS != 0,
        },
        offset,
    ))
}

/// Payload start stored in the header. Any 8-byte alignment inside the
/// file is accepted, so a file written on a 4 KiB host still opens when
/// the host page is 16 KiB or 64 KiB. An offset of 0 is not a stand-in
/// for the host page.
fn checked_payload_offset(stored: u64, file_len: usize) -> Result<usize, ParseError> {
    let off = usize::try_from(stored)
        .map_err(|_| ParseError::ValidationError("CON-bin payload offset does not fit".into()))?;
    if off < FIELD_BYTES || off > file_len || off % 8 != 0 {
        return Err(ParseError::ValidationError(
            "CON-bin payload offset is not an 8-byte aligned address inside the file".into(),
        ));
    }
    Ok(off)
}

#[derive(Clone, Copy)]
struct F64Payload {
    offset: usize,
    end: usize,
}

/// Binary64 columns with a velocity run. Binary32 and a missing velocity
/// run are errors: `sum_mapped` reads those two binary64 runs.
fn f64_payload(header_bytes: &[u8], file_len: usize) -> Result<F64Payload, ParseError> {
    let (header, stored) = parse_fields(header_bytes)?;
    if header.binary32 {
        return Err(ParseError::ValidationError(
            "CON-bin file is binary32; sum_mapped reads binary64".into(),
        ));
    }
    if !header.velocities {
        return Err(ParseError::ValidationError(
            "CON-bin file has no velocity run".into(),
        ));
    }
    let offset = checked_payload_offset(stored, file_len)?;
    let values = header
        .position_len()?
        .checked_mul(2)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
    let nbytes = values
        .checked_mul(8)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
    let end = offset
        .checked_add(nbytes)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
    if end > file_len {
        return Err(ParseError::IncompleteFrame);
    }
    Ok(F64Payload { offset, end })
}

/// A mapped CON-bin. The position run and the velocity run are the file.
pub struct ConBinMap {
    /// `MAP_PRIVATE` copy-on-write (`MmapOptions::map_copy`). A store copies
    /// the page and does not write the file.
    pub map: memmap2::MmapMut,
    pub header: ConBinHeader,
    pub payload_off: usize,
}

impl ConBinMap {
    pub fn positions_f64(&self) -> Result<&[f64], ParseError> {
        self.run(std::mem::size_of::<f64>(), 0)
    }

    pub fn positions_f64_mut(&mut self) -> Result<&mut [f64], ParseError> {
        self.run_mut(std::mem::size_of::<f64>(), 0)
    }

    pub fn velocities_f64(&self) -> Result<&[f64], ParseError> {
        let n = self.header.position_len()?;
        self.run(std::mem::size_of::<f64>(), n)
    }

    pub fn positions_f32(&self) -> Result<&[f32], ParseError> {
        self.run(std::mem::size_of::<f32>(), 0)
    }

    pub fn velocities_f32(&self) -> Result<&[f32], ParseError> {
        let n = self.header.position_len()?;
        self.run(std::mem::size_of::<f32>(), n)
    }

    /// Byte offset of the first section after positions, velocities and forces.
    fn after_motion(&self) -> Result<usize, ParseError> {
        let width = self.header.elem_width();
        let block = self
            .header
            .position_len()?
            .checked_mul(width)
            .ok_or_else(|| {
                ParseError::InvalidCount("CON-bin column byte length overflows".into())
            })?;
        let mut at = self
            .payload_off
            .checked_add(block)
            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
        if self.header.velocities {
            at = at.checked_add(block).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        if self.header.forces {
            at = at.checked_add(block).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        Ok(at)
    }

    fn atoms_per_file(&self) -> Result<usize, ParseError> {
        (self.header.n_frames as usize)
            .checked_mul(self.header.n_atoms as usize)
            .ok_or_else(|| ParseError::InvalidCount("CON-bin atom count overflows".into()))
    }

    pub fn masses_f64(&self) -> Result<Option<&[f64]>, ParseError> {
        if !self.header.masses || self.header.binary32 {
            return Ok(None);
        }
        let n = self.atoms_per_file()?;
        self.view_at(self.after_motion()?, n).map(Some)
    }

    /// The `(frames, 6)` cell column of a binary64 file, `a b c alpha beta
    /// gamma` per frame, or `None` when the file has none or is binary32.
    ///
    /// # Errors
    ///
    /// [`ParseError::NonFiniteValue`] naming the field (`cell[i]`) and the
    /// frame when the column holds a NaN or an infinity.
    pub fn cell_f64(&self) -> Result<Option<&[f64]>, ParseError> {
        if !self.header.cell || self.header.binary32 {
            return Ok(None);
        }
        let mut at = self.after_motion()?;
        if self.header.masses {
            let n = self
                .atoms_per_file()?
                .checked_mul(8)
                .ok_or_else(|| ParseError::InvalidCount("CON-bin mass bytes overflow".into()))?;
            at = at.checked_add(n).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        let n = (self.header.n_frames as usize)
            .checked_mul(6)
            .ok_or_else(|| ParseError::InvalidCount("CON-bin cell length overflows".into()))?;
        let cells = self.view_at::<f64>(at, n)?;
        // The cell column is six numbers a frame, read once here. A NaN or
        // an infinity is stored bit for bit in the file, so it is named
        // before the caller sees the slice.
        crate::types::check_cell_rows(cells)?;
        Ok(Some(cells))
    }

    pub fn atom_ids(&self) -> Result<Option<&[u64]>, ParseError> {
        if !self.header.atom_ids {
            return Ok(None);
        }
        self.view_at(self.ids_off()?, self.atoms_per_file()?)
            .map(Some)
    }

    pub fn fixed_masks(&self) -> Result<Option<&[u8]>, ParseError> {
        if !self.header.fixed {
            return Ok(None);
        }
        let mut at = self.ids_off()?;
        if self.header.atom_ids {
            let n = self
                .atoms_per_file()?
                .checked_mul(8)
                .ok_or_else(|| ParseError::InvalidCount("CON-bin id bytes overflow".into()))?;
            at = at.checked_add(n).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        self.view_at(at, self.atoms_per_file()?).map(Some)
    }

    fn ids_off(&self) -> Result<usize, ParseError> {
        let mut at = self.after_motion()?;
        let width = self.header.elem_width();
        if self.header.masses {
            let n = self
                .atoms_per_file()?
                .checked_mul(width)
                .ok_or_else(|| ParseError::InvalidCount("CON-bin mass bytes overflow".into()))?;
            at = at.checked_add(n).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        if self.header.cell {
            let n = (self.header.n_frames as usize)
                .checked_mul(6)
                .and_then(|n| n.checked_mul(width))
                .ok_or_else(|| ParseError::InvalidCount("CON-bin cell bytes overflow".into()))?;
            at = at.checked_add(n).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin payload offset overflows".into())
            })?;
        }
        Ok(at)
    }

    fn view_at<T>(&self, start: usize, n: usize) -> Result<&[T], ParseError> {
        let nbytes = n.checked_mul(std::mem::size_of::<T>()).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column byte length overflows".into())
        })?;
        let end = start.checked_add(nbytes).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column extends past the file".into())
        })?;
        if end > self.map.len() {
            return Err(ParseError::IncompleteFrame);
        }
        let bytes = &self.map[start..end];
        if bytes.as_ptr().align_offset(std::mem::align_of::<T>()) != 0 {
            return Err(ParseError::ValidationError(
                "CON-bin payload is not aligned for its element type".into(),
            ));
        }
        Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<T>(), n) })
    }

    fn run<T>(&self, width: usize, column: usize) -> Result<&[T], ParseError> {
        let n = self.header.position_len()?;
        let start = self
            .payload_off
            .checked_add(column.checked_mul(width).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin column byte length overflows".into())
            })?)
            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
        let nbytes = n.checked_mul(width).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column byte length overflows".into())
        })?;
        let end = start.checked_add(nbytes).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column extends past the file".into())
        })?;
        if end > self.map.len() {
            return Err(ParseError::IncompleteFrame);
        }
        let bytes = &self.map[start..end];
        if !cfg!(target_endian = "little") {
            return Err(ParseError::ValidationError(
                "CON-bin is little-endian; this host cannot view it in place".into(),
            ));
        }
        if bytes.as_ptr().align_offset(std::mem::align_of::<T>()) != 0 {
            return Err(ParseError::ValidationError(
                "CON-bin payload is not aligned for its element type".into(),
            ));
        }
        // SAFETY: `bytes` is inside the map, its length is a multiple of `T`,
        // and the pointer is aligned for `T`. The file is little-endian and
        // the host is little-endian, so the bit pattern is the value.
        // The map stays borrowed for the returned slice.
        Ok(unsafe { std::slice::from_raw_parts(bytes.as_ptr().cast::<T>(), n) })
    }

    fn run_mut<T>(&mut self, width: usize, column: usize) -> Result<&mut [T], ParseError> {
        let n = self.header.position_len()?;
        let start = self
            .payload_off
            .checked_add(column.checked_mul(width).ok_or_else(|| {
                ParseError::InvalidCount("CON-bin column byte length overflows".into())
            })?)
            .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
        let nbytes = n.checked_mul(width).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column byte length overflows".into())
        })?;
        let end = start.checked_add(nbytes).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column extends past the file".into())
        })?;
        if end > self.map.len() {
            return Err(ParseError::IncompleteFrame);
        }
        if !cfg!(target_endian = "little") {
            return Err(ParseError::ValidationError(
                "CON-bin is little-endian; this host cannot view it in place".into(),
            ));
        }
        let ptr = self.map[start..end].as_mut_ptr();
        if ptr.align_offset(std::mem::align_of::<T>()) != 0 {
            return Err(ParseError::ValidationError(
                "CON-bin payload is not aligned for its element type".into(),
            ));
        }
        // SAFETY: same alignment and length rules as `run`. The map is
        // `MAP_PRIVATE`, so stores copy a page and do not write the file.
        Ok(unsafe { std::slice::from_raw_parts_mut(ptr.cast::<T>(), n) })
    }
}

/// Sum both binary64 columns of `path`.
///
/// The default is one `readahead` stream.
/// Two sessions on one boot compared one stream with a stream per span.
/// Neither plan won at every thread count in both.
/// The host cache was not controlled.
/// The default stays one stream, the simpler plan.
/// `nr_requests` is the depth of each hardware queue (`nr_hw_queues`
/// of them, blk-mq), not one device-wide pool.
/// Workers sum a piece after that piece is faulted in, and the piece
/// sums are added in file order. The header's payload offset, length
/// and dtype select the bytes. Binary32 and a missing velocity run are
/// errors. Other platforms map the file and sum it with no `readahead`.
pub fn sum_mapped(path: &Path, threads: usize) -> Result<f64, ParseError> {
    #[cfg(target_os = "linux")]
    {
        let limits = QueueLimits::of(path)?;
        sequential_resident_sum(path, threads.max(1), &limits)
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = threads;
        plain_sum(path)
    }
}

#[cfg(not(target_os = "linux"))]
fn plain_sum(path: &Path) -> Result<f64, ParseError> {
    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let map = unsafe { memmap2::Mmap::map(&file) }
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    if map.len() < FIELD_BYTES {
        return Err(ParseError::ValidationError(
            "CON-bin header is not CONBIN01".into(),
        ));
    }
    let payload = f64_payload(&map[..FIELD_BYTES], map.len())?;
    if !cfg!(target_endian = "little") {
        return Err(ParseError::ValidationError(
            "CON-bin is little-endian; this host cannot view it in place".into(),
        ));
    }
    let bytes = &map[payload.offset..payload.end];
    let ptr = bytes.as_ptr();
    if ptr.align_offset(std::mem::align_of::<f64>()) != 0 {
        return Err(ParseError::ValidationError(
            "CON-bin payload is not aligned for its element type".into(),
        ));
    }
    let data = unsafe { std::slice::from_raw_parts(ptr.cast::<f64>(), bytes.len() / 8) };
    Ok(data.iter().copied().sum())
}

#[cfg(target_os = "linux")]
fn sequential_resident_sum(
    path: &Path,
    threads: usize,
    limits: &QueueLimits,
) -> Result<f64, ParseError> {
    let owned = open_map(path)?;
    let page = limits.page;
    let len = owned.len;
    let base = owned.ptr as usize;
    let header =
        unsafe { std::slice::from_raw_parts(owned.ptr.cast::<u8>(), FIELD_BYTES.min(len)) };
    let payload = f64_payload(header, len)?;
    let request = (limits.max_request & !(page - 1)).max(page);
    let pieces = piece_list(0, len, request);
    if pages_all_resident(owned.ptr, len, page)? {
        return Ok(sum_pieces_in_order(
            base,
            payload.offset,
            payload.end,
            threads,
            &pieces,
        ));
    }
    // One stream fills the read side of the queue.
    let depth = limits.nr_requests.max(1);
    let (tx, rx) = std::sync::mpsc::sync_channel::<usize>(depth);
    let (err_tx, err_rx) = std::sync::mpsc::channel::<String>();
    let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));
    let addr = owned.ptr as usize;
    let found = std::thread::scope(|scope| {
        let queued = pieces.clone();
        scope.spawn(move || {
            let fd = match File::open(path) {
                Ok(fd) => fd,
                Err(err) => {
                    let _ = err_tx.send(err.to_string());
                    return;
                }
            };
            // Keep `depth` requests in flight. Submit the next piece only
            // after the oldest one has been waited on, so the count does not
            // become depth + 1.
            let mut submitted = 0usize;
            while submitted < depth.min(queued.len()) {
                if let Err(err) = advise_readahead(&fd, queued[submitted].0, queued[submitted].1) {
                    let _ = err_tx.send(err);
                    return;
                }
                submitted += 1;
            }
            for i in 0..queued.len() {
                let (off, n) = queued[i];
                if let Err(err) = wait_resident(addr, off, n, page) {
                    let _ = err_tx.send(err);
                    return;
                }
                let _ = tx.send(i);
                if submitted < queued.len() {
                    if let Err(err) =
                        advise_readahead(&fd, queued[submitted].0, queued[submitted].1)
                    {
                        let _ = err_tx.send(err);
                        return;
                    }
                    submitted += 1;
                }
            }
        });
        let slots = std::sync::Arc::new(std::sync::Mutex::new(vec![0.0f64; pieces.len()]));
        let mut handles = Vec::with_capacity(threads);
        for _ in 0..threads {
            let rx = std::sync::Arc::clone(&rx);
            let slots = std::sync::Arc::clone(&slots);
            let pieces = pieces.clone();
            handles.push(scope.spawn(move || {
                loop {
                    let msg = rx.lock().expect("piece queue").recv();
                    let Ok(index) = msg else { break };
                    let (off, n) = pieces[index];
                    let part = sum_range(base, off, off + n, payload.offset, payload.end);
                    slots.lock().expect("piece sums")[index] = part;
                }
            }));
        }
        for handle in handles {
            handle.join().expect("column sum");
        }
        let slots = slots.lock().expect("piece sums");
        slots.iter().copied().sum::<f64>()
    });
    if let Ok(err) = err_rx.try_recv() {
        return Err(ParseError::ValidationError(err));
    }
    Ok(found)
}

/// One `readahead` stream per worker, each over a disjoint span.
///
/// The piece is `max_sectors_kb` times 1024. `nr_requests` is the depth
/// of each hardware queue, so each worker keeps
/// `max(1, nr_requests / workers)` pieces in flight.
/// Two sessions on one boot compared one stream with a stream per span.
/// Neither plan won at every thread count in both.
/// The host cache was not controlled.
/// The default stays one stream, the simpler plan.
#[cfg(target_os = "linux")]
pub fn sum_split_streams(path: &Path, threads: usize) -> Result<f64, ParseError> {
    let limits = QueueLimits::of(path)?;
    split_stream_sum(path, threads.max(1), &limits)
}

#[cfg(not(target_os = "linux"))]
pub fn sum_split_streams(path: &Path, threads: usize) -> Result<f64, ParseError> {
    let _ = threads;
    plain_sum(path)
}

#[cfg(target_os = "linux")]
fn split_stream_sum(path: &Path, threads: usize, limits: &QueueLimits) -> Result<f64, ParseError> {
    let owned = open_map(path)?;
    let page = limits.page;
    let len = owned.len;
    let base = owned.ptr as usize;
    let header =
        unsafe { std::slice::from_raw_parts(owned.ptr.cast::<u8>(), FIELD_BYTES.min(len)) };
    let payload = f64_payload(header, len)?;
    let request = (limits.max_request & !(page - 1)).max(page);
    let ranges = worker_ranges(len, threads, page);
    if pages_all_resident(owned.ptr, len, page)? {
        let pieces = piece_list(0, len, request);
        return Ok(sum_pieces_in_order(
            base,
            payload.offset,
            payload.end,
            threads,
            &pieces,
        ));
    }
    let depth = (limits.nr_requests / ranges.len()).max(1);
    let (err_tx, err_rx) = std::sync::mpsc::channel::<String>();
    let sum = std::thread::scope(|scope| {
        let mut handles = Vec::with_capacity(ranges.len());
        for (span, end) in ranges {
            let err_tx = err_tx.clone();
            handles.push(scope.spawn(move || {
                match stream_one_span(
                    path,
                    SpanGeom {
                        base,
                        span,
                        end,
                        page,
                        payload_off: payload.offset,
                        payload_end: payload.end,
                        request,
                        depth,
                    },
                ) {
                    Ok(part) => part,
                    Err(err) => {
                        let _ = err_tx.send(err);
                        0.0
                    }
                }
            }));
        }
        drop(err_tx);
        handles
            .into_iter()
            .map(|handle| handle.join().expect("split stream"))
            .sum::<f64>()
    });
    if let Ok(err) = err_rx.try_recv() {
        return Err(ParseError::ValidationError(err));
    }
    Ok(sum)
}

#[cfg(target_os = "linux")]
struct SpanGeom {
    base: usize,
    span: usize,
    end: usize,
    page: usize,
    payload_off: usize,
    payload_end: usize,
    request: usize,
    depth: usize,
}

#[cfg(target_os = "linux")]
fn stream_one_span(path: &Path, geom: SpanGeom) -> Result<f64, String> {
    let SpanGeom {
        base,
        span,
        end,
        page,
        payload_off,
        payload_end,
        request,
        depth,
    } = geom;
    let fd = File::open(path).map_err(|err| err.to_string())?;
    let pieces = piece_list(span, end, request);
    let depth = depth.max(1);
    let mut next_submit = 0usize;
    let mut next_sum = 0usize;
    let mut acc = 0.0f64;
    while next_sum < pieces.len() {
        while next_submit < pieces.len() && next_submit - next_sum < depth {
            let (off, n) = pieces[next_submit];
            advise_readahead(&fd, off, n)?;
            next_submit += 1;
        }
        let (off, n) = pieces[next_sum];
        wait_resident(base, off, n, page)?;
        acc += sum_range(base, off, off + n, payload_off, payload_end);
        next_sum += 1;
    }
    Ok(acc)
}

#[cfg(target_os = "linux")]
fn sum_pieces_in_order(
    base: usize,
    payload_off: usize,
    payload_end: usize,
    threads: usize,
    pieces: &[(usize, usize)],
) -> f64 {
    let mut slots = vec![0.0f64; pieces.len()];
    let next = std::sync::atomic::AtomicUsize::new(0);
    std::thread::scope(|scope| {
        let mut handles = Vec::with_capacity(threads);
        for _ in 0..threads {
            handles.push(scope.spawn(|| {
                let mut local = Vec::new();
                loop {
                    let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    if index >= pieces.len() {
                        break;
                    }
                    let (off, n) = pieces[index];
                    local.push((
                        index,
                        sum_range(base, off, off + n, payload_off, payload_end),
                    ));
                }
                local
            }));
        }
        for handle in handles {
            for (index, part) in handle.join().expect("column sum") {
                slots[index] = part;
            }
        }
    });
    slots.iter().copied().sum()
}

#[cfg(target_os = "linux")]
fn pages_all_resident(ptr: *mut libc::c_void, len: usize, page: usize) -> Result<bool, ParseError> {
    if len == 0 {
        return Ok(true);
    }
    let pages = len.div_ceil(page);
    let mut vec = vec![0u8; pages];
    let rc = unsafe { libc::mincore(ptr, len, vec.as_mut_ptr()) };
    if rc != 0 {
        return Err(ParseError::ValidationError(
            std::io::Error::last_os_error().to_string(),
        ));
    }
    Ok(vec.iter().all(|byte| byte & 1 == 1))
}

/// `Ok` means the range is resident. `Err` is the errno from `madvise`.
/// Only `EINVAL` means this kernel has no `MADV_POPULATE_READ`, so the
/// caller may fault the pages itself. `EFAULT`, `EIO`, `EHWPOISON` and
/// `ENOMEM` are failures (man 2 madvise).
#[cfg(target_os = "linux")]
fn populate_followup(code: i32) -> Result<(), i32> {
    if code == libc::EINVAL {
        Ok(())
    } else {
        Err(code)
    }
}

#[cfg(target_os = "linux")]
fn touch_pages(addr: usize, off: usize, len: usize, page: usize) {
    let pages = len.div_ceil(page);
    for index in 0..pages {
        let at = index * page;
        if at >= len {
            break;
        }
        let byte = (addr + off + at) as *const u8;
        std::hint::black_box(unsafe { std::ptr::read_volatile(byte) });
    }
}

#[cfg(target_os = "linux")]
fn wait_resident(addr: usize, off: usize, len: usize, page: usize) -> Result<(), String> {
    // One readahead has already been submitted. MADV_POPULATE_READ (Linux
    // 5.14) faults this range and waits. The address is checked before the
    // call, so EINVAL is the old-kernel miss and one byte of each page is
    // read. EAGAIN is a transient kernel resource (man 2 madvise) and is
    // retried once per page of the range. Any other errno is returned.
    if page == 0 || !(addr + off).is_multiple_of(page) {
        return Err("madvise address is not page-aligned".into());
    }
    let start = (addr + off) as *mut libc::c_void;
    let pages = len.div_ceil(page).max(1);
    let mut tried = 0usize;
    loop {
        let rc = unsafe { libc::madvise(start, len, libc::MADV_POPULATE_READ) };
        if rc == 0 {
            return Ok(());
        }
        let err = std::io::Error::last_os_error();
        let code = err.raw_os_error().unwrap_or(0);
        if code == libc::EAGAIN && tried < pages {
            tried += 1;
            continue;
        }
        if populate_followup(code).is_ok() {
            touch_pages(addr, off, len, page);
            return Ok(());
        }
        return Err(err.to_string());
    }
}

#[cfg(target_os = "linux")]
fn advise_readahead(file: &File, off: usize, len: usize) -> Result<(), String> {
    let rc = unsafe { libc::readahead(file.as_raw_fd(), off as i64, len) };
    if rc != 0 {
        Err(std::io::Error::last_os_error().to_string())
    } else {
        Ok(())
    }
}

#[cfg(target_os = "linux")]
struct OwnedMap {
    ptr: *mut libc::c_void,
    len: usize,
}

#[cfg(target_os = "linux")]
impl Drop for OwnedMap {
    fn drop(&mut self) {
        unsafe { libc::munmap(self.ptr, self.len) };
    }
}

#[cfg(target_os = "linux")]
fn open_map(path: &Path) -> Result<OwnedMap, ParseError> {
    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let len = file
        .metadata()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?
        .len() as usize;
    let ptr = unsafe {
        libc::mmap(
            std::ptr::null_mut(),
            len,
            libc::PROT_READ,
            libc::MAP_PRIVATE,
            file.as_raw_fd(),
            0,
        )
    };
    if ptr == libc::MAP_FAILED {
        return Err(ParseError::ValidationError(
            std::io::Error::last_os_error().to_string(),
        ));
    }
    unsafe {
        libc::madvise(ptr, len, libc::MADV_SEQUENTIAL);
        libc::madvise(ptr, len, libc::MADV_HUGEPAGE);
    }
    Ok(OwnedMap { ptr, len })
}

#[cfg(target_os = "linux")]
fn sum_range(base: usize, start: usize, end: usize, payload_off: usize, payload_end: usize) -> f64 {
    let from = start.max(payload_off);
    let to = end.min(payload_end);
    if to <= from {
        return 0.0;
    }
    let data = unsafe { std::slice::from_raw_parts((base + from) as *const f64, (to - from) / 8) };
    let mut acc = 0.0f64;
    for &value in data {
        acc += value;
    }
    acc
}

/// Map `path` and fault the pages in before returning.
///
/// The map is `MAP_PRIVATE` and writable. A store to a page copies that
/// page. It does not modify the file. `mmap(2)` leaves it unspecified
/// whether a later write to the file by someone else appears in a page
/// the caller has not stored to. Truncation can raise `SIGBUS`.
///
/// `MADV_SEQUENTIAL` and `MADV_WILLNEED` describe one forward pass.
/// `MADV_HUGEPAGE` is the request used when transparent huge pages are in
/// `madvise` mode (`CONFIG_TRANSPARENT_HUGEPAGE_MADVISE`). File-backed
/// huge pages also need `CONFIG_READ_ONLY_THP_FOR_FS`
/// (Documentation/admin-guide/mm/transhuge.rst). This kernel's
/// `/proc/config.gz` has that option unset, and a mapped read showed
/// `FilePmdMapped` 0. The advice stays, because it is the switch the
/// kernel documents, and it is a no-op without that option.
/// `MADV_POPULATE_READ` (Linux 5.14) is the span hint. A failure, including
/// `EINVAL` from a kernel before 5.14, leaves the mapping in place and one
/// byte of each page is read, so the caller still sees the file.
/// `MAP_POPULATE` hides errors and cannot be split across the caller's
/// threads after `mmap` returns. When `mmap` itself fails, the file is
/// read into a private mapping and the accessors return those bytes.
/// `threads` workers fault page-aligned spans. A file shorter than one
/// page per worker stays on one worker. The page is `sysconf(SC_PAGESIZE)`.
pub fn map_file(path: &Path, threads: usize) -> Result<ConBinMap, ParseError> {
    map_file_with(path, threads, Prefetch::Span)
}

/// [`map_file`] with an explicit prefetch. The benchmark pairs these.
pub fn map_file_with(
    path: &Path,
    threads: usize,
    prefetch: Prefetch,
) -> Result<ConBinMap, ParseError> {
    // A crash-safe write publishes by rename. An open taken before that
    // rename still names the previous inode, so the map of that open is
    // not the file now at `path`. If the path changes while this call
    // holds the first mapping, map the published file instead.
    let mapped = map_current(path, threads, prefetch)?;
    #[cfg(unix)]
    if path_identity(path) != Some(mapped.0) {
        return Ok(map_current(path, threads, prefetch)?.1);
    }
    Ok(mapped.1)
}

/// `(device, inode)` of `path`, when the path exists.
#[cfg(unix)]
fn path_identity(path: &Path) -> Option<(u64, u64)> {
    let meta = std::fs::metadata(path).ok()?;
    Some(file_identity_meta(&meta))
}

#[cfg(unix)]
fn file_identity(file: &File) -> Result<(u64, u64), ParseError> {
    let meta = file
        .metadata()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    Ok(file_identity_meta(&meta))
}

#[cfg(unix)]
fn file_identity_meta(meta: &std::fs::Metadata) -> (u64, u64) {
    use std::os::unix::fs::MetadataExt;
    (meta.dev(), meta.ino())
}

fn map_current(
    path: &Path,
    threads: usize,
    prefetch: Prefetch,
) -> Result<((u64, u64), ConBinMap), ParseError> {
    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    #[cfg(unix)]
    let identity = file_identity(&file)?;
    #[cfg(not(unix))]
    let identity = (0, 0);
    // MAP_PRIVATE, PROT_READ|PROT_WRITE. Writes copy the page.
    // When `mmap` itself fails, the file is read into a private mapping
    // that holds the same bytes, so the accessors return the same values.
    let map = map_copy_or_read(&file)?;
    if map.len() < FIELD_BYTES {
        return Err(ParseError::ValidationError(
            "CON-bin header is not CONBIN01".into(),
        ));
    }
    let (header, offset) = parse_fields(&map[..FIELD_BYTES])?;
    let page = page_size()?;
    let payload_off = checked_payload_offset(offset, map.len())?;
    fault_in(path, &map, threads, page, prefetch)?;
    Ok((
        identity,
        ConBinMap {
            map,
            header,
            payload_off,
        },
    ))
}

#[cfg(test)]
thread_local! {
    static POPULATE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    static MAP_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// File-backed private map, or an anonymous map filled by `read` when `mmap` fails.
fn map_copy_or_read(file: &File) -> Result<memmap2::MmapMut, ParseError> {
    #[cfg(test)]
    if MAP_FAILS.with(|flag| flag.get()) {
        return private_copy(file);
    }
    match unsafe { memmap2::MmapOptions::new().map_copy(file) } {
        Ok(map) => Ok(map),
        Err(_) => private_copy(file),
    }
}

fn private_copy(file: &File) -> Result<memmap2::MmapMut, ParseError> {
    let len = usize::try_from(
        file.metadata()
            .map_err(|err| ParseError::ValidationError(err.to_string()))?
            .len(),
    )
    .map_err(|_| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
    if len < FIELD_BYTES {
        return Err(ParseError::ValidationError(
            "CON-bin header is not CONBIN01".into(),
        ));
    }
    let mut anon = memmap2::MmapOptions::new()
        .len(len)
        .map_anon()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let mut reader = file
        .try_clone()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    reader
        .read_exact(&mut anon[..])
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    Ok(anon)
}

fn touch_mapped_pages(map: &memmap2::MmapMut, page: usize) {
    let page = page.max(1);
    for chunk in map.chunks(page) {
        std::hint::black_box(chunk.first().copied());
    }
}

fn fault_in(
    path: &Path,
    map: &memmap2::MmapMut,
    threads: usize,
    page: usize,
    prefetch: Prefetch,
) -> Result<(), ParseError> {
    #[cfg(unix)]
    let _ = map.advise(memmap2::Advice::Sequential);
    #[cfg(target_os = "linux")]
    let _ = map.advise(memmap2::Advice::HugePage);
    #[cfg(target_os = "linux")]
    {
        match prefetch {
            Prefetch::Span => {
                let _ = map.advise(memmap2::Advice::WillNeed);
                // `MADV_POPULATE_READ` is a hint. Kernels before 5.14 return
                // `EINVAL`, and some filesystems return other errors. A failed
                // hint leaves the mapping in place; the pages are touched so
                // the caller still reads the same values.
                let hint_failed = {
                    #[cfg(test)]
                    {
                        POPULATE_FAILS.with(|flag| flag.get())
                    }
                    #[cfg(not(test))]
                    {
                        false
                    }
                };
                if hint_failed
                    || advise_spans(map, memmap2::Advice::PopulateRead, threads, page).is_err()
                {
                    touch_mapped_pages(map, page);
                }
            }
            Prefetch::ChunkPopulate => {
                let window = QueueLimits::of(path)?.worker_span(threads);
                chunk_each(map, threads, page, window, ChunkOp::Populate)?;
            }
            Prefetch::ChunkWillneed => {
                let window = QueueLimits::of(path)?.worker_span(threads);
                chunk_each(map, threads, page, window, ChunkOp::Willneed { path })?;
            }
            Prefetch::Hybrid => {
                let window = QueueLimits::of(path)?.worker_span(threads);
                chunk_each(map, threads, page, window, ChunkOp::Hybrid { path })?;
            }
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (path, threads, prefetch);
        for chunk in map.chunks(page) {
            std::hint::black_box(chunk.first().copied());
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
enum ChunkOp<'a> {
    Populate,
    Willneed { path: &'a Path },
    Hybrid { path: &'a Path },
}

#[cfg(target_os = "linux")]
fn chunk_each(
    map: &memmap2::MmapMut,
    threads: usize,
    page: usize,
    window: usize,
    op: ChunkOp<'_>,
) -> Result<(), ParseError> {
    let ranges = worker_ranges(map.len(), threads, page);
    let shared = match op {
        ChunkOp::Populate => ChunkOp::Populate,
        ChunkOp::Willneed { path } => ChunkOp::Willneed { path },
        ChunkOp::Hybrid { path } => ChunkOp::Hybrid { path },
    };
    std::thread::scope(|scope| {
        let mut handles = Vec::with_capacity(ranges.len());
        for (start, end) in ranges {
            let op = match shared {
                ChunkOp::Populate => ChunkOp::Populate,
                ChunkOp::Willneed { path } => ChunkOp::Willneed { path },
                ChunkOp::Hybrid { path } => ChunkOp::Hybrid { path },
            };
            handles.push(scope.spawn(move || chunk_worker(map, start, end, window, page, op)));
        }
        handles.into_iter().try_for_each(|handle| {
            handle.join().unwrap_or_else(|_| {
                Err(ParseError::ValidationError(
                    "CON-bin prefetch thread panicked".into(),
                ))
            })
        })
    })
}

#[cfg(target_os = "linux")]
fn chunk_worker(
    map: &memmap2::MmapMut,
    start: usize,
    end: usize,
    window: usize,
    page: usize,
    op: ChunkOp<'_>,
) -> Result<(), ParseError> {
    let window = window.max(page);
    let pieces = piece_list(start, end, window);
    let fd = match op {
        ChunkOp::Willneed { path } | ChunkOp::Hybrid { path } => {
            Some(File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?)
        }
        ChunkOp::Populate => None,
    };
    match op {
        ChunkOp::Populate => {
            for (off, len) in pieces {
                populate_range(map, off, len)?;
            }
        }
        ChunkOp::Willneed { .. } => {
            let fd = fd.as_ref().expect("willneed opens a descriptor");
            for (off, len) in pieces {
                willneed(fd, off, len)?;
            }
        }
        ChunkOp::Hybrid { .. } => {
            let fd = fd.as_ref().expect("hybrid opens a descriptor");
            if let Some((off, len)) = pieces.first().copied() {
                willneed(fd, off, len)?;
            }
            for i in 0..pieces.len() {
                if let Some((off, len)) = pieces.get(i + 1).copied() {
                    willneed(fd, off, len)?;
                }
                let (off, len) = pieces[i];
                populate_range(map, off, len)?;
            }
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn piece_list(start: usize, end: usize, window: usize) -> Vec<(usize, usize)> {
    let mut pieces = Vec::new();
    let mut off = start;
    while off < end {
        let len = window.min(end - off);
        pieces.push((off, len));
        off += len;
    }
    pieces
}

#[cfg(target_os = "linux")]
fn populate_range(map: &memmap2::MmapMut, off: usize, len: usize) -> Result<(), ParseError> {
    let page = page_size()?;
    wait_resident(map.as_ptr() as usize, off, len, page).map_err(ParseError::ValidationError)
}

#[cfg(target_os = "linux")]
fn willneed(file: &File, off: usize, len: usize) -> Result<(), ParseError> {
    let rc = unsafe {
        libc::posix_fadvise(
            file.as_raw_fd(),
            off as libc::off_t,
            len as libc::off_t,
            libc::POSIX_FADV_WILLNEED,
        )
    };
    if rc != 0 {
        return Err(ParseError::ValidationError(format!(
            "posix_fadvise WILLNEED: {rc}"
        )));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn worker_ranges(len: usize, threads: usize, page: usize) -> Vec<(usize, usize)> {
    if len == 0 {
        return Vec::new();
    }
    let threads = threads.max(1);
    let workers = if len < page.saturating_mul(threads) {
        1
    } else {
        threads
    };
    if workers == 1 {
        return vec![(0, len)];
    }
    let chunk = (len / workers) & !(page - 1);
    let mut ranges = Vec::with_capacity(workers);
    let mut start = 0usize;
    for worker in 0..workers {
        let take = if worker + 1 == workers {
            len - start
        } else {
            chunk
        };
        ranges.push((start, start + take));
        start += take;
    }
    ranges
}

#[cfg(target_os = "linux")]
fn advise_spans(
    map: &memmap2::MmapMut,
    advice: memmap2::Advice,
    threads: usize,
    page: usize,
) -> Result<(), ParseError> {
    let len = map.len();
    if len == 0 {
        return Ok(());
    }
    let threads = threads.max(1);
    let workers = if len < page.saturating_mul(threads) {
        1
    } else {
        threads
    };
    if workers == 1 {
        return map
            .advise(advice)
            .map_err(|err| ParseError::ValidationError(err.to_string()));
    }
    let chunk = (len / workers) & !(page - 1);
    std::thread::scope(|scope| {
        let mut start = 0usize;
        let mut handles = Vec::with_capacity(workers);
        for worker in 0..workers {
            let take = if worker + 1 == workers {
                len - start
            } else {
                chunk
            };
            let off = start;
            start += take;
            handles.push(scope.spawn(move || map.advise_range(advice, off, take)));
        }
        handles.into_iter().try_for_each(|handle| {
            handle
                .join()
                .unwrap_or_else(|_| Err(std::io::Error::other("CON-bin populate thread panicked")))
                .map_err(|err| ParseError::ValidationError(err.to_string()))
        })
    })
}

pub fn read_header(path: &Path) -> Result<ConBinHeader, ParseError> {
    let mut file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let mut bytes = [0u8; FIELD_BYTES];
    file.read_exact(&mut bytes)
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    parse_fields(&bytes).map(|(header, _)| header)
}

fn bytes_of<T>(values: &mut [T]) -> &mut [u8] {
    let len = std::mem::size_of_val(values);
    // SAFETY: `values` is a live slice. The byte view covers exactly those
    // elements and is not used after `values` is borrowed again.
    unsafe { std::slice::from_raw_parts_mut(values.as_mut_ptr().cast::<u8>(), len) }
}

/// Copy a binary64 CON-bin into caller-owned columns. One thread issues the reads.
pub fn read_into(
    path: &Path,
    positions: &mut [f64],
    velocities: Option<&mut [f64]>,
) -> Result<ConBinHeader, ParseError> {
    read_into_threads(path, positions, velocities, 1)
}

/// [`read_into`] with `threads` workers. Each worker reads a page-aligned span.
/// A span shorter than one page stays on one worker.
pub fn read_into_threads(
    path: &Path,
    positions: &mut [f64],
    velocities: Option<&mut [f64]>,
    threads: usize,
) -> Result<ConBinHeader, ParseError> {
    read_columns_into(path, positions, velocities, threads, false)
}

/// Copy both binary64 columns into owned vectors.
///
/// Each vector is `with_capacity`, then `pread` fills `spare_capacity_mut`
/// and `set_len` publishes those slots. The byte view is not a `&mut [f64]`
/// over uninitialised memory. A missing velocity run is an error.
///
/// The header's frame and atom counts are not reserved until both columns
/// fit in the file. A count the file cannot hold is [`ParseError::IncompleteFrame`].
pub fn read_owned_f64(
    path: &Path,
    threads: usize,
) -> Result<(ConBinHeader, Vec<f64>, Vec<f64>), ParseError> {
    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let mut raw = [0u8; FIELD_BYTES];
    (&file)
        .read_exact(&mut raw)
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let (header, offset) = parse_fields(&raw)?;
    if header.binary32 {
        return Err(ParseError::ValidationError(
            "CON-bin file is binary32; use read_into_f32".into(),
        ));
    }
    if !header.velocities {
        return Err(ParseError::ValidationError(
            "CON-bin file has no velocity run".into(),
        ));
    }
    let n = header.position_len()?;
    let column = n
        .checked_mul(std::mem::size_of::<f64>())
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
    let file_len = file
        .metadata()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?
        .len() as usize;
    let pos_off = checked_payload_offset(offset, file_len)?;
    let both = column
        .checked_mul(2)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
    let end = pos_off
        .checked_add(both)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin payload offset overflows".into()))?;
    if end > file_len {
        return Err(ParseError::IncompleteFrame);
    }
    drop(file);
    let mut positions = Vec::<f64>::with_capacity(n);
    let mut velocities = Vec::<f64>::with_capacity(n);
    fill_owned_f64(path, &mut positions, &mut velocities, n, threads)?;
    Ok((header, positions, velocities))
}

#[cfg(unix)]
fn spare_prefix_uninit(buf: &mut Vec<f64>, n: usize) -> &mut [std::mem::MaybeUninit<u8>] {
    let spare = buf.spare_capacity_mut();
    assert!(spare.len() >= n);
    let nbytes = n * std::mem::size_of::<f64>();
    let ptr = spare.as_mut_ptr().cast::<std::mem::MaybeUninit<u8>>();
    // SAFETY: `n` uninitialised f64 slots cover `nbytes` bytes. A
    // `MaybeUninit<u8>` slot may be uninitialised, so this slice does not
    // claim the bytes are initialised. `pread` writes through the raw
    // pointer, then `set_len` publishes the f64 slots.
    unsafe { std::slice::from_raw_parts_mut(ptr, nbytes) }
}

fn fill_owned_f64(
    path: &Path,
    positions: &mut Vec<f64>,
    velocities: &mut Vec<f64>,
    n: usize,
    threads: usize,
) -> Result<(), ParseError> {
    #[cfg(not(unix))]
    {
        let _ = (path, positions, velocities, n, threads);
        return Err(ParseError::ValidationError(
            "CON-bin pread fill requires Unix".into(),
        ));
    }
    #[cfg(unix)]
    {
        let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
        let mut raw = [0u8; FIELD_BYTES];
        (&file)
            .read_exact(&mut raw)
            .map_err(|err| ParseError::ValidationError(err.to_string()))?;
        let (_header, offset) = parse_fields(&raw)?;
        let width = std::mem::size_of::<f64>();
        let expect = n.checked_mul(width).ok_or_else(|| {
            ParseError::InvalidCount("CON-bin column byte length overflows".into())
        })?;
        let page = page_size()?;
        let file_len = file
            .metadata()
            .map_err(|err| ParseError::ValidationError(err.to_string()))?
            .len() as usize;
        let pos_off = checked_payload_offset(offset, file_len)? as u64;
        let fd = file.as_raw_fd();
        {
            let bytes = spare_prefix_uninit(positions, n);
            pread_parallel_uninit(fd, bytes, pos_off, threads, page)?;
        }
        // SAFETY: `pread_parallel_uninit` wrote `n` little-endian f64 values or returned.
        unsafe { positions.set_len(n) };
        decode_le(positions);
        {
            let bytes = spare_prefix_uninit(velocities, n);
            pread_parallel_uninit(fd, bytes, pos_off + expect as u64, threads, page)?;
        }
        unsafe { velocities.set_len(n) };
        decode_le(velocities);
        Ok(())
    }
}

/// Copy a binary32 CON-bin into caller-owned columns. One thread issues the reads.
pub fn read_into_f32(
    path: &Path,
    positions: &mut [f32],
    velocities: Option<&mut [f32]>,
) -> Result<ConBinHeader, ParseError> {
    read_into_f32_threads(path, positions, velocities, 1)
}

/// [`read_into_f32`] with `threads` workers. The split is the same page rule
/// as [`read_into_threads`].
pub fn read_into_f32_threads(
    path: &Path,
    positions: &mut [f32],
    velocities: Option<&mut [f32]>,
    threads: usize,
) -> Result<ConBinHeader, ParseError> {
    read_columns_into(path, positions, velocities, threads, true)
}

fn read_columns_into<T: StoreLe>(
    path: &Path,
    positions: &mut [T],
    velocities: Option<&mut [T]>,
    threads: usize,
    binary32: bool,
) -> Result<ConBinHeader, ParseError> {
    let file = File::open(path).map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let mut raw = [0u8; FIELD_BYTES];
    (&file)
        .read_exact(&mut raw)
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let (header, offset) = parse_fields(&raw)?;
    if header.binary32 != binary32 {
        return Err(ParseError::ValidationError(if binary32 {
            "CON-bin file is binary64; use read_into".into()
        } else {
            "CON-bin file is binary32; use read_into_f32".into()
        }));
    }
    let n = header.position_len()?;
    let width = std::mem::size_of::<T>();
    let expect = n
        .checked_mul(width)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column byte length overflows".into()))?;
    if positions.len() != n {
        return Err(ParseError::InvalidCount(format!(
            "position slice has {} values, the file has {n}",
            positions.len()
        )));
    }
    let page = page_size()?;
    let file_len = file
        .metadata()
        .map_err(|err| ParseError::ValidationError(err.to_string()))?
        .len() as usize;
    let pos_off = checked_payload_offset(offset, file_len)? as u64;
    let pos_bytes = bytes_of(positions);
    if pos_bytes.len() != expect {
        return Err(ParseError::InvalidCount(format!(
            "position slice has {} bytes, the file has {expect}",
            pos_bytes.len()
        )));
    }
    #[cfg(not(unix))]
    {
        let _ = (pos_bytes, pos_off, threads, page, velocities, header);
        return Err(ParseError::ValidationError(
            "CON-bin pread fill requires Unix".into(),
        ));
    }
    #[cfg(unix)]
    {
        let fd = file.as_raw_fd();
        // Sequential advice matches one pass over the payload. WILLNEED is not
        // used here: it starts a second readahead beside the reads themselves.
        // libc exposes posix_fadvise on Linux. macOS has posix_madvise instead.
        #[cfg(target_os = "linux")]
        unsafe {
            libc::posix_fadvise(fd, 0, 0, libc::POSIX_FADV_SEQUENTIAL);
        }
        // Linux read returns at most MAX_RW_COUNT bytes (INT_MAX aligned down to
        // the page, include/linux/fs.h). `pread_all` continues until the span is full.
        pread_parallel(fd, pos_bytes, pos_off, threads, page)?;
        decode_le(positions);
        if header.velocities {
            let Some(vel) = velocities else {
                return Err(ParseError::InvalidCount(
                    "CON-bin has velocities and the caller passed no velocity slice".into(),
                ));
            };
            if vel.len() != n {
                return Err(ParseError::InvalidCount(format!(
                    "velocity slice has {} values, the file has {n}",
                    vel.len()
                )));
            }
            let vel_bytes = bytes_of(vel);
            pread_parallel(fd, vel_bytes, pos_off + expect as u64, threads, page)?;
            decode_le(vel);
        }
        Ok(header)
    }
}

#[cfg(unix)]
fn pread_parallel(
    fd: i32,
    dest: &mut [u8],
    offset: u64,
    threads: usize,
    page: usize,
) -> Result<(), ParseError> {
    let threads = threads.max(1);
    let workers = if dest.len() < page.saturating_mul(threads) {
        1
    } else {
        threads
    };
    if workers == 1 {
        return pread_all(fd, dest, offset);
    }
    let chunk = (dest.len() / workers) & !(page - 1);
    std::thread::scope(|scope| {
        let mut rest = dest;
        let mut off = offset;
        let mut handles = Vec::with_capacity(workers);
        for worker in 0..workers {
            let take = if worker + 1 == workers {
                rest.len()
            } else {
                chunk
            };
            let (head, tail) = rest.split_at_mut(take);
            rest = tail;
            let this = off;
            off += take as u64;
            handles.push(scope.spawn(move || pread_all(fd, head, this)));
        }
        handles
            .into_iter()
            .try_for_each(|handle| handle.join().unwrap_or(Err(ParseError::IncompleteFrame)))
    })
}

#[cfg(unix)]
fn pread_raw(fd: i32, ptr: *mut u8, len: usize, mut offset: u64) -> Result<(), ParseError> {
    let mut done = 0;
    while done < len {
        let n = unsafe { libc::pread(fd, ptr.add(done).cast(), len - done, offset as libc::off_t) };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            // POSIX: EINTR means the call was interrupted before a transfer.
            // Restart the same offset. Rust's `read_at` does the same for
            // `ErrorKind::Interrupted`.
            if err.raw_os_error() == Some(libc::EINTR) {
                continue;
            }
            return Err(ParseError::ValidationError(err.to_string()));
        }
        if n == 0 {
            return Err(ParseError::IncompleteFrame);
        }
        done += n as usize;
        offset += n as u64;
    }
    Ok(())
}

#[cfg(unix)]
fn pread_all(fd: i32, dest: &mut [u8], offset: u64) -> Result<(), ParseError> {
    pread_raw(fd, dest.as_mut_ptr(), dest.len(), offset)
}

#[cfg(unix)]
fn pread_uninit(
    fd: i32,
    dest: &mut [std::mem::MaybeUninit<u8>],
    offset: u64,
) -> Result<(), ParseError> {
    // `as_mut_ptr` of `MaybeUninit<u8>` is the address `pread` may write.
    // The slice type does not require the bytes to be initialised.
    pread_raw(fd, dest.as_mut_ptr().cast::<u8>(), dest.len(), offset)
}

#[cfg(unix)]
fn pread_parallel_uninit(
    fd: i32,
    dest: &mut [std::mem::MaybeUninit<u8>],
    offset: u64,
    threads: usize,
    page: usize,
) -> Result<(), ParseError> {
    let threads = threads.max(1);
    let workers = if dest.len() < page.saturating_mul(threads) {
        1
    } else {
        threads
    };
    if workers == 1 {
        return pread_uninit(fd, dest, offset);
    }
    let chunk = (dest.len() / workers) & !(page - 1);
    std::thread::scope(|scope| {
        let mut rest = dest;
        let mut off = offset;
        let mut handles = Vec::with_capacity(workers);
        for worker in 0..workers {
            let take = if worker + 1 == workers {
                rest.len()
            } else {
                chunk
            };
            let (head, tail) = rest.split_at_mut(take);
            rest = tail;
            let this = off;
            off += take as u64;
            handles.push(scope.spawn(move || pread_uninit(fd, head, this)));
        }
        handles
            .into_iter()
            .try_for_each(|handle| handle.join().unwrap_or(Err(ParseError::IncompleteFrame)))
    })
}

mod sealed_number {
    pub trait Sealed {}
    impl Sealed for f64 {}
    impl Sealed for f32 {}
    impl Sealed for u64 {}
    impl Sealed for u8 {}
}

trait StoreLe: Copy + sealed_number::Sealed {
    fn store_le(self, out: &mut Vec<u8>);
    fn load_le(self) -> Self;
}

impl StoreLe for f64 {
    fn store_le(self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.to_le_bytes());
    }
    fn load_le(self) -> Self {
        f64::from_le_bytes(self.to_ne_bytes())
    }
}

impl StoreLe for f32 {
    fn store_le(self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.to_le_bytes());
    }
    fn load_le(self) -> Self {
        f32::from_le_bytes(self.to_ne_bytes())
    }
}

impl StoreLe for u64 {
    fn store_le(self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.to_le_bytes());
    }
    fn load_le(self) -> Self {
        u64::from_le_bytes(self.to_ne_bytes())
    }
}

impl StoreLe for u8 {
    fn store_le(self, out: &mut Vec<u8>) {
        out.push(self);
    }
    fn load_le(self) -> Self {
        self
    }
}

#[cfg(test)]
fn write_values<T: StoreLe>(file: &mut File, values: &[T]) -> Result<(), ParseError> {
    // A little-endian host already stores the file order. The byte view is
    // the values themselves, so the write does not build a second buffer.
    if cfg!(target_endian = "little") {
        let bytes = unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        };
        return file
            .write_all(bytes)
            .map_err(|err| ParseError::ValidationError(err.to_string()));
    }
    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
    for value in values {
        value.store_le(&mut bytes);
    }
    file.write_all(&bytes)
        .map_err(|err| ParseError::ValidationError(err.to_string()))
}

/// `pread` left little-endian file bytes in `values`. A little-endian host
/// already reads them as the numbers. A big-endian host swaps each one.
fn decode_le<T: StoreLe>(values: &mut [T]) {
    if cfg!(target_endian = "little") {
        return;
    }
    for value in values {
        *value = value.load_le();
    }
}

thread_local! {
    /// One header page per thread. The padding stays zero, and each write
    /// fills the 40-byte prefix in place instead of allocating another page.
    static HEADER_PAGE: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}

fn header_page_bytes(header: &ConBinHeader, page: usize) -> Vec<u8> {
    let mut header_page = vec![0u8; page];
    let prefix = header_fields(header, page as u64);
    header_page[..FIELD_BYTES].copy_from_slice(&prefix);
    header_page
}

/// Little-endian hosts already store values in file order. The slice is
/// that memory. It is not a second buffer.
#[cfg(target_endian = "little")]
fn view_bytes<T: StoreLe>(values: &[T]) -> &[u8] {
    // SAFETY: `T: StoreLe` is sealed to f64, f32, u64 and u8. Each is a
    // plain number with no padding. This function is compiled only on a
    // little-endian host, so those bytes are already the file order. The
    // slice borrows `values` and does not outlive it.
    unsafe {
        std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
    }
}

#[cfg(target_endian = "big")]
fn le_bytes<T: StoreLe>(values: &[T]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
    for value in values {
        value.store_le(&mut bytes);
    }
    bytes
}

/// Preallocate `page + parts` and store the reused header plus every part
/// with one vectored write. A short write is resumed. Nothing is synced:
/// the caller still publishes by rename.
fn write_assembled(
    file: &mut File,
    header: &ConBinHeader,
    page: usize,
    parts: &[&[u8]],
) -> Result<(), ParseError> {
    let payload = parts
        .iter()
        .try_fold(0u64, |sum, part| sum.checked_add(part.len() as u64))
        .ok_or_else(|| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
    let total = (page as u64)
        .checked_add(payload)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin file length overflows".into()))?;
    preallocate(file, total)?;
    HEADER_PAGE.with(|slot| {
        let mut buf = slot.borrow_mut();
        if buf.len() != page {
            buf.clear();
            buf.resize(page, 0);
        }
        let prefix = header_fields(header, page as u64);
        buf[..FIELD_BYTES].copy_from_slice(&prefix);
        let mut iovecs = Vec::with_capacity(1 + parts.len());
        iovecs.push(IoSlice::new(buf.as_slice()));
        for part in parts {
            if !part.is_empty() {
                iovecs.push(IoSlice::new(part));
            }
        }
        let mut rest = iovecs.as_mut_slice();
        while !rest.is_empty() {
            match file.write_vectored(rest) {
                Ok(0) => {
                    return Err(ParseError::ValidationError(
                        "CON-bin write stored no bytes".into(),
                    ));
                }
                Ok(n) => IoSlice::advance_slices(&mut rest, n),
                Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(err) => return Err(ParseError::ValidationError(err.to_string())),
            }
        }
        Ok(())
    })
}

fn publish_assembled(
    path: &Path,
    header: &ConBinHeader,
    page: usize,
    parts: &[&[u8]],
) -> Result<(), ParseError> {
    crate::writer::publish_new(
        path,
        |err| ParseError::ValidationError(err.to_string()),
        |file| write_assembled(file, header, page, parts),
    )
}

#[cfg(test)]
fn write_header_page(
    file: &mut File,
    header: &ConBinHeader,
    page: usize,
) -> Result<(), ParseError> {
    file.write_all(&header_page_bytes(header, page))
        .map_err(|err| ParseError::ValidationError(err.to_string()))
}

/// Store `values` in file order.
#[cfg(feature = "python")]
fn write_le<T: StoreLe>(file: &mut File, values: &[T]) -> Result<(), ParseError> {
    #[cfg(target_endian = "little")]
    let bytes = view_bytes(values);
    #[cfg(target_endian = "big")]
    let bytes = le_bytes(values);
    file.write_all(bytes.as_ref())
        .map_err(|err| ParseError::ValidationError(err.to_string()))
}

#[cfg(all(feature = "python", not(all(unix, target_endian = "little"))))]
pub(crate) fn write_f64_le(file: &mut File, values: &[f64]) -> Result<(), ParseError> {
    write_le(file, values)
}

/// Store the `len` doubles at `ptr` at the file position.
///
/// Only the kernel reads them; no Rust reference to them is formed, so
/// another thread may store into them meanwhile, as with
/// `ndarray.tofile`.
///
/// # Safety
///
/// `ptr` must stay valid for `len` doubles until this returns.
#[cfg(all(feature = "python", unix, target_endian = "little"))]
pub(crate) unsafe fn write_f64_raw(
    file: &File,
    ptr: *const f64,
    len: usize,
) -> Result<(), ParseError> {
    use std::os::fd::AsRawFd;
    let mut at = ptr.cast::<u8>();
    let mut left = len * std::mem::size_of::<f64>();
    while left > 0 {
        let stored = unsafe { libc::write(file.as_raw_fd(), at.cast(), left.min(1 << 30)) };
        if stored < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(ParseError::ValidationError(err.to_string()));
        }
        if stored == 0 {
            return Err(ParseError::ValidationError(
                std::io::Error::from(std::io::ErrorKind::WriteZero).to_string(),
            ));
        }
        at = unsafe { at.add(stored as usize) };
        left -= stored as usize;
    }
    Ok(())
}

/// [`write_f64_columns`] with the binary64 columns handed over in runs.
///
/// The counts name the binary64 columns in payload order: positions,
/// then velocities, masses and cell when present. `emit(column, values,
/// file)` stores that range of that column at the file position, at most
/// `run` values at a time, so the caller decides how memory it does not
/// own reaches the file. The file matches [`write_f64_columns`] of the
/// same values.
#[cfg(feature = "python")]
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_f64_columns_staged(
    path: &Path,
    n_frames: u64,
    n_atoms: u64,
    positions: usize,
    velocities: Option<usize>,
    masses: Option<usize>,
    cell: Option<usize>,
    atom_ids: Option<&[u64]>,
    fixed: Option<&[u8]>,
    run: usize,
    mut emit: impl FnMut(usize, std::ops::Range<usize>, &mut File) -> Result<(), ParseError>,
) -> Result<ConBinHeader, ParseError> {
    let header = f64_columns_header(
        n_frames,
        n_atoms,
        positions,
        velocities,
        masses,
        cell,
        atom_ids.map(<[u64]>::len),
        fixed.map(<[u8]>::len),
    )?;
    let page = page_size()?;
    let mut counts = vec![positions];
    counts.extend(velocities);
    counts.extend(masses);
    counts.extend(cell);
    let overflow = || ParseError::InvalidCount("CON-bin file length overflows".into());
    let values = counts
        .iter()
        .copied()
        .chain(atom_ids.map(<[u64]>::len))
        .try_fold(0u64, |sum, count| sum.checked_add(count as u64))
        .ok_or_else(overflow)?;
    let total = values
        .checked_mul(8)
        .and_then(|bytes| bytes.checked_add(fixed.map_or(0, <[u8]>::len) as u64))
        .and_then(|bytes| bytes.checked_add(page as u64))
        .ok_or_else(overflow)?;
    let run = run.max(1);
    crate::writer::publish_new(
        path,
        |err| ParseError::ValidationError(err.to_string()),
        |file| {
            preallocate(file, total)?;
            file.write_all(&header_page_bytes(&header, page))
                .map_err(|err| ParseError::ValidationError(err.to_string()))?;
            for (column, count) in counts.iter().copied().enumerate() {
                let mut at = 0;
                while at < count {
                    let end = (at + run).min(count);
                    emit(column, at..end, file)?;
                    at = end;
                }
            }
            if let Some(values) = atom_ids {
                write_le(file, values)?;
            }
            if let Some(values) = fixed {
                write_le(file, values)?;
            }
            Ok(())
        },
    )?;
    Ok(header)
}

/// Write version 2 from columns already in memory.
///
/// Positions are required. Velocities, masses, the cell, atom ids and the
/// per-axis fixed mask are stored when the caller passes them. The payload
/// order is positions, velocities, masses, cell, atom ids, fixed masks.
fn column_len(name: &str, got: usize, want: usize) -> Result<(), ParseError> {
    if got == want {
        return Ok(());
    }
    Err(ParseError::InvalidCount(format!(
        "CON-bin {name} has {got} values, need {want}"
    )))
}

/// Check the value counts of a version-2 binary64 write and build its header.
#[allow(clippy::too_many_arguments)]
fn f64_columns_header(
    n_frames: u64,
    n_atoms: u64,
    positions: usize,
    velocities: Option<usize>,
    masses: Option<usize>,
    cell: Option<usize>,
    atom_ids: Option<usize>,
    fixed: Option<usize>,
) -> Result<ConBinHeader, ParseError> {
    let frames = usize::try_from(n_frames)
        .map_err(|_| ParseError::InvalidCount("CON-bin frame count does not fit".into()))?;
    let atoms = usize::try_from(n_atoms)
        .map_err(|_| ParseError::InvalidCount("CON-bin atom count does not fit".into()))?;
    let n = frames
        .checked_mul(atoms)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
    let xyz = n
        .checked_mul(3)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
    let cells = frames
        .checked_mul(6)
        .ok_or_else(|| ParseError::InvalidCount("CON-bin column length overflows".into()))?;
    column_len("positions", positions, xyz)?;
    if let Some(values) = velocities {
        column_len("velocities", values, xyz)?;
    }
    if let Some(values) = masses {
        column_len("masses", values, n)?;
    }
    if let Some(values) = cell {
        column_len("cell", values, cells)?;
    }
    if let Some(values) = atom_ids {
        column_len("atom ids", values, n)?;
    }
    if let Some(values) = fixed {
        column_len("fixed masks", values, n)?;
    }
    Ok(ConBinHeader {
        version: VERSION_2,
        n_frames,
        n_atoms,
        binary32: false,
        velocities: velocities.is_some(),
        forces: false,
        masses: masses.is_some(),
        fixed: fixed.is_some(),
        cell: cell.is_some(),
        atom_ids: atom_ids.is_some(),
    })
}

#[allow(clippy::too_many_arguments)]
pub fn write_f64_columns(
    path: &Path,
    n_frames: u64,
    n_atoms: u64,
    positions: &[f64],
    velocities: Option<&[f64]>,
    masses: Option<&[f64]>,
    cell: Option<&[f64]>,
    atom_ids: Option<&[u64]>,
    fixed: Option<&[u8]>,
) -> Result<ConBinHeader, ParseError> {
    let header = f64_columns_header(
        n_frames,
        n_atoms,
        positions.len(),
        velocities.map(<[f64]>::len),
        masses.map(<[f64]>::len),
        cell.map(<[f64]>::len),
        atom_ids.map(<[u64]>::len),
        fixed.map(<[u8]>::len),
    )?;
    if let Some(values) = cell {
        crate::types::check_cell_rows(values)?;
    }
    let page = page_size()?;
    #[cfg(target_endian = "little")]
    {
        let mut parts = Vec::with_capacity(6);
        parts.push(view_bytes(positions));
        if let Some(values) = velocities {
            parts.push(view_bytes(values));
        }
        if let Some(values) = masses {
            parts.push(view_bytes(values));
        }
        if let Some(values) = cell {
            parts.push(view_bytes(values));
        }
        if let Some(values) = atom_ids {
            parts.push(view_bytes(values));
        }
        if let Some(values) = fixed {
            parts.push(view_bytes(values));
        }
        publish_assembled(path, &header, page, &parts)?;
    }
    #[cfg(target_endian = "big")]
    {
        let pos = le_bytes(positions);
        let vel = velocities.map(le_bytes);
        let mass = masses.map(le_bytes);
        let box_cell = cell.map(le_bytes);
        let ids = atom_ids.map(le_bytes);
        let masks = fixed.map(le_bytes);
        let mut parts = Vec::with_capacity(6);
        parts.push(pos.as_slice());
        if let Some(values) = vel.as_ref() {
            parts.push(values);
        }
        if let Some(values) = mass.as_ref() {
            parts.push(values);
        }
        if let Some(values) = box_cell.as_ref() {
            parts.push(values);
        }
        if let Some(values) = ids.as_ref() {
            parts.push(values);
        }
        if let Some(values) = masks.as_ref() {
            parts.push(values);
        }
        publish_assembled(path, &header, page, &parts)?;
    }
    Ok(header)
}

/// Write one binary64 file whose columns come from `seed`.
///
/// The header page and both runs match what [`map_file`] and [`read_into`] read.
/// `seed` is mixed with each value index, so the same triple writes the same file.
/// The bytes are published by rename, the same way [`write_f64_columns`] is,
/// so a reader that still holds an older mapping keeps that inode.
pub fn write_uniform(
    path: &Path,
    frames: u64,
    atoms: u64,
    seed: u64,
) -> Result<ConBinHeader, ParseError> {
    let header = ConBinHeader {
        version: VERSION_2,
        n_frames: frames,
        n_atoms: atoms,
        binary32: false,
        velocities: true,
        forces: false,
        masses: false,
        fixed: false,
        cell: false,
        atom_ids: false,
    };
    let n = header.position_len()?;
    let page = page_size()?;
    let pos: Vec<f64> = (0..n).map(|i| mix_unit(seed, i as u64)).collect();
    let vel: Vec<f64> = (0..n)
        .map(|i| mix_unit(seed, (n as u64) + i as u64))
        .collect();
    #[cfg(target_endian = "little")]
    publish_assembled(path, &header, page, &[view_bytes(&pos), view_bytes(&vel)])?;
    #[cfg(target_endian = "big")]
    {
        let pos_le = le_bytes(&pos);
        let vel_le = le_bytes(&vel);
        publish_assembled(path, &header, page, &[pos_le.as_slice(), vel_le.as_slice()])?;
    }
    Ok(header)
}

/// SplitMix64 finalizer, then a unit interval.
/// The multipliers and shift distances are the ones in Steele, Lea and Flood, 2014.
const SPLITMIX_MUL_1: u64 = 0x9E37_79B9_7F4A_7C15;
const SPLITMIX_MUL_2: u64 = 0xBF58_476D_1CE4_E5B9;
const SPLITMIX_MUL_3: u64 = 0x94D0_49BB_1331_11EB;
const SPLITMIX_SHIFT_1: u32 = 30;
const SPLITMIX_SHIFT_2: u32 = 27;
const SPLITMIX_SHIFT_3: u32 = 31;
const SPLITMIX_FLOAT_SHIFT: u32 = 11;
const SPLITMIX_FLOAT_BITS: u32 = 53;

fn mix_unit(seed: u64, index: u64) -> f64 {
    let mut z = seed.wrapping_add(index).wrapping_mul(SPLITMIX_MUL_1);
    z = (z ^ (z >> SPLITMIX_SHIFT_1)).wrapping_mul(SPLITMIX_MUL_2);
    z = (z ^ (z >> SPLITMIX_SHIFT_2)).wrapping_mul(SPLITMIX_MUL_3);
    z ^= z >> SPLITMIX_SHIFT_3;
    (z >> SPLITMIX_FLOAT_SHIFT) as f64 / ((1u64 << SPLITMIX_FLOAT_BITS) as f64)
}

/// Stream a CON text file into a CON-bin of the same frames.
///
/// The header occupies one host page, so the payload starts on a page
/// boundary. Positions of every frame are written as one run, then velocities.
///
/// ```
/// use readcon_core::conbin::{read_owned_f64, write_from_con};
/// use std::path::Path;
///
/// let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
/// let dir = tempfile::tempdir().unwrap();
/// let out = dir.path().join("tiny.bin");
/// let header = write_from_con(&src, &out, false).unwrap();
/// assert_eq!((header.n_frames, header.n_atoms), (1, 4));
/// let (again, positions, velocities) = read_owned_f64(&out, 1).unwrap();
/// assert_eq!(again.n_frames, 1);
/// assert_eq!(positions.len(), 12);
/// assert!((positions[0] - 0.6394).abs() < 1e-4);
/// assert_eq!(velocities.len(), 12);
/// ```
pub fn write_from_con(
    con_path: &Path,
    out_path: &Path,
    binary32: bool,
) -> Result<ConBinHeader, ParseError> {
    write_from_con_with_threads(con_path, out_path, binary32, 1)
}

/// [`write_from_con`] using `threads` to parse equal-length frames.
///
/// A file that is not a sequence of equal-length frames stays on one
/// thread: the frame boundaries are only known by parsing it in order.
/// Equal-length frames are parsed on `threads` workers. Each worker then
/// `pwrite`s its own column chunks into a preallocated file, and the
/// publish is still one rename. A file that is not equal-length frames
/// stays on one thread. The output matches the one-thread writer.
///
/// Eight thousand copies of `cuh2.con` (114 MB of CON-bin) took 0.343 s,
/// 0.212 s, 0.138 s and 0.117 s at 1, 2, 4 and 8 threads. The speedup is
/// about 2.9 at 8 threads. Weak scaling still grows the file with the
/// worker count, so the wall time cannot stay flat.
pub fn write_from_con_with_threads(
    con_path: &Path,
    out_path: &Path,
    binary32: bool,
    threads: usize,
) -> Result<ConBinHeader, ParseError> {
    let text = std::fs::read_to_string(con_path)
        .map_err(|err| ParseError::ValidationError(err.to_string()))?;
    let page = page_size()?;
    crate::writer::publish_new(
        out_path,
        |err| ParseError::ValidationError(err.to_string()),
        |file| write_conbin_body(file, &text, binary32, page, threads),
    )?;
    read_header(out_path)
}

struct FrameColumns {
    n_frames: u64,
    n_atoms: u64,
    positions: Vec<f64>,
    velocities: Vec<f64>,
    forces: Vec<f64>,
    masses: Vec<f64>,
    fixed: Vec<u8>,
    cells: Vec<f64>,
    ids: Vec<u64>,
    any_force: bool,
    any_velocity: bool,
}

fn equal_frame_span(text: &str) -> Option<usize> {
    let nl = text.find('\n')?;
    let marker = &text[..=nl];
    let rest = text.get(marker.len()..)?;
    let rel = rest.find(marker)?;
    let span = marker.len() + rel;
    if span < 32 || text.len() % span != 0 {
        return None;
    }
    let n = text.len() / span;
    if n < 2 {
        return None;
    }
    for index in 1..n {
        if !text[index * span..].starts_with(marker) {
            return None;
        }
    }
    Some(span)
}

/// The columns of the frames in `text`. `first_frame` is the index of the
/// first of them in the whole file, so a failure names its global frame.
fn accumulate_frames(text: &str, first_frame: u64) -> Result<FrameColumns, ParseError> {
    let mut n_frames = 0u64;
    let mut n_atoms = 0u64;
    let mut positions = Vec::new();
    let mut velocities = Vec::new();
    let mut forces = Vec::new();
    let mut masses = Vec::new();
    let mut fixed = Vec::new();
    let mut cells = Vec::new();
    let mut ids = Vec::new();
    let mut any_force = false;
    let mut any_velocity = false;
    for frame in ConFrameIterator::new(text) {
        let frame = frame.map_err(|error| error.in_frame(first_frame + n_frames))?;
        let n = frame.atom_data.len();
        if n_frames == 0 {
            n_atoms = n as u64;
        } else if n as u64 != n_atoms {
            return Err(ParseError::InvalidCount(
                "CON-bin requires the same atom count in every frame".into(),
            ));
        }
        let xyz = n.saturating_mul(3);
        positions.reserve(xyz);
        velocities.reserve(xyz);
        forces.reserve(xyz);
        masses.reserve(n);
        fixed.reserve(n);
        ids.reserve(n);
        cells.reserve(6);
        let mut mass_at = 0usize;
        for (count, mass) in frame
            .header
            .natms_per_type
            .iter()
            .zip(frame.header.masses_per_type.iter())
        {
            for _ in 0..*count {
                masses.push(*mass);
                mass_at += 1;
            }
        }
        if mass_at < n {
            let fill = frame.header.masses_per_type.last().copied().unwrap_or(0.0);
            masses.extend(std::iter::repeat_n(fill, n - mass_at));
        } else if mass_at > n {
            masses.truncate(masses.len() - (mass_at - n));
        }
        cells.extend_from_slice(&frame.header.boxl);
        cells.extend_from_slice(&frame.header.angles);
        any_velocity |= frame.has_velocities();
        for (index, atom) in frame.atom_data.iter().enumerate() {
            positions.extend_from_slice(&frame.xyz_at(index));
            velocities.extend_from_slice(&atom.velocity().unwrap_or([0.0; 3]));
            if let Some(row) = atom.force() {
                any_force = true;
                forces.extend_from_slice(&row);
            } else {
                forces.extend_from_slice(&[0.0, 0.0, 0.0]);
            }
            let flags = atom.fixed();
            fixed.push(u8::from(flags[0]) | (u8::from(flags[1]) << 1) | (u8::from(flags[2]) << 2));
            ids.push(atom.atom_id);
        }
        n_frames += 1;
    }
    Ok(FrameColumns {
        n_frames,
        n_atoms,
        positions,
        velocities,
        forces,
        masses,
        fixed,
        cells,
        ids,
        any_force,
        any_velocity,
    })
}

fn equal_parts(text: &str, threads: usize) -> Result<Option<Vec<(u64, FrameColumns)>>, ParseError> {
    let Some(span) = equal_frame_span(text) else {
        return Ok(None);
    };
    let n = text.len() / span;
    let threads = threads.max(1).min(n);
    if threads < 2 {
        return Ok(None);
    }
    let mut parts = Vec::with_capacity(threads);
    std::thread::scope(|scope| {
        let mut jobs = Vec::with_capacity(threads);
        for thread in 0..threads {
            let start = n * thread / threads;
            let end = n * (thread + 1) / threads;
            let chunk = &text[start * span..end * span];
            jobs.push(scope.spawn(move || (start as u64, accumulate_frames(chunk, start as u64))));
        }
        for job in jobs {
            parts.push(job.join().expect("frame parse"));
        }
    });
    let mut built = Vec::with_capacity(parts.len());
    for (begin, columns) in parts {
        built.push((begin, columns?));
    }
    Ok(Some(built))
}

fn write_at(file: &File, mut bytes: &[u8], mut offset: u64) -> Result<(), ParseError> {
    while !bytes.is_empty() {
        #[cfg(unix)]
        let wrote = {
            use std::os::unix::fs::FileExt;
            file.write_at(bytes, offset)
                .map_err(|err| ParseError::ValidationError(err.to_string()))?
        };
        #[cfg(not(unix))]
        let wrote = {
            use std::os::windows::fs::FileExt;
            file.seek_write(bytes, offset)
                .map_err(|err| ParseError::ValidationError(err.to_string()))?
        };
        if wrote == 0 {
            return Err(ParseError::ValidationError(
                "positioned write stored no bytes".into(),
            ));
        }
        bytes = &bytes[wrote..];
        offset += wrote as u64;
    }
    Ok(())
}

fn store_at<T: StoreLe>(file: &File, values: &[T], offset: u64) -> Result<(), ParseError> {
    if values.is_empty() {
        return Ok(());
    }
    if cfg!(target_endian = "little") {
        let bytes = unsafe {
            std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))
        };
        return write_at(file, bytes, offset);
    }
    let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));
    for value in values {
        value.store_le(&mut bytes);
    }
    write_at(file, &bytes, offset)
}

fn store_f32_at(file: &File, values: &[f64], offset: u64) -> Result<(), ParseError> {
    let narrow: Vec<f32> = values.iter().map(|value| *value as f32).collect();
    store_at(file, &narrow, offset)
}

fn preallocate(file: &File, len: u64) -> Result<(), ParseError> {
    // `allocate_len(0)` leaves the current length. An empty CON-bin is
    // truncated. Every other length uses the shared reserve: `fallocate`
    // on Linux and Android, `posix_fallocate` on FreeBSD, `F_PREALLOCATE`
    // on macOS, and `set_len` on Windows and when the filesystem rejects it.
    let result = if len == 0 {
        file.set_len(0)
    } else {
        crate::writer::allocate_len(file, len)
    };
    result.map_err(|err| ParseError::ValidationError(err.to_string()))
}

fn write_parts_at(
    file: &File,
    parts: &[(u64, FrameColumns)],
    binary32: bool,
    page: usize,
) -> Result<(), ParseError> {
    let n_atoms = parts[0].1.n_atoms;
    let mut n_frames = 0u64;
    let mut any_force = false;
    for (begin, columns) in parts {
        if columns.n_atoms != n_atoms {
            return Err(ParseError::InvalidCount(
                "CON-bin requires the same atom count in every frame".into(),
            ));
        }
        if *begin != n_frames {
            return Err(ParseError::ValidationError(
                "CON-bin frame chunks are not in order".into(),
            ));
        }
        n_frames += columns.n_frames;
        any_force |= columns.any_force;
    }
    let elem = if binary32 { 4u64 } else { 8 };
    let xyz = n_frames * n_atoms * 3 * elem;
    let mut at = page as u64;
    let pos_at = at;
    at += xyz;
    let vel_at = at;
    at += xyz;
    let force_at = if any_force {
        let here = at;
        at += xyz;
        Some(here)
    } else {
        None
    };
    let mass_at = at;
    at += n_frames * n_atoms * elem;
    let cell_at = at;
    at += n_frames * 6 * elem;
    let id_at = at;
    at += n_frames * n_atoms * 8;
    let fix_at = at;
    at += n_frames * n_atoms;
    preallocate(file, at)?;
    let stride_xyz = n_atoms * 3 * elem;
    let stride_atom = n_atoms * elem;
    let mut failed: Option<ParseError> = None;
    std::thread::scope(|scope| {
        let mut jobs = Vec::with_capacity(parts.len());
        for (begin, columns) in parts {
            jobs.push(scope.spawn(move || -> Result<(), ParseError> {
                if binary32 {
                    check_cells_fit_binary32(&columns.cells, *begin)?;
                    store_f32_at(file, &columns.positions, pos_at + begin * stride_xyz)?;
                    store_f32_at(file, &columns.velocities, vel_at + begin * stride_xyz)?;
                    if let Some(force_at) = force_at {
                        store_f32_at(file, &columns.forces, force_at + begin * stride_xyz)?;
                    }
                    store_f32_at(file, &columns.masses, mass_at + begin * stride_atom)?;
                    store_f32_at(file, &columns.cells, cell_at + begin * 6 * elem)?;
                } else {
                    store_at(file, &columns.positions, pos_at + begin * stride_xyz)?;
                    store_at(file, &columns.velocities, vel_at + begin * stride_xyz)?;
                    if let Some(force_at) = force_at {
                        store_at(file, &columns.forces, force_at + begin * stride_xyz)?;
                    }
                    store_at(file, &columns.masses, mass_at + begin * stride_atom)?;
                    store_at(file, &columns.cells, cell_at + begin * 6 * elem)?;
                }
                store_at(file, &columns.ids, id_at + begin * n_atoms * 8)?;
                store_at(file, &columns.fixed, fix_at + begin * n_atoms)?;
                Ok(())
            }));
        }
        for job in jobs {
            if let Err(err) = job.join().expect("column write") {
                failed = Some(err);
            }
        }
    });
    if let Some(err) = failed {
        return Err(err);
    }
    let header = ConBinHeader {
        version: VERSION_2,
        n_frames,
        n_atoms,
        binary32,
        velocities: true,
        forces: any_force,
        masses: true,
        fixed: true,
        cell: true,
        atom_ids: true,
    };
    let page_bytes = header_page_bytes(&header, page);
    write_at(file, &page_bytes, 0)
}

fn write_conbin_body(
    file: &mut File,
    text: &str,
    binary32: bool,
    page: usize,
    threads: usize,
) -> Result<(), ParseError> {
    if threads > 1 {
        if let Some(parts) = equal_parts(text, threads)? {
            return write_parts_at(file, &parts, binary32, page);
        }
    }
    let built = accumulate_frames(text, 0)?;
    let header = ConBinHeader {
        version: VERSION_2,
        n_frames: built.n_frames,
        n_atoms: built.n_atoms,
        binary32,
        velocities: true,
        forces: built.any_force,
        masses: true,
        fixed: true,
        cell: true,
        atom_ids: true,
    };
    emit_built(file, &header, page, binary32, &built)
}

/// A cell that is finite in binary64 can still be infinite in binary32. The
/// file would store that infinity, so the write is refused and names the
/// frame (`first_frame` plus the row) and the field.
fn check_cells_fit_binary32(cells: &[f64], first_frame: u64) -> Result<(), ParseError> {
    if cells.iter().all(|v| (*v as f32).is_finite()) {
        return Ok(());
    }
    for (row_index, row) in cells.chunks(6).enumerate() {
        if let Some((index, value)) = row
            .iter()
            .enumerate()
            .find(|(_, v)| !(**v as f32).is_finite())
        {
            return Err(ParseError::non_finite_cell(
                &format!("cell[{index}]"),
                format!("{value} (infinite in binary32)"),
            )
            .in_frame(first_frame + row_index as u64));
        }
    }
    Ok(())
}

fn emit_built(
    file: &mut File,
    header: &ConBinHeader,
    page: usize,
    binary32: bool,
    built: &FrameColumns,
) -> Result<(), ParseError> {
    let _ = built.any_velocity;
    #[cfg(target_endian = "little")]
    {
        if binary32 {
            check_cells_fit_binary32(&built.cells, 0)?;
            let pos32: Vec<f32> = built.positions.iter().map(|v| *v as f32).collect();
            let vel32: Vec<f32> = built.velocities.iter().map(|v| *v as f32).collect();
            let force32 = if built.any_force {
                Some(built.forces.iter().map(|v| *v as f32).collect::<Vec<f32>>())
            } else {
                None
            };
            let mass32: Vec<f32> = built.masses.iter().map(|v| *v as f32).collect();
            let cell32: Vec<f32> = built.cells.iter().map(|v| *v as f32).collect();
            let mut parts = Vec::with_capacity(7);
            parts.push(view_bytes(&pos32));
            parts.push(view_bytes(&vel32));
            if let Some(values) = force32.as_ref() {
                parts.push(view_bytes(values));
            }
            parts.push(view_bytes(&mass32));
            parts.push(view_bytes(&cell32));
            parts.push(view_bytes(&built.ids));
            parts.push(view_bytes(&built.fixed));
            write_assembled(file, header, page, &parts)
        } else {
            let mut parts = Vec::with_capacity(7);
            parts.push(view_bytes(&built.positions));
            parts.push(view_bytes(&built.velocities));
            if built.any_force {
                parts.push(view_bytes(&built.forces));
            }
            parts.push(view_bytes(&built.masses));
            parts.push(view_bytes(&built.cells));
            parts.push(view_bytes(&built.ids));
            parts.push(view_bytes(&built.fixed));
            write_assembled(file, header, page, &parts)
        }
    }
    #[cfg(target_endian = "big")]
    {
        let mut owned = Vec::with_capacity(7);
        if binary32 {
            check_cells_fit_binary32(&built.cells, 0)?;
            let pos32: Vec<f32> = built.positions.iter().map(|v| *v as f32).collect();
            let vel32: Vec<f32> = built.velocities.iter().map(|v| *v as f32).collect();
            let force32: Vec<f32> = built.forces.iter().map(|v| *v as f32).collect();
            let mass32: Vec<f32> = built.masses.iter().map(|v| *v as f32).collect();
            let cell32: Vec<f32> = built.cells.iter().map(|v| *v as f32).collect();
            owned.push(le_bytes(&pos32));
            owned.push(le_bytes(&vel32));
            if built.any_force {
                owned.push(le_bytes(&force32));
            }
            owned.push(le_bytes(&mass32));
            owned.push(le_bytes(&cell32));
        } else {
            owned.push(le_bytes(&built.positions));
            owned.push(le_bytes(&built.velocities));
            if built.any_force {
                owned.push(le_bytes(&built.forces));
            }
            owned.push(le_bytes(&built.masses));
            owned.push(le_bytes(&built.cells));
        }
        owned.push(le_bytes(&built.ids));
        owned.push(le_bytes(&built.fixed));
        let parts: Vec<&[u8]> = owned.iter().map(|bytes| bytes.as_slice()).collect();
        write_assembled(file, header, page, &parts)
    }
}

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

    #[cfg(target_endian = "little")]
    #[test]
    fn view_bytes_matches_the_number_encoding() {
        let values = [1.5f64, -0.25];
        let mut expect = Vec::new();
        for value in values {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        assert_eq!(view_bytes(&values), expect.as_slice());
    }

    fn reject_short(label: &str, needle: &str, want: &str) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("short.bin");
        let positions = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
        let err = match label {
            "positions" => {
                write_f64_columns(&path, 1, 2, &[0.0, 1.0, 2.0], None, None, None, None, None)
            }
            "velocities" => write_f64_columns(
                &path,
                1,
                2,
                &positions,
                Some(&[0.0, 1.0, 2.0]),
                None,
                None,
                None,
                None,
            ),
            "masses" => write_f64_columns(
                &path,
                1,
                2,
                &positions,
                None,
                Some(&[63.5]),
                None,
                None,
                None,
            ),
            "cell" => write_f64_columns(
                &path,
                1,
                2,
                &positions,
                None,
                None,
                Some(&[1.0, 1.0, 1.0]),
                None,
                None,
            ),
            "atom ids" => {
                write_f64_columns(&path, 1, 2, &positions, None, None, None, Some(&[0]), None)
            }
            "fixed masks" => {
                write_f64_columns(&path, 1, 2, &positions, None, None, None, None, Some(&[0]))
            }
            _ => panic!("unknown column {label}"),
        }
        .expect_err(label);
        let message = err.to_string();
        assert!(
            message.contains(needle) && message.contains(want),
            "{message}"
        );
        assert!(!path.exists(), "a rejected column must not publish a file");
    }

    #[test]
    fn a_short_positions_column_is_rejected_before_publish() {
        reject_short("positions", "positions", "need 6");
    }

    #[test]
    fn a_short_velocities_column_is_rejected_before_publish() {
        reject_short("velocities", "velocities", "need 6");
    }

    #[test]
    fn a_short_masses_column_is_rejected_before_publish() {
        reject_short("masses", "masses", "need 2");
    }

    #[test]
    fn a_short_cell_column_is_rejected_before_publish() {
        reject_short("cell", "cell", "need 6");
    }

    #[test]
    fn a_short_atom_id_column_is_rejected_before_publish() {
        reject_short("atom ids", "atom ids", "need 2");
    }

    #[test]
    fn a_short_fixed_mask_column_is_rejected_before_publish() {
        reject_short("fixed masks", "fixed masks", "need 2");
    }

    fn write_known(path: &Path, frames: usize, atoms: usize) {
        let page = page_size().unwrap();
        let mut file = File::create(path).unwrap();
        let header = ConBinHeader::version1(frames as u64, atoms as u64, false, true);
        write_header_page(&mut file, &header, page).unwrap();
        let n = frames * atoms * 3;
        let pos: Vec<f64> = (0..n).map(|i| i as f64 * 0.25).collect();
        let vel: Vec<f64> = (0..n).map(|i| i as f64 * -0.5).collect();
        write_values(&mut file, &pos).unwrap();
        write_values(&mut file, &vel).unwrap();
    }

    #[test]
    fn wide_columns_are_read_by_several_workers() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("wide-workers.conbin");
        write_known(&path, 2, 2048);
        let (header, pos, vel) = read_owned_f64(&path, 4).unwrap();
        let n = header.position_len().unwrap();
        let mut again_pos = vec![0.0; n];
        let mut again_vel = vec![0.0; n];
        read_into_threads(&path, &mut again_pos, Some(&mut again_vel), 4).unwrap();
        assert_eq!(pos, again_pos);
        assert_eq!(vel, again_vel);
        assert_eq!(pos[0], 0.0);
        assert_eq!(vel[1], -0.5);
    }

    /// Four atoms per frame, one shared header line, coordinates that move.
    ///
    /// Fixed widths keep `equal_frame_span` able to split the file. A test
    /// that repeats one frame still passes if the chunks are written backwards.
    fn distinct_frames(n: usize) -> String {
        let mut text = String::new();
        for frame in 0..n {
            text.push_str(
                "distinct\n{\"con_spec_version\":2}\n10.0 10.0 10.0\n90.0 90.0 90.0\n0 0\n0 0\n1\n4\n63.546\nCu\nCoordinates of Component 1\n",
            );
            for atom in 0..4 {
                text.push_str(&format!(
                    "{:10.4} {:10.4} {:10.4} 0 {:3}\n",
                    frame as f64 + atom as f64 * 0.25,
                    0.5,
                    1.5,
                    atom
                ));
            }
        }
        text
    }

    fn positions_in_part_order(text: &str, threads: usize) -> Vec<f64> {
        let parts = equal_parts(text, threads).unwrap().unwrap();
        let mut out = Vec::new();
        for (_, columns) in parts {
            out.extend(columns.positions);
        }
        out
    }

    /// The bug the identical-copy test missed: later chunks labeled as earlier frames.
    fn positions_if_chunks_are_reversed(text: &str, threads: usize) -> Vec<f64> {
        let span = equal_frame_span(text).unwrap();
        let n = text.len() / span;
        let threads = threads.max(1).min(n);
        let mut chunks = Vec::with_capacity(threads);
        for thread in 0..threads {
            let start = n * thread / threads;
            let end = n * (thread + 1) / threads;
            chunks.push(accumulate_frames(&text[start * span..end * span], 0).unwrap());
        }
        chunks.reverse();
        let mut out = Vec::new();
        for columns in chunks {
            out.extend(columns.positions);
        }
        out
    }

    #[test]
    fn repeated_frames_on_several_threads_match_one_thread() {
        let text = distinct_frames(8);
        let serial_positions = accumulate_frames(&text, 0).unwrap().positions;
        assert_eq!(positions_in_part_order(&text, 4), serial_positions);
        assert_ne!(
            positions_if_chunks_are_reversed(&text, 4),
            serial_positions,
            "reversed chunks of identical frames would still match"
        );
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("in.con");
        std::fs::write(&input, &text).unwrap();
        for binary32 in [false, true] {
            let one = dir.path().join(format!("one-{binary32}.conbin"));
            write_from_con_with_threads(&input, &one, binary32, 1).unwrap();
            let serial = std::fs::read(&one).unwrap();
            for threads in [2usize, 4, 8] {
                let many = dir.path().join(format!("t{threads}-{binary32}.conbin"));
                write_from_con_with_threads(&input, &many, binary32, threads).unwrap();
                assert_eq!(
                    std::fs::read(&many).unwrap(),
                    serial,
                    "threads {threads} binary32 {binary32}"
                );
            }
        }
    }

    #[test]
    fn column_writer_publishes_every_optional_run() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("columns.conbin");
        let header = write_f64_columns(
            &path,
            1,
            2,
            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
            Some(&[0.1, 0.2, 0.3, 0.4, 0.5, 0.6]),
            Some(&[63.5, 1.0]),
            Some(&[10.0, 10.0, 10.0, 90.0, 90.0, 90.0]),
            Some(&[7, 8]),
            Some(&[0b001, 0b100]),
        )
        .unwrap();
        assert!(
            header.velocities && header.masses && header.cell && header.atom_ids && header.fixed
        );
        let again = read_header(&path).unwrap();
        assert_eq!(again.n_atoms, 2);
        assert!(again.masses && again.atom_ids);
        let mapped = map_file(&path, 1).unwrap();
        assert_eq!(
            mapped.positions_f64().unwrap(),
            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
        );
    }

    #[test]
    fn f64_columns_round_trip_matches_the_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("columns.conbin");
        let positions = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let velocities = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5];
        let masses = [12.0, 16.0];
        let cell = [10.0, 11.0, 12.0, 90.0, 90.0, 90.0];
        let ids = [3u64, 4];
        let fixed = [0b001u8, 0b110];
        let header = write_f64_columns(
            &path,
            1,
            2,
            &positions,
            Some(&velocities),
            Some(&masses),
            Some(&cell),
            Some(&ids),
            Some(&fixed),
        )
        .unwrap();
        let bytes = std::fs::read(&path).unwrap();
        let copy = dir.path().join("copy.conbin");
        write_f64_columns(
            &copy,
            1,
            2,
            &positions,
            Some(&velocities),
            Some(&masses),
            Some(&cell),
            Some(&ids),
            Some(&fixed),
        )
        .unwrap();
        assert_eq!(std::fs::read(&copy).unwrap(), bytes);

        let page = page_size().unwrap();
        let mut expect = vec![0u8; page];
        expect[..FIELD_BYTES].copy_from_slice(&header_fields(&header, page as u64));
        for value in positions {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        for value in velocities {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        for value in masses {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        for value in cell {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        for value in ids {
            expect.extend_from_slice(&value.to_le_bytes());
        }
        expect.extend_from_slice(&fixed);
        assert_eq!(bytes, expect);

        let mapped = map_file(&path, 1).unwrap();
        assert_eq!(mapped.positions_f64().unwrap(), &positions);
        assert_eq!(mapped.velocities_f64().unwrap(), &velocities);
        assert_eq!(mapped.masses_f64().unwrap().unwrap(), &masses);
        assert_eq!(mapped.cell_f64().unwrap().unwrap(), &cell);
        assert_eq!(mapped.atom_ids().unwrap().unwrap(), &ids);
        assert_eq!(mapped.fixed_masks().unwrap().unwrap(), &fixed);

        let bare = dir.path().join("positions.conbin");
        write_f64_columns(&bare, 1, 1, &[9.0, 8.0, 7.0], None, None, None, None, None).unwrap();
        let bare_bytes = std::fs::read(&bare).unwrap();
        assert_eq!(bare_bytes.len(), page + 24);
        assert!(bare_bytes[FIELD_BYTES..page].iter().all(|byte| *byte == 0));
        let mut coords = Vec::new();
        coords.extend_from_slice(&9.0f64.to_le_bytes());
        coords.extend_from_slice(&8.0f64.to_le_bytes());
        coords.extend_from_slice(&7.0f64.to_le_bytes());
        assert_eq!(&bare_bytes[page..], coords.as_slice());
    }

    #[test]
    fn write_from_con_is_byte_identical() {
        let dir = tempfile::tempdir().unwrap();
        let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/tiny_cuh2.con");
        let first = dir.path().join("a.conbin");
        let second = dir.path().join("b.conbin");
        let header = write_from_con(&src, &first, false).unwrap();
        write_from_con(&src, &second, false).unwrap();
        let bytes = std::fs::read(&first).unwrap();
        assert_eq!(std::fs::read(&second).unwrap(), bytes);
        let page = page_size().unwrap();
        assert!(bytes.len() > page);
        assert_eq!(&bytes[..8], MAGIC);
        assert!(bytes[FIELD_BYTES..page].iter().all(|byte| *byte == 0));
        let (_again, positions, velocities) = read_owned_f64(&first, 1).unwrap();
        assert_eq!(positions.len(), header.position_len().unwrap());
        assert_eq!(velocities.len(), positions.len());
        let mapped = map_file(&first, 1).unwrap();
        assert_eq!(mapped.positions_f64().unwrap(), positions.as_slice());
        assert_eq!(mapped.velocities_f64().unwrap(), velocities.as_slice());
    }

    #[test]
    fn every_prefetch_reads_the_same_columns() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("wide.conbin");
        write_known(&path, 2, 64);
        let span = map_file_with(&path, 2, Prefetch::Span).unwrap();
        let expect_pos = span.positions_f64().unwrap().to_vec();
        let expect_vel = span.velocities_f64().unwrap().to_vec();
        assert_eq!(expect_pos.len(), 2 * 64 * 3);
        for mode in [
            Prefetch::ChunkPopulate,
            Prefetch::ChunkWillneed,
            Prefetch::Hybrid,
        ] {
            let mapped = map_file_with(&path, 2, mode).unwrap();
            assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
            assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
        }
        let expect = expect_pos.iter().sum::<f64>() + expect_vel.iter().sum::<f64>();
        assert_eq!(sum_split_streams(&path, 2).unwrap(), expect);
        assert_eq!(sum_mapped(&path, 2).unwrap(), expect);
    }

    #[test]
    fn a_rename_publish_is_not_read_through_the_previous_mapping() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("republish.conbin");
        write_uniform(&path, 1, 4, 1).unwrap();
        let first = map_file(&path, 1).unwrap();
        let first_pos = first.positions_f64().unwrap().to_vec();
        write_uniform(&path, 1, 4, 99).unwrap();
        let second = map_file(&path, 1).unwrap();
        let second_pos = second.positions_f64().unwrap().to_vec();
        assert_ne!(first_pos, second_pos);
        assert_eq!(first.positions_f64().unwrap(), first_pos.as_slice());
        let (_header, owned, _velocities) = read_owned_f64(&path, 1).unwrap();
        assert_eq!(owned, second_pos);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn worker_span_shares_the_queue() {
        let limits = QueueLimits {
            page: 4096,
            logical_block: 512,
            max_request: 1280 * 1024,
            nr_requests: 256,
            read_ahead: 128 * 1024,
            nr_hw_queues: 1,
            rotational: true,
        };
        assert_eq!(limits.worker_span(8), 32 * 1280 * 1024);
        assert_eq!(limits.worker_span(1), 256 * 1280 * 1024);
        // /dev/shm is tmpfs, so it has no block queue. The sum must still run.
        let dir = std::path::PathBuf::from(format!("/dev/shm/conbin-sum-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("known.conbin");
        write_known(&path, 4, 8);
        let mapped = map_file(&path, 1).unwrap();
        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
        let got = sum_mapped(&path, 2).unwrap();
        let got_split = sum_split_streams(&path, 2).unwrap();
        assert_eq!(got, expect, "parallel sum {got} serial sum {expect}");
        assert_eq!(
            got_split, expect,
            "split sum {got_split} serial sum {expect}"
        );
        let _ = std::fs::remove_dir_all(&dir);
        let short = QueueLimits {
            nr_requests: 2,
            read_ahead: 4096,
            ..limits
        };
        assert_eq!(short.worker_span(8), 1280 * 1024);
        let shm = std::path::PathBuf::from(format!("/dev/shm/conbin-queue-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&shm);
        std::fs::create_dir_all(&shm).unwrap();
        let qpath = shm.join("known.conbin");
        write_known(&qpath, 1, 1);
        let got = QueueLimits::of(&qpath).unwrap();
        assert!(got.page.is_power_of_two());
        assert_eq!(got.max_request, got.page);
        assert_eq!(got.nr_requests, 1);
        assert!(!got.rotational);
        let _ = std::fs::remove_dir_all(&shm);
    }

    #[test]
    fn mapped_runs_match_the_pread_fill() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("known.conbin");
        write_known(&path, 4, 3);
        let mapped = map_file(&path, 2).unwrap();
        let pos = mapped.positions_f64().unwrap();
        let vel = mapped.velocities_f64().unwrap();
        assert_eq!(pos.len(), 4 * 3 * 3);
        assert_eq!(pos[0], 0.0);
        assert_eq!(pos[1], 0.25);
        assert_eq!(vel[1], -0.5);
        let mut got_pos = vec![0.0; pos.len()];
        let mut got_vel = vec![0.0; vel.len()];
        read_into_threads(&path, &mut got_pos, Some(&mut got_vel), 2).unwrap();
        assert_eq!(got_pos, pos);
        assert_eq!(got_vel, vel);
        let _ = std::fs::remove_dir_all(dir);
    }

    struct HookGuard {
        slot: &'static std::thread::LocalKey<std::cell::Cell<bool>>,
    }

    impl HookGuard {
        fn arm(slot: &'static std::thread::LocalKey<std::cell::Cell<bool>>) -> Self {
            slot.with(|flag| flag.set(true));
            Self { slot }
        }
    }

    impl Drop for HookGuard {
        fn drop(&mut self) {
            self.slot.with(|flag| flag.set(false));
        }
    }

    #[test]
    fn populate_failure_still_reads_the_same_values() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("known.conbin");
        write_known(&path, 4, 3);
        let plain = map_file(&path, 2).unwrap();
        let expect_pos = plain.positions_f64().unwrap().to_vec();
        let expect_vel = plain.velocities_f64().unwrap().to_vec();
        drop(plain);
        let _guard = HookGuard::arm(&POPULATE_FAILS);
        let mapped = map_file(&path, 2).unwrap();
        assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
        assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
        let mut got_pos = vec![0.0; expect_pos.len()];
        let mut got_vel = vec![0.0; expect_vel.len()];
        read_into_threads(&path, &mut got_pos, Some(&mut got_vel), 2).unwrap();
        assert_eq!(got_pos, expect_pos);
        assert_eq!(got_vel, expect_vel);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn mmap_failure_still_reads_the_same_values() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("known.conbin");
        write_known(&path, 4, 3);
        let plain = map_file(&path, 1).unwrap();
        let expect_pos = plain.positions_f64().unwrap().to_vec();
        let expect_vel = plain.velocities_f64().unwrap().to_vec();
        drop(plain);
        let _guard = HookGuard::arm(&MAP_FAILS);
        let mapped = map_file(&path, 1).unwrap();
        assert_eq!(mapped.positions_f64().unwrap(), expect_pos.as_slice());
        assert_eq!(mapped.velocities_f64().unwrap(), expect_vel.as_slice());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn writer_stores_one_known_value_little_endian() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("one.conbin");
        // Second position is 0.25. Its little-endian bytes are fixed.
        write_known(&path, 1, 1);
        let known = 0.25f64;
        let bytes = std::fs::read(&path).unwrap();
        let at = page_size().unwrap() + std::mem::size_of::<f64>();
        assert_eq!(&bytes[at..at + 8], known.to_le_bytes().as_slice());
        let mapped = map_file(&path, 1).unwrap();
        assert_eq!(mapped.positions_f64().unwrap()[1], known);
        let mut got = vec![0.0; mapped.header.position_len().unwrap()];
        let mut vel = vec![0.0; got.len()];
        read_into_threads(&path, &mut got, Some(&mut vel), 1).unwrap();
        assert_eq!(got[1], known);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn write_from_con_round_trips_text() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let con = dir.join("two.con");
        std::fs::write(
            &con,
            include_str!("../resources/test/tiny_cuh2.con").repeat(2),
        )
        .unwrap();
        let bin = dir.join("two.conbin");
        let header = write_from_con(&con, &bin, false).unwrap();
        assert_eq!(header.n_frames, 2);
        assert_eq!(header.n_atoms, 4);
        let mapped = map_file(&bin, 1).unwrap();
        let pos = mapped.positions_f64().unwrap();
        assert_eq!(pos.len(), 2 * 4 * 3);
        assert!(pos[0].is_finite());
        assert_eq!(mapped.header.version, 2);
        assert!(mapped.header.masses && mapped.header.cell && mapped.header.fixed);
        assert_eq!(mapped.masses_f64().unwrap().unwrap().len(), 2 * 4);
        assert_eq!(mapped.cell_f64().unwrap().unwrap().len(), 2 * 6);
        assert_eq!(mapped.fixed_masks().unwrap().unwrap().len(), 2 * 4);
        assert_eq!(mapped.atom_ids().unwrap().unwrap().len(), 2 * 4);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn a_store_copies_the_page_and_leaves_the_file() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("known.conbin");
        write_known(&path, 2, 4);
        let before = std::fs::read(&path).unwrap();
        let mut mapped = map_file(&path, 1).unwrap();
        {
            let pos = mapped.positions_f64_mut().unwrap();
            let original = pos[0];
            pos[0] = original + 1.0;
            assert_eq!(pos[0], original + 1.0);
        }
        let after = std::fs::read(&path).unwrap();
        assert_eq!(before, after);
        let reread = map_file(&path, 1).unwrap();
        assert_eq!(reread.positions_f64().unwrap()[0], 0.0);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn a_4k_offset_opens_on_a_16k_or_64k_host() {
        // The stored offset is 4096, and the file is shorter than a 16 KiB
        // or 64 KiB page. The reader keeps 4096. It does not replace that
        // offset with the host page.
        let header = ConBinHeader::version1(1, 1, false, true);
        let mut bytes = header_fields(&header, 4096).to_vec();
        bytes.resize(4096 + 48, 0);
        bytes[4096..4096 + 8].copy_from_slice(&1.25f64.to_le_bytes());
        bytes[4096 + 24..4096 + 32].copy_from_slice(&(-2.5f64).to_le_bytes());
        assert!(bytes.len() < 16 * 1024);
        assert!(bytes.len() < 64 * 1024);
        let off = checked_payload_offset(4096, bytes.len()).unwrap();
        assert_eq!(off, 4096);
        assert_ne!(off, 16 * 1024);
        assert_ne!(off, 64 * 1024);
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let path = dir.join("known.conbin");
        std::fs::write(&path, &bytes).unwrap();
        let mapped = map_file(&path, 1).unwrap();
        assert_eq!(mapped.payload_off, 4096);
        assert_eq!(mapped.positions_f64().unwrap()[0], 1.25);
        assert_eq!(mapped.velocities_f64().unwrap()[0], -2.5);
        let _ = std::fs::remove_dir_all(dir);
    }

    fn write_typed(path: &Path, binary32: bool, velocities: bool) {
        let header = ConBinHeader::version1(1, 1, binary32, velocities);
        let mut bytes = header_fields(&header, 64).to_vec();
        bytes.resize(64 + 48, 0);
        std::fs::write(path, bytes).unwrap();
    }

    #[test]
    fn sum_mapped_rejects_binary32_and_a_missing_velocity_run() {
        let _scratch = tempfile::tempdir().unwrap();
        let dir = _scratch.path();
        let binary32 = dir.join("f32.conbin");
        write_typed(&binary32, true, true);
        let err = sum_mapped(&binary32, 1).unwrap_err();
        assert!(err.to_string().contains("binary32"), "{err}");
        let bare = dir.join("nov.conbin");
        write_typed(&bare, false, false);
        let err = sum_mapped(&bare, 1).unwrap_err();
        assert!(err.to_string().contains("no velocity"), "{err}");
        let err = read_owned_f64(&bare, 1).unwrap_err();
        assert!(err.to_string().contains("no velocity"), "{err}");
        let known = dir.join("known.conbin");
        write_known(&known, 1, 2);
        let (_header, pos, vel) = read_owned_f64(&known, 1).unwrap();
        let mapped = map_file(&known, 1).unwrap();
        assert_eq!(pos.as_slice(), mapped.positions_f64().unwrap());
        assert_eq!(vel.as_slice(), mapped.velocities_f64().unwrap());
        let _ = std::fs::remove_dir_all(dir);
    }

    /// A real disk for the readahead check. `POSIX_FADV_DONTNEED` does not
    /// drop tmpfs pages, so a tmpfs directory cannot host that test.
    #[cfg(target_os = "linux")]
    fn disk_dir() -> Option<tempfile::TempDir> {
        for rel in ["target", "build"] {
            let base = Path::new(rel);
            if std::fs::create_dir_all(base).is_err() || dir_is_tmpfs(base) {
                continue;
            }
            if let Ok(dir) = tempfile::tempdir_in(base) {
                return Some(dir);
            }
        }
        None
    }

    #[cfg(target_os = "linux")]
    fn dir_is_tmpfs(path: &Path) -> bool {
        let text = path.to_string_lossy();
        let Ok(c) = std::ffi::CString::new(text.as_bytes()) else {
            return false;
        };
        let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
        let rc = unsafe { libc::statfs(c.as_ptr(), &mut stat) };
        // include/uapi/linux/magic.h TMPFS_MAGIC
        rc == 0 && stat.f_type == 0x01021994
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_cold_multi_megabyte_file_uses_the_readahead_stream() {
        let Some(tmp) = disk_dir() else {
            eprintln!("skip: target and build are tmpfs, so the readahead check cannot drop pages");
            return;
        };
        let dir = tmp.path();
        let path = dir.join("cold.conbin");
        // Larger than the kernel readahead window, so `MADV_SEQUENTIAL`
        // cannot make every page resident before the stream starts.
        write_known(&path, 8, 65536);
        let file = File::open(&path).unwrap();
        file.sync_all().unwrap();
        drop(file);
        let file = File::open(&path).unwrap();
        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
        assert_eq!(rc, 0);
        drop(file);
        let got = sum_mapped(&path, 2).unwrap();
        let file = File::open(&path).unwrap();
        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
        assert_eq!(rc, 0);
        drop(file);
        let split = sum_split_streams(&path, 2).unwrap();
        let mapped = map_file(&path, 1).unwrap();
        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
        assert_eq!(got, expect);
        assert_eq!(split, expect);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn sum_mapped_streams_when_pages_are_not_resident() {
        let Some(tmp) = disk_dir() else {
            eprintln!("skip: target and build are tmpfs, so the readahead check cannot drop pages");
            return;
        };
        let dir = tmp.path();
        let path = dir.join("known.conbin");
        write_known(&path, 2, 32);
        let file = File::open(&path).unwrap();
        file.sync_all().unwrap();
        let rc = unsafe { libc::posix_fadvise(file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
        assert_eq!(rc, 0);
        let len = file.metadata().unwrap().len() as usize;
        let ptr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                len,
                libc::PROT_READ,
                libc::MAP_PRIVATE,
                file.as_raw_fd(),
                0,
            )
        };
        assert_ne!(ptr, libc::MAP_FAILED);
        let page = page_size().unwrap();
        let pages = len.div_ceil(page);
        let mut vec = vec![0u8; pages];
        let rc = unsafe { libc::mincore(ptr, len, vec.as_mut_ptr()) };
        assert_eq!(rc, 0);
        assert!(
            vec.iter().any(|byte| byte & 1 == 0),
            "every page stayed resident"
        );
        unsafe { libc::munmap(ptr, len) };
        let got = sum_mapped(&path, 2).unwrap();
        let mapped = map_file(&path, 1).unwrap();
        let expect = mapped.positions_f64().unwrap().iter().sum::<f64>()
            + mapped.velocities_f64().unwrap().iter().sum::<f64>();
        assert_eq!(got, expect, "{got} {expect}");
        let _ = std::fs::remove_dir_all(dir);
    }

    /// Fills both columns with `pread` into spare capacity.
    /// Miri runs this with `-Zmiri-disable-isolation`.
    /// Miri does not model file-backed mmap, `mincore`, `readahead`
    /// or `MADV_POPULATE_READ`.
    #[cfg(unix)]
    #[test]
    fn read_owned_f64_fills_spare_capacity_by_pread() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known.conbin");
        write_known(&path, 2, 8);
        for threads in [1usize, 2] {
            let (header, pos, vel) = read_owned_f64(&path, threads).unwrap();
            let n = header.position_len().unwrap();
            assert_eq!(pos.len(), n);
            assert_eq!(vel.len(), n);
            let mut raw = Vec::new();
            std::io::Read::read_to_end(&mut File::open(&path).unwrap(), &mut raw).unwrap();
            let off = raw.len() - 2 * n * 8;
            let want: Vec<f64> = raw[off..]
                .as_chunks::<8>()
                .0
                .iter()
                .map(|chunk| f64::from_le_bytes(*chunk))
                .collect();
            assert_eq!(pos.as_slice(), &want[..n]);
            assert_eq!(vel.as_slice(), &want[n..]);
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn populate_followup_touches_only_after_einval() {
        assert!(populate_followup(libc::EINVAL).is_ok());
        for code in [libc::EFAULT, libc::EIO, libc::EHWPOISON, libc::ENOMEM] {
            assert_eq!(populate_followup(code).unwrap_err(), code);
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn wait_resident_rejects_an_unaligned_address() {
        let page = page_size().unwrap();
        let ptr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                page,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                -1,
                0,
            )
        };
        assert_ne!(ptr, libc::MAP_FAILED);
        let err = wait_resident(ptr as usize + 1, 0, 1, page).unwrap_err();
        assert!(err.contains("page-aligned"), "{err}");
        unsafe { libc::munmap(ptr, page) };
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn wait_resident_returns_an_unmapped_populate_error() {
        let page = page_size().unwrap();
        // The hole sits between two mappings this test still owns, so a
        // parallel test's mmap is unlikely to land on it. A hit is retried:
        // the address is only unmapped until something else claims it.
        for _ in 0..64 {
            let ptr = unsafe {
                libc::mmap(
                    std::ptr::null_mut(),
                    page * 3,
                    libc::PROT_NONE,
                    libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                    -1,
                    0,
                )
            };
            assert_ne!(ptr, libc::MAP_FAILED);
            let hole = unsafe { (ptr as *mut u8).add(page) as *mut libc::c_void };
            unsafe { libc::munmap(hole, page) };
            let result = wait_resident(hole as usize, 0, page, page);
            unsafe { libc::munmap(ptr, page) };
            unsafe { libc::munmap((ptr as *mut u8).add(page * 2) as *mut libc::c_void, page) };
            if let Err(err) = result {
                assert!(err.contains("os error"), "{err}");
                return;
            }
        }
        panic!("madvise on an unmapped page returned success");
    }
}