readcon-core 0.23.1

An oxidized single and multiple CON file reader and writer with FFI bindings for ergonomic C/C++ usage. Implements CON spec v3.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
use crate::error::ParseError;
use crate::helpers::symbol_to_atomic_number;
use crate::types::{
    AtomDatum, ConFrame, FrameHeader, PreboxHeader, SECTION_CHARGES, SECTION_DISPLACEMENTS,
    SECTION_ENERGIES, SECTION_FORCES, SECTION_MAGMOMS, SECTION_SPINS, SECTION_SPREADS,
    SECTION_VELOCITIES, meta,
};
use serde_json::Value;
use std::iter::Peekable;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

/// Line source with peek for section detection (blank-line separators).
///
/// Implemented by the memchr cursor on the hot iterator path and by
/// `Peekable<I>` for tests / ad-hoc callers.
/// Rows of one coordinate block, in file order.
///
/// `atoms` is empty unless the caller asked for per-atom shells. The
/// numeric columns are the bytes a serial `next_coord_row` loop would
/// have stored.
#[doc(hidden)]
pub struct CoordRows {
    pub xyz: Vec<f64>,
    pub ids: Vec<u64>,
    pub flags: Vec<[bool; 3]>,
    pub atoms: Vec<crate::types::AtomDatum>,
    pub consumed: usize,
}

/// Worker count for a coordinate block that is too wide to hand to one task.
///
/// One means the calling thread parses the block. The frame iterator sets
/// this only for a single wide frame, then puts it back.
pub(crate) fn wide_workers() -> usize {
    WIDE_WORKERS.with(|slot| slot.get())
}

pub(crate) fn set_wide_workers(n: usize) {
    WIDE_WORKERS.with(|slot| slot.set(n.max(1)));
}

std::thread_local! {
    static WIDE_WORKERS: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };
}

/// Fill `n` coordinate rows.
///
/// `breaks[i]` is the absolute index of that row's `\n`. Row 0 begins at
/// `row0`. `xyz` receives `n * 3` values. `ids` and `flags` may be null
/// when the caller does not want them. `flags` is the packed column-4 mask.
#[cfg(feature = "parallel")]
pub(crate) fn fill_rows_from_breaks(
    bytes: &[u8],
    breaks: &[usize],
    row0: usize,
    spec_version: u32,
    start_id: u64,
    workers: usize,
    xyz: *mut f64,
    ids: *mut u64,
    flags: *mut u8,
) -> Result<(), ParseError> {
    let n = breaks.len();
    if n == 0 {
        return Ok(());
    }
    let chunk = n.div_ceil(workers.max(1)).max(1);
    let groups = n.div_ceil(chunk);
    let xyz_ptr = xyz as usize;
    let ids_ptr = ids as usize;
    let flags_ptr = flags as usize;
    let fill = || {
        use rayon::prelude::*;
        (0..groups).into_par_iter().try_for_each(|group| {
            let first = group * chunk;
            let last = (first + chunk).min(n);
            for row_index in first..last {
                let start = if row_index == 0 {
                    row0
                } else {
                    breaks[row_index - 1] + 1
                };
                let end = breaks[row_index] + 1;
                if end > bytes.len() || start > end {
                    return Err(ParseError::IncompleteFrame);
                }
                let default_id = start_id + row_index as u64;
                let ((row, fixed, atom_id), _next) =
                    parse_coord_row_at(&bytes[start..end], 0, spec_version, default_id)?;
                unsafe {
                    std::ptr::copy_nonoverlapping(
                        row.as_ptr(),
                        (xyz_ptr as *mut f64).add(row_index * 3),
                        3,
                    );
                    if ids_ptr != 0 {
                        *((ids_ptr as *mut u64).add(row_index)) = atom_id;
                    }
                    if flags_ptr != 0 {
                        let mask = u8::from(fixed[0])
                            | (u8::from(fixed[1]) << 1)
                            | (u8::from(fixed[2]) << 2);
                        *((flags_ptr as *mut u8).add(row_index)) = mask;
                    }
                }
            }
            Ok(())
        })
    };
    on_pool(workers, fill)
}

/// Run `body` on a pool of `workers` threads.
///
/// The pool for a given size is kept for the process. Building one per
/// call was a serial pause on the wide-frame read and the row formatter.
#[cfg(feature = "parallel")]
pub(crate) fn on_pool<T: Send>(workers: usize, body: impl FnOnce() -> T + Send) -> T {
    if workers < 2 {
        return body();
    }
    // The cached pool is leaked for the process. Miri rejects a thread
    // that is still running when the test binary exits, so it builds a
    // pool, runs `body`, and joins.
    #[cfg(miri)]
    {
        return match rayon::ThreadPoolBuilder::new().num_threads(workers).build() {
            Ok(pool) => pool.install(body),
            Err(_) => body(),
        };
    }
    #[cfg(not(miri))]
    {
        let pool = {
            use std::sync::{Mutex, OnceLock};
            static POOLS: OnceLock<Mutex<Vec<(usize, &'static rayon::ThreadPool)>>> =
                OnceLock::new();
            let pools = POOLS.get_or_init(|| Mutex::new(Vec::new()));
            let mut guard = pools.lock().unwrap_or_else(|err| err.into_inner());
            if let Some((_, pool)) = guard.iter().find(|(size, _)| *size == workers) {
                *pool
            } else {
                let next_core = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
                let built = match rayon::ThreadPoolBuilder::new()
                    .num_threads(workers)
                    .spawn_handler(move |thread| {
                        // One worker per physical core. Leaving the placement to
                        // the kernel put two of these on one core and left
                        // another idle, which is the whole 8-thread gap.
                        let core = next_core.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        std::thread::Builder::new().spawn(move || {
                            pin_worker(core);
                            thread.run();
                        })?;
                        Ok(())
                    })
                    .build()
                {
                    Ok(pool) => pool,
                    Err(_) => return body(),
                };
                let pool: &'static rayon::ThreadPool = Box::leak(Box::new(built));
                guard.push((workers, pool));
                pool
            }
        };
        pool.install(body)
    }
}

pub(crate) fn pin_worker(core: usize) {
    // `sched_setaffinity` is Linux. Pinning is a performance hint.
    #[cfg(all(not(miri), target_os = "linux"))]
    unsafe {
        let mut set: libc::cpu_set_t = std::mem::zeroed();
        libc::CPU_ZERO(&mut set);
        libc::CPU_SET(core, &mut set);
        libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set);
    }
    #[cfg(any(miri, not(target_os = "linux")))]
    {
        let _ = core;
    }
}

/// Coordinate rows in `bytes`, which begins at the first row.
///
/// `n` rows are required. The returned `consumed` count is the number of
/// bytes those rows occupy, including their newlines. `symbol` builds the
/// per-atom shells; `None` leaves `atoms` empty. A structural miss returns
/// `Err` and the caller keeps the serial loop.
#[cfg(feature = "parallel")]
pub(crate) fn parallel_coord_rows(
    bytes: &[u8],
    n: usize,
    spec_version: u32,
    start_id: u64,
    workers: usize,
    symbol: Option<&std::sync::Arc<str>>,
) -> Result<CoordRows, ParseError> {
    if n == 0 {
        return Ok(CoordRows {
            xyz: Vec::new(),
            ids: Vec::new(),
            flags: Vec::new(),
            atoms: Vec::new(),
            consumed: 0,
        });
    }
    // Same chunking as the column reader: count newlines, then each worker
    // walks its own run. An offset per line was a serial pass the plain
    // read does not pay.
    let (chunks, consumed) = plan_coord_chunks(bytes, 0, n, workers.max(1))?;
    let mut xyz = Vec::<f64>::with_capacity(n.saturating_mul(3));
    let mut ids = Vec::<u64>::with_capacity(n);
    let mut flags = Vec::<[bool; 3]>::with_capacity(n);
    let mut atoms_raw: Vec<std::mem::MaybeUninit<crate::types::AtomDatum>> = Vec::new();
    if symbol.is_some() {
        atoms_raw = Vec::with_capacity(n);
        unsafe { atoms_raw.set_len(n) };
    }
    let xyz_ptr = xyz.as_mut_ptr() as usize;
    let ids_ptr = ids.as_mut_ptr() as usize;
    let flags_ptr = flags.as_mut_ptr() as usize;
    let atoms_ptr = atoms_raw.as_mut_ptr() as usize;
    let mut row0 = Vec::with_capacity(chunks.len());
    let mut acc = 0usize;
    for (_, nrows) in &chunks {
        row0.push(acc);
        acc += *nrows;
    }
    let fill_chunk = |index: usize| -> Result<(), ParseError> {
        let (start, nrows) = chunks[index];
        let mut row = row0[index];
        let mut pos = start;
        let mut shares = symbol.map(|symbol| symbol_shares(symbol, nrows));
        for _ in 0..nrows {
            let ((xyz, fixed, atom_id), next) =
                parse_coord_row_at(bytes, pos, spec_version, start_id + row as u64)?;
            unsafe {
                std::ptr::copy_nonoverlapping(xyz.as_ptr(), (xyz_ptr as *mut f64).add(row * 3), 3);
                *((ids_ptr as *mut u64).add(row)) = atom_id;
                *((flags_ptr as *mut [bool; 3]).add(row)) = fixed;
                if let Some(shares) = shares.as_mut() {
                    let slot = (xyz_ptr as *mut f64).add(row * 3);
                    let atom =
                        crate::types::AtomDatum::at_slot(shares.take(), slot, fixed, atom_id);
                    (*(atoms_ptr as *mut std::mem::MaybeUninit<crate::types::AtomDatum>).add(row))
                        .write(atom);
                }
            }
            pos = next;
            row += 1;
        }
        Ok(())
    };
    let built = if workers < 2 || chunks.len() < 2 {
        (0..chunks.len()).try_for_each(fill_chunk)
    } else {
        on_pool(workers, || {
            use rayon::prelude::*;
            (0..chunks.len()).into_par_iter().try_for_each(fill_chunk)
        })
    };
    if let Err(err) = built {
        std::mem::forget(atoms_raw);
        return Err(err);
    }
    // SAFETY: every row was written before `built` returned Ok. The
    // length stays 0 on the error path above.
    unsafe {
        xyz.set_len(n * 3);
        ids.set_len(n);
        flags.set_len(n);
    }
    let atoms = if symbol.is_some() {
        let mut raw = std::mem::ManuallyDrop::new(atoms_raw);
        unsafe {
            Vec::from_raw_parts(
                raw.as_mut_ptr() as *mut crate::types::AtomDatum,
                n,
                raw.capacity(),
            )
        }
    } else {
        Vec::new()
    };
    Ok(CoordRows {
        xyz,
        ids,
        flags,
        atoms,
        consumed,
    })
}

/// Walk `nrows` coordinate lines starting at byte `start`.
///
/// `row_base` is the first row's index in `xyz` / `ids` / `flags` / `atoms`.
/// This is the per-member kernel of [`fill_rows_from_chunks`], so a worker
/// can parse a slice as soon as that slice has been inflated.
#[cfg(feature = "parallel")]
pub(crate) fn parse_coord_run(
    bytes: &[u8],
    start: usize,
    nrows: usize,
    spec_version: u32,
    row_base: usize,
    symbol: Option<&std::sync::Arc<str>>,
    xyz: *mut f64,
    ids: *mut u64,
    flags: *mut [bool; 3],
    atoms: *mut std::mem::MaybeUninit<crate::types::AtomDatum>,
) -> Result<usize, ParseError> {
    let mut pos = start;
    let mut shares = symbol.map(|symbol| symbol_shares(symbol, nrows));
    for step in 0..nrows {
        let row = row_base + step;
        let ((xyz_row, fixed, atom_id), next) =
            parse_coord_row_at(bytes, pos, spec_version, row as u64)?;
        unsafe {
            let dest = xyz.add(row * 3);
            std::ptr::copy_nonoverlapping(xyz_row.as_ptr(), dest, 3);
            *ids.add(row) = atom_id;
            *flags.add(row) = fixed;
            if let Some(shares) = shares.as_mut() {
                let atom = crate::types::AtomDatum::at_slot(shares.take(), dest, fixed, atom_id);
                (*atoms.add(row)).write(atom);
            }
        }
        pos = next;
    }
    Ok(pos)
}

#[cfg(feature = "parallel")]
#[allow(dead_code)]
fn coord_line_ranges(
    bytes: &[u8],
    n: usize,
    workers: usize,
) -> Result<Vec<(usize, usize)>, ParseError> {
    let newlines = newline_index(bytes, workers);
    let mut ranges = Vec::with_capacity(n);
    let mut start = 0usize;
    for index in 0..n {
        if start > bytes.len() {
            return Err(ParseError::IncompleteFrame);
        }
        let end = if index < newlines.len() {
            newlines[index] + 1
        } else if index == newlines.len() && start < bytes.len() {
            bytes.len()
        } else {
            return Err(ParseError::IncompleteFrame);
        };
        if end < start {
            return Err(ParseError::IncompleteFrame);
        }
        ranges.push((start, end));
        start = end;
    }
    Ok(ranges)
}

/// Newline positions in `bytes`.
///
/// Chunks are cut on byte boundaries, then each interior cut that lands
/// inside a line is moved to the next newline so a row is not split.
/// Workers count those newlines, a prefix sum places each run, and the
/// same workers write the offsets. The offset array is not zeroed, so
/// the writer is the first touch. `workers < 2` scans on the calling thread.
#[cfg(feature = "parallel")]
pub(crate) fn newline_index(bytes: &[u8], workers: usize) -> Vec<usize> {
    newline_index_at(bytes, 0, workers)
}

/// [`newline_index`] with `base` added to every stored offset.
#[cfg(feature = "parallel")]
pub(crate) fn newline_index_at(bytes: &[u8], base: usize, workers: usize) -> Vec<usize> {
    if bytes.is_empty() || workers < 2 || bytes.len() < (1 << 20) {
        return memchr::memchr_iter(b'\n', bytes)
            .map(|index| base + index)
            .collect();
    }
    let cuts = newline_cuts(bytes, workers);
    newline_index_exact(&cuts, bytes, base)
}

/// One cache line, so adjacent chunk counters do not share a line.
#[cfg(feature = "parallel")]
#[derive(Clone)]
#[repr(C, align(64))]
struct ChunkTally {
    n: usize,
}

#[cfg(feature = "parallel")]
pub(crate) fn newline_cuts(bytes: &[u8], workers: usize) -> Vec<usize> {
    let workers = workers.min(bytes.len()).max(1);
    let mut cuts = Vec::with_capacity(workers + 1);
    cuts.push(0usize);
    for index in 1..workers {
        let mut at = index * bytes.len() / workers;
        // A cut in the middle of a row belongs to the chunk that holds
        // the newline. Move it to the first byte after that newline.
        if at > 0 && at < bytes.len() && bytes[at - 1] != b'\n' {
            if let Some(rel) = memchr::memchr(b'\n', &bytes[at..]) {
                at += rel + 1;
            } else {
                at = bytes.len();
            }
        }
        if cuts.last().copied() != Some(at) {
            cuts.push(at);
        }
    }
    if cuts.last().copied() != Some(bytes.len()) {
        cuts.push(bytes.len());
    }
    cuts
}

/// Count newlines in each `cuts` window. One store per chunk, so the
/// counters do not bounce a cache line during the scan.
#[cfg(feature = "parallel")]
fn count_newline_chunks(bytes: &[u8], cuts: &[usize]) -> Vec<usize> {
    let nchunks = cuts.len().saturating_sub(1);
    let mut tallies = vec![ChunkTally { n: 0 }; nchunks];
    if nchunks == 0 {
        return Vec::new();
    }
    let ptr = tallies.as_mut_ptr() as usize;
    let count = || {
        use rayon::prelude::*;
        (0..nchunks).into_par_iter().for_each(|index| {
            let n = memchr::memchr_iter(b'\n', &bytes[cuts[index]..cuts[index + 1]]).count();
            unsafe {
                (*(ptr as *mut ChunkTally).add(index)).n = n;
            }
        });
    };
    if nchunks < 2 {
        count();
    } else {
        on_pool(nchunks, count);
    }
    tallies.into_iter().map(|tally| tally.n).collect()
}

/// Byte start and row count for each worker that parses `n_rows`
/// coordinate lines beginning at `start`.
///
/// The newline *count* places the rows. Workers then parse their own
/// slice in order, so the read does not materialise an offset per line.
/// The returned end is the first byte after the `n_rows`-th newline.
#[cfg(feature = "parallel")]
pub(crate) fn plan_coord_chunks(
    bytes: &[u8],
    start: usize,
    n_rows: usize,
    workers: usize,
) -> Result<(Vec<(usize, usize)>, usize), ParseError> {
    if n_rows == 0 {
        return Ok((Vec::new(), start));
    }
    if start >= bytes.len() {
        return Err(ParseError::IncompleteFrame);
    }
    let mut window = n_rows.saturating_mul(96).max(1);
    loop {
        let end = start.saturating_add(window).min(bytes.len());
        let region = &bytes[start..end];
        let cuts = newline_cuts(region, workers);
        let counts = count_newline_chunks(region, &cuts);
        let total: usize = counts.iter().sum();
        if total >= n_rows || end == bytes.len() {
            if total < n_rows {
                return Err(ParseError::IncompleteFrame);
            }
            return chunks_from_counts(bytes, start, &cuts, &counts, n_rows);
        }
        window = window.saturating_mul(2);
    }
}

#[cfg(feature = "parallel")]
fn chunks_from_counts(
    bytes: &[u8],
    start: usize,
    cuts: &[usize],
    counts: &[usize],
    n_rows: usize,
) -> Result<(Vec<(usize, usize)>, usize), ParseError> {
    let mut need = n_rows;
    let mut chunks = Vec::new();
    let mut end_abs = start;
    for index in 0..counts.len() {
        if need == 0 {
            break;
        }
        let have = counts[index];
        if have == 0 {
            continue;
        }
        let from = start + cuts[index];
        let to = start + cuts[index + 1];
        let take = have.min(need);
        let chunk_end = if take == have && to > from && bytes[to - 1] == b'\n' {
            to
        } else {
            let mut seen = 0usize;
            let mut found = None;
            for rel in memchr::memchr_iter(b'\n', &bytes[from..to]) {
                seen += 1;
                if seen == take {
                    found = Some(from + rel + 1);
                    break;
                }
            }
            found.ok_or(ParseError::IncompleteFrame)?
        };
        chunks.push((from, take));
        end_abs = chunk_end;
        need -= take;
    }
    if need != 0 {
        return Err(ParseError::IncompleteFrame);
    }
    Ok((chunks, end_abs))
}

/// Parse coordinate rows described by [`plan_coord_chunks`].
///
/// Each chunk is a contiguous run of lines. The worker walks that run
/// and writes `nrows` coordinates at the prefix-summed row.
#[cfg(feature = "parallel")]
pub(crate) fn fill_rows_from_chunks(
    bytes: &[u8],
    chunks: &[(usize, usize)],
    spec_version: u32,
    start_id: u64,
    workers: usize,
    xyz: *mut f64,
    ids: *mut u64,
    flags: *mut u8,
) -> Result<(), ParseError> {
    if chunks.is_empty() {
        return Ok(());
    }
    let mut row0 = Vec::with_capacity(chunks.len());
    let mut acc = 0usize;
    for (_, nrows) in chunks {
        row0.push(acc);
        acc += *nrows;
    }
    let xyz_ptr = xyz as usize;
    let ids_ptr = ids as usize;
    let flags_ptr = flags as usize;
    let fill = || {
        use rayon::prelude::*;
        chunks
            .par_iter()
            .zip(row0.par_iter().copied())
            .try_for_each(|(&(start, nrows), mut row)| {
                let mut pos = start;
                for _ in 0..nrows {
                    let ((xyz, fixed, atom_id), next) =
                        parse_coord_row_at(bytes, pos, spec_version, start_id + row as u64)?;
                    unsafe {
                        std::ptr::copy_nonoverlapping(
                            xyz.as_ptr(),
                            (xyz_ptr as *mut f64).add(row * 3),
                            3,
                        );
                        if ids_ptr != 0 {
                            *((ids_ptr as *mut u64).add(row)) = atom_id;
                        }
                        if flags_ptr != 0 {
                            let mask = u8::from(fixed[0])
                                | (u8::from(fixed[1]) << 1)
                                | (u8::from(fixed[2]) << 2);
                            *((flags_ptr as *mut u8).add(row)) = mask;
                        }
                    }
                    pos = next;
                    row += 1;
                }
                Ok(())
            })
    };
    if workers < 2 {
        let mut row_at = 0usize;
        for &(start, nrows) in chunks {
            let mut pos = start;
            for _ in 0..nrows {
                let ((row_xyz, fixed, atom_id), next) =
                    parse_coord_row_at(bytes, pos, spec_version, start_id + row_at as u64)?;
                unsafe {
                    std::ptr::copy_nonoverlapping(row_xyz.as_ptr(), xyz.add(row_at * 3), 3);
                    if ids_ptr != 0 {
                        *((ids_ptr as *mut u64).add(row_at)) = atom_id;
                    }
                    if flags_ptr != 0 {
                        let mask = u8::from(fixed[0])
                            | (u8::from(fixed[1]) << 1)
                            | (u8::from(fixed[2]) << 2);
                        *((flags_ptr as *mut u8).add(row_at)) = mask;
                    }
                }
                pos = next;
                row_at += 1;
            }
        }
        Ok(())
    } else if chunks.len() < 2 {
        fill()
    } else {
        on_pool(workers, fill)
    }
}

/// Exact index: count, prefix sum, then store into an unzeroed buffer.
#[cfg(feature = "parallel")]
fn newline_index_exact(cuts: &[usize], bytes: &[u8], base: usize) -> Vec<usize> {
    let nchunks = cuts.len() - 1;
    let counts = count_newline_chunks(bytes, cuts);
    let mut slots = vec![0usize; nchunks];
    let mut total = 0usize;
    for index in 0..nchunks {
        slots[index] = total;
        total += counts[index];
    }
    let mut out = Vec::<usize>::with_capacity(total);
    let ptr = out.as_mut_ptr() as usize;
    let store = || {
        use rayon::prelude::*;
        (0..nchunks).into_par_iter().for_each(|index| {
            let from = cuts[index];
            let mut at = slots[index];
            for rel in memchr::memchr_iter(b'\n', &bytes[from..cuts[index + 1]]) {
                unsafe {
                    *((ptr as *mut usize).add(at)) = base + from + rel;
                }
                at += 1;
            }
        });
    };
    if nchunks < 2 {
        store();
    } else {
        on_pool(nchunks.max(1), store);
    }
    // SAFETY: the store wrote every index in `0..total`.
    unsafe { out.set_len(total) };
    out
}

#[cfg(feature = "parallel")]
#[allow(dead_code)]
fn write_coord_group(
    bytes: &[u8],
    group: &[(usize, usize)],
    row0: usize,
    spec_version: u32,
    start_id: u64,
    symbol: Option<&std::sync::Arc<str>>,
    xyz_ptr: usize,
    ids_ptr: usize,
    flags_ptr: usize,
    atoms_ptr: usize,
) -> Result<(), ParseError> {
    let mut shares = symbol.map(|symbol| symbol_shares(symbol, group.len()));
    for (offset, &(start, end)) in group.iter().enumerate() {
        let row_index = row0 + offset;
        let default_id = start_id + row_index as u64;
        let ((row, fixed, atom_id), _next) =
            parse_coord_row_at(&bytes[start..end], 0, spec_version, default_id)?;
        unsafe {
            std::ptr::copy_nonoverlapping(
                row.as_ptr(),
                (xyz_ptr as *mut f64).add(row_index * 3),
                3,
            );
            *((ids_ptr as *mut u64).add(row_index)) = atom_id;
            *((flags_ptr as *mut [bool; 3]).add(row_index)) = fixed;
            if let Some(shares) = shares.as_mut() {
                let slot = (xyz_ptr as *mut f64).add(row_index * 3);
                let atom = crate::types::AtomDatum::at_slot(shares.take(), slot, fixed, atom_id);
                (*(atoms_ptr as *mut std::mem::MaybeUninit<crate::types::AtomDatum>)
                    .add(row_index))
                .write(atom);
            }
        }
    }
    Ok(())
}

pub trait LineStream<'a> {
    fn next_line(&mut self) -> Option<&'a str>;
    fn peek_line(&mut self) -> Option<&'a str>;
    /// Take `n` coordinate rows starting at the cursor, or `None` to keep
    /// the one-row loop. The cursor moves only when this returns `Some`.
    fn try_take_coord_block(
        &mut self,
        _n: usize,
        _spec_version: u32,
        _start_id: u64,
        _symbol: &std::sync::Arc<str>,
        _workers: usize,
    ) -> Option<CoordRows> {
        None
    }
    /// True when every remaining line, including the current peek, is
    /// empty or whitespace. Default is false so a one-line peek cannot
    /// hide a following section.
    fn remainder_is_whitespace(&mut self) -> bool {
        false
    }
    /// Called while a blank line is peeked. True when that blank begins a
    /// section: the next line is a symbol and the line after it is a
    /// component label. A blank that does not is line 1 of the next frame.
    fn blank_line_opens_section(&mut self) -> bool {
        false
    }

    /// With a blank line peeked, true when [`Self::blank_line_opens_section`]
    /// is true. A stream that cannot look ahead keeps the legacy rule and
    /// returns true.
    fn blank_opens_velocity_block(&mut self) -> bool {
        true
    }

    /// One coordinate row, fused with the line scan when the stream can do it.
    ///
    /// The default pulls a `&str` line. [`crate::iterators::MemchrLines`]
    /// parses the row directly from the byte cursor so tokenize and numeric
    /// parse are one pass.
    fn next_coord_row(
        &mut self,
        spec_version: u32,
        default_id: u64,
    ) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
        let line = self.next_line().ok_or(ParseError::IncompleteFrame)?;
        parse_coord_row(line, spec_version, default_id)
    }

    /// One vector-section row (xyz, flag, required id), fused with the line
    /// scan when the stream can do it. End of input is [`ParseError::IncompleteFrame`];
    /// callers that are inside a named section map that to `IncompleteSection`.
    fn next_vector_row(
        &mut self,
        spec_version: u32,
    ) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
        let line = self.next_line().ok_or(ParseError::IncompleteFrame)?;
        parse_vector_section_row(line, spec_version)
    }
}

fn take_vector_row<'a>(
    lines: &mut impl LineStream<'a>,
    spec_version: u32,
    section: &str,
) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
    match lines.next_vector_row(spec_version) {
        Ok(row) => Ok(row),
        Err(ParseError::IncompleteFrame) => Err(ParseError::IncompleteSection(section.to_string())),
        Err(err) => Err(err),
    }
}

impl<'a, I> LineStream<'a> for Peekable<I>
where
    I: Iterator<Item = &'a str> + Clone,
{
    #[inline]
    fn next_line(&mut self) -> Option<&'a str> {
        Iterator::next(self)
    }
    #[inline]
    fn peek_line(&mut self) -> Option<&'a str> {
        Peekable::peek(self).copied()
    }
    fn blank_line_opens_section(&mut self) -> bool {
        let mut probe = self.clone();
        let Some(blank) = probe.next_line() else {
            return false;
        };
        if !blank.trim().is_empty() {
            return false;
        }
        section_follows(&mut probe)
    }

    fn blank_opens_velocity_block(&mut self) -> bool {
        match self.peek_line() {
            Some(line) if line.trim().is_empty() => self.blank_line_opens_section(),
            _ => true,
        }
    }
}

/// True when `line` has the words `of` and `Component` in that order.
pub(crate) fn line_has_component_label(line: &str) -> bool {
    let mut words = line.split_ascii_whitespace();
    while let Some(word) = words.next() {
        if word.eq_ignore_ascii_case("of")
            && words
                .next()
                .is_some_and(|next| next.eq_ignore_ascii_case("component"))
        {
            return true;
        }
    }
    false
}

fn section_follows<'a>(lines: &mut impl LineStream<'a>) -> bool {
    let Some(symbol) = lines.next_line() else {
        return false;
    };
    if symbol.trim().is_empty() || symbol.trim_start().starts_with('{') {
        return false;
    }
    let Some(label) = lines.next_line() else {
        return false;
    };
    line_has_component_label(label)
}

/// Length of the stack buffer of [`parse_line_of_range_f64_stack`]: the most
/// columns an atom line has, which are x, y, z, the flag and the optional id
/// (spec "Coordinates").
pub const NUMERIC_STACK_WIDTH: usize = COORD_ROW_MIN_COLUMNS + 1;

/// Hot-path: parse up to [`NUMERIC_STACK_WIDTH`] whitespace-separated f64s
/// into a stack buffer.
/// Returns count of tokens actually present (before padding).
/// Pads `out[found..max]` from `defaults` when `found < max` and `found >= min`.
///
/// Single-pass over the line bytes: skip ASCII whitespace, then
/// [`fast_float2::parse_partial`] (Eisel–Lemire / SIMD-class decimal kernel)
/// with a token-boundary check. No `SplitWhitespace`, no per-token `&str`,
/// no heap `Vec`. Prefer this over allocating [`parse_line_of_n_f64`] on atom lines.
#[inline]
pub fn parse_line_of_range_f64_stack(
    line: &str,
    min: usize,
    max: usize,
    defaults: &[f64],
    out: &mut [f64; NUMERIC_STACK_WIDTH],
) -> Result<usize, ParseError> {
    debug_assert!(max <= NUMERIC_STACK_WIDTH && min <= max && defaults.len() >= max);
    let bytes = line.as_bytes();
    let n = bytes.len();
    let mut i = 0usize;
    let mut found = 0usize;
    while found < max {
        while i < n && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= n {
            break;
        }
        let end = bytes[i..]
            .iter()
            .position(|b| b.is_ascii_whitespace())
            .map(|k| i + k)
            .unwrap_or(n);
        let token = std::str::from_utf8(&bytes[i..end]).unwrap_or("");
        if is_nonfinite_spelling(token) {
            return Err(ParseError::NonFiniteValue(token.to_string()));
        }
        let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..])
            .map_err(|_| ParseError::InvalidNumberFormat(format!("invalid float: {token}")))?;
        let next = i + consumed;
        // Reject partial tokens like "1.2abc" (must end at whitespace or EOS).
        if next != end {
            return Err(ParseError::InvalidNumberFormat(format!(
                "invalid float: {token}"
            )));
        }
        if !val.is_finite() {
            return Err(ParseError::NonFiniteValue(token.to_string()));
        }
        out[found] = val;
        found += 1;
        i = next;
    }
    while i < n && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    // Reject trailing extra tokens (same contract as the old split loop).
    if i < n {
        return Err(ParseError::InvalidVectorLength {
            expected: max,
            found: found + 1,
        });
    }
    if found < min || found > max {
        return Err(ParseError::InvalidVectorLength {
            expected: max,
            found,
        });
    }
    while found < max {
        out[found] = defaults[found];
        found += 1;
    }
    Ok(found)
}

/// Parses a line of whitespace-separated f64 values using fast-float2.
///
/// This is the hot-path parser for coordinate and velocity lines. It uses
/// `fast_float2::parse` instead of `str::parse::<f64>()` for better throughput
/// on the numeric-heavy atom data lines. Fixed-width atom lines use
/// [`parse_line_of_range_f64_stack`] to avoid a heap `Vec` per line.
///
/// # Arguments
///
/// * `line` - A string slice representing a single line of data.
/// * `n` - The exact number of f64 values expected on the line.
pub fn parse_line_of_n_f64(line: &str, n: usize) -> Result<Vec<f64>, ParseError> {
    if n <= NUMERIC_STACK_WIDTH {
        let defaults = [0.0f64; NUMERIC_STACK_WIDTH];
        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
        parse_line_of_range_f64_stack(line, n, n, &defaults, &mut buf)?;
        return Ok(buf[..n].to_vec());
    }
    let mut values = Vec::with_capacity(n.min(max_tokens_on_line(line)));
    for token in line.split_ascii_whitespace() {
        values.push(parse_finite_float_token(token)?);
    }
    if values.len() == n {
        Ok(values)
    } else {
        Err(ParseError::InvalidVectorLength {
            expected: n,
            found: values.len(),
        })
    }
}

/// Parses a line of whitespace-separated f64 values, accepting between `min`
/// and `max` values (inclusive). Returns a vector of exactly `max` elements,
/// padding with values from `defaults` when fewer than `max` are present.
///
/// Used for atom lines where column 5 (atom_index) is optional.
/// Prefer [`parse_line_of_range_f64_stack`] on the atom hot path
/// (`max <= NUMERIC_STACK_WIDTH`).
pub fn parse_line_of_range_f64(
    line: &str,
    min: usize,
    max: usize,
    defaults: &[f64],
) -> Result<Vec<f64>, ParseError> {
    if max <= NUMERIC_STACK_WIDTH {
        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
        parse_line_of_range_f64_stack(line, min, max, defaults, &mut buf)?;
        return Ok(buf[..max].to_vec());
    }
    let mut values = Vec::with_capacity(max);
    for token in line.split_ascii_whitespace() {
        values.push(parse_finite_float_token(token)?);
    }
    if values.len() < min || values.len() > max {
        return Err(ParseError::InvalidVectorLength {
            expected: max,
            found: values.len(),
        });
    }
    while values.len() < max {
        let idx = values.len();
        values.push(defaults[idx]);
    }
    Ok(values)
}

/// CON-num.1 spellings. A leading sign is optional. Case is ignored.
/// Digit and dot tokens return before any letter compare so the atom
/// hot path does not allocate.
fn is_nonfinite_spelling(token: &str) -> bool {
    let rest = token
        .strip_prefix('+')
        .or_else(|| token.strip_prefix('-'))
        .unwrap_or(token);
    match rest.as_bytes().first() {
        Some(b) if b.is_ascii_digit() || *b == b'.' => return false,
        None => return false,
        _ => {}
    }
    rest.eq_ignore_ascii_case("nan")
        || rest.eq_ignore_ascii_case("inf")
        || rest.eq_ignore_ascii_case("infinity")
}

fn parse_finite_float_token(token: &str) -> Result<f64, ParseError> {
    if is_nonfinite_spelling(token) {
        return Err(ParseError::NonFiniteValue(token.to_string()));
    }
    let (val, consumed) = fast_float2::parse_partial::<f64, _>(token.as_bytes())
        .map_err(|_| ParseError::InvalidNumberFormat(format!("invalid float: {token}")))?;
    if consumed != token.len() {
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid float: {token}"
        )));
    }
    if !val.is_finite() {
        return Err(ParseError::NonFiniteValue(token.to_string()));
    }
    Ok(val)
}

fn skip_ascii_ws(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    i
}

fn take_token(line: &str, i: usize) -> Option<(&str, usize)> {
    let bytes = line.as_bytes();
    if i >= bytes.len() {
        return None;
    }
    let mut j = i;
    while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
        j += 1;
    }
    Some((&line[i..j], j))
}

/// Column 4. A sign, a decimal point, or a value outside the spec's set
/// is `InvalidFixedFlag` in every mode (CON-mask.1, CON-mask.5, D8).
fn parse_fixed_flag(token: &str, spec_version: u32) -> Result<[bool; 3], ParseError> {
    let bad = || {
        ParseError::InvalidFixedFlag(format!(
            "column 4 flag {token:?} is not a legal integer for spec {spec_version}"
        ))
    };
    if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
        return Err(bad());
    }
    let val: u64 = token.parse::<u64>().map_err(|_| bad())?;
    if spec_version < 2 {
        return match val {
            0 => Ok([false, false, false]),
            1 => Ok([true, true, true]),
            _ => Err(bad()),
        };
    }
    if val > 7 {
        return Err(bad());
    }
    let v = val as u8;
    Ok([v & 1 != 0, v & 2 != 0, v & 4 != 0])
}

/// Column 5. Digits only, parsed as `u64`, never through `f64` (CON-id.1, D9).
/// A sign or a decimal point is `InvalidNumberFormat` at the token level.
fn parse_atom_id_token(token: &str) -> Result<u64, ParseError> {
    if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid integer: {token}"
        )));
    }
    token.parse::<u64>().map_err(|_| {
        ParseError::InvalidNumberFormat(format!("integer out of range 0..=2^64-1: {token}"))
    })
}

/// Coordinate row: three finite floats, an integer flag, and an optional id.
/// Four columns take `default_id`, the 0-based position in the frame
/// (CON-id.9). Any other width is `InvalidVectorLength` (CON-num.9).
fn parse_coord_row(
    line: &str,
    spec_version: u32,
    default_id: u64,
) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
    parse_vector_row(line, spec_version, Some(default_id))
}

/// Vector section row. The flag and id columns are required (exact width 5).
fn parse_vector_section_row(
    line: &str,
    spec_version: u32,
) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
    parse_vector_row(line, spec_version, None)
}

fn parse_vector_row(
    line: &str,
    spec_version: u32,
    default_id: Option<u64>,
) -> Result<([f64; 3], [bool; 3], u64), ParseError> {
    let (row, end) = parse_coord_fields(line.as_bytes(), 0, spec_version, default_id)?;
    if end != line.len() {
        let found = 5 + count_tokens_on_line(line.as_bytes(), end);
        return Err(ParseError::InvalidVectorLength { expected: 5, found });
    }
    Ok(row)
}

/// Field separator inside a coordinate row. Newline ends the row.
#[inline(always)]
fn is_field_ws(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\r' | 0x0c)
}

#[inline(always)]
fn skip_field_ws(bytes: &[u8], mut i: usize) -> usize {
    while i < bytes.len() && is_field_ws(bytes[i]) {
        i += 1;
    }
    i
}

fn token_on_line(bytes: &[u8], i: usize) -> String {
    let mut j = i;
    while j < bytes.len() && !is_field_ws(bytes[j]) && bytes[j] != b'\n' {
        j += 1;
    }
    String::from_utf8_lossy(&bytes[i..j]).into_owned()
}

fn count_tokens_on_line(bytes: &[u8], mut i: usize) -> usize {
    let mut n = 0usize;
    loop {
        i = skip_field_ws(bytes, i);
        if i >= bytes.len() || bytes[i] == b'\n' {
            break;
        }
        n += 1;
        while i < bytes.len() && !is_field_ws(bytes[i]) && bytes[i] != b'\n' {
            i += 1;
        }
    }
    n
}

/// Invalid UTF-8 in a numeric row, otherwise a normal number-format error.
fn utf8_or_number(bytes: &[u8], line_start: usize, i: usize) -> ParseError {
    let end = bytes[line_start..]
        .iter()
        .position(|b| *b == b'\n')
        .map(|p| line_start + p)
        .unwrap_or(bytes.len());
    if std::str::from_utf8(&bytes[line_start..end]).is_err() {
        return ParseError::ValidationError("invalid UTF-8".into());
    }
    ParseError::InvalidNumberFormat(format!("invalid float: {}", token_on_line(bytes, i)))
}

#[inline(always)]
fn parse_f64_at(bytes: &[u8], i: usize, line_start: usize) -> Result<(f64, usize), ParseError> {
    if i >= bytes.len() || bytes[i] == b'\n' {
        return Err(ParseError::InvalidVectorLength {
            expected: 5,
            found: 0,
        });
    }
    if bytes[i] >= 0x80 {
        return Err(utf8_or_number(bytes, line_start, i));
    }
    if looks_like_nonfinite(bytes, i) {
        let token = token_on_line(bytes, i);
        if is_nonfinite_spelling(&token) {
            return Err(ParseError::NonFiniteValue(token));
        }
    }
    let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..]).map_err(|_| {
        ParseError::InvalidNumberFormat(format!("invalid float: {}", token_on_line(bytes, i)))
    })?;
    let next = i + consumed;
    let boundary = next >= bytes.len() || is_field_ws(bytes[next]) || bytes[next] == b'\n';
    if !boundary || !val.is_finite() {
        let token = token_on_line(bytes, i);
        if is_nonfinite_spelling(&token) || !val.is_finite() {
            return Err(ParseError::NonFiniteValue(token));
        }
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid float: {token}"
        )));
    }
    Ok((val, next))
}

#[inline(always)]
fn parse_flag_at(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
) -> Result<([bool; 3], usize), ParseError> {
    if i >= bytes.len() || bytes[i] == b'\n' {
        return Err(ParseError::InvalidVectorLength {
            expected: 5,
            found: 3,
        });
    }
    let bad = || {
        ParseError::InvalidFixedFlag(format!(
            "column 4 flag {:?} is not a legal integer for spec {spec_version}",
            token_on_line(bytes, i)
        ))
    };
    if !bytes[i].is_ascii_digit() {
        return Err(bad());
    }
    let mut j = i;
    let mut val: u64 = 0;
    while j < bytes.len() && bytes[j].is_ascii_digit() {
        let d = u64::from(bytes[j] - b'0');
        val = val
            .checked_mul(10)
            .and_then(|v| v.checked_add(d))
            .ok_or_else(bad)?;
        j += 1;
    }
    if j < bytes.len() && !is_field_ws(bytes[j]) && bytes[j] != b'\n' {
        return Err(bad());
    }
    let fixed = if spec_version < 2 {
        match val {
            0 => [false, false, false],
            1 => [true, true, true],
            _ => return Err(bad()),
        }
    } else if val <= 7 {
        let v = val as u8;
        [v & 1 != 0, v & 2 != 0, v & 4 != 0]
    } else {
        return Err(bad());
    };
    Ok((fixed, j))
}

#[inline(always)]
fn parse_id_at(bytes: &[u8], i: usize) -> Result<(u64, usize), ParseError> {
    if i >= bytes.len() || bytes[i] == b'\n' || !bytes[i].is_ascii_digit() {
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid integer: {}",
            token_on_line(bytes, i)
        )));
    }
    let mut j = i;
    let mut val: u64 = 0;
    while j < bytes.len() && bytes[j].is_ascii_digit() {
        let d = u64::from(bytes[j] - b'0');
        val = val
            .checked_mul(10)
            .and_then(|v| v.checked_add(d))
            .ok_or_else(|| {
                ParseError::InvalidNumberFormat(format!(
                    "integer out of range 0..=2^64-1: {}",
                    token_on_line(bytes, i)
                ))
            })?;
        j += 1;
    }
    if j < bytes.len() && !is_field_ws(bytes[j]) && bytes[j] != b'\n' {
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid integer: {}",
            token_on_line(bytes, i)
        )));
    }
    Ok((val, j))
}

/// One parsed coordinate row: xyz, fixed flags, and the atom id.
type ParsedCoord = ([f64; 3], [bool; 3], u64);

/// One coordinate or vector row starting at `i`.
///
/// Stops at newline or end of `bytes` and returns the index just past the
/// row (after the newline, when one was present). Floats, the flag, and the
/// id are parsed in that single scan. The success path does not build error
/// strings; those stay on the cold fallback.
#[inline(always)]
fn parse_coord_fields(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
    default_id: Option<u64>,
) -> Result<(ParsedCoord, usize), ParseError> {
    if let Some(parsed) = parse_coord_fields_fast(bytes, i, spec_version, default_id) {
        return Ok(parsed);
    }
    parse_coord_fields_detailed(bytes, i, spec_version, default_id)
}

/// Common coordinate row: three finite decimals, a small flag, an optional id.
#[inline(always)]
fn parse_coord_fields_fast(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
    default_id: Option<u64>,
) -> Option<(ParsedCoord, usize)> {
    let mut i = skip_field_ws(bytes, i);
    let mut xyz = [0.0f64; 3];
    for dest in &mut xyz {
        if i >= bytes.len() || bytes[i] == b'\n' || bytes[i] >= 0x80 {
            return None;
        }
        let (val, next) = crate::fast_dec::parse_f64_hot(bytes, i)?;
        if next < bytes.len() && !is_field_ws(bytes[next]) && bytes[next] != b'\n' {
            return None;
        }
        *dest = val;
        i = skip_field_ws(bytes, next);
    }
    let (fixed, next) = parse_flag_fast(bytes, i, spec_version)?;
    i = skip_field_ws(bytes, next);
    let (atom_id, next) = if i >= bytes.len() || bytes[i] == b'\n' {
        (default_id?, i)
    } else {
        parse_u64_fast(bytes, i)?
    };
    i = skip_field_ws(bytes, next);
    if i < bytes.len() && bytes[i] != b'\n' {
        return None;
    }
    if i < bytes.len() && bytes[i] == b'\n' {
        i += 1;
    }
    Some(((xyz, fixed, atom_id), i))
}

#[inline(always)]
fn parse_u64_fast(bytes: &[u8], i: usize) -> Option<(u64, usize)> {
    if i >= bytes.len() || !bytes[i].is_ascii_digit() {
        return None;
    }
    let mut j = i;
    let mut val: u64 = 0;
    let mut digits = 0u32;
    while j < bytes.len() && bytes[j].is_ascii_digit() {
        digits += 1;
        // 19 digits can overflow u64; the detailed parser reports that.
        if digits > 18 {
            return None;
        }
        val = val * 10 + u64::from(bytes[j] - b'0');
        j += 1;
    }
    if j < bytes.len() && !is_field_ws(bytes[j]) && bytes[j] != b'\n' {
        return None;
    }
    Some((val, j))
}

#[inline(always)]
fn parse_flag_fast(bytes: &[u8], i: usize, spec_version: u32) -> Option<([bool; 3], usize)> {
    let (val, j) = parse_u64_fast(bytes, i)?;
    let fixed = if spec_version < 2 {
        match val {
            0 => [false, false, false],
            1 => [true, true, true],
            _ => return None,
        }
    } else if val <= 7 {
        let v = val as u8;
        [v & 1 != 0, v & 2 != 0, v & 4 != 0]
    } else {
        return None;
    };
    Some((fixed, j))
}

#[cold]
#[inline(never)]
fn parse_coord_fields_detailed(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
    default_id: Option<u64>,
) -> Result<(ParsedCoord, usize), ParseError> {
    let line_start = i;
    let mut i = skip_field_ws(bytes, i);
    if i >= bytes.len() || bytes[i] == b'\n' {
        return Err(ParseError::InvalidVectorLength {
            expected: 5,
            found: 0,
        });
    }
    let mut xyz = [0.0f64; 3];
    for (slot, dest) in xyz.iter_mut().enumerate() {
        if i >= bytes.len() || bytes[i] == b'\n' {
            return Err(ParseError::InvalidVectorLength {
                expected: 5,
                found: slot,
            });
        }
        if bytes[i] >= 0x80 {
            return Err(utf8_or_number(bytes, line_start, i));
        }
        let (val, next) = parse_f64_at(bytes, i, line_start)?;
        *dest = val;
        i = skip_field_ws(bytes, next);
    }
    let (fixed, next) = parse_flag_at(bytes, i, spec_version)?;
    i = skip_field_ws(bytes, next);
    let (atom_id, next) = if i >= bytes.len() || bytes[i] == b'\n' {
        (
            default_id.ok_or(ParseError::InvalidVectorLength {
                expected: 5,
                found: 4,
            })?,
            i,
        )
    } else {
        parse_id_at(bytes, i)?
    };
    i = skip_field_ws(bytes, next);
    if i < bytes.len() && bytes[i] != b'\n' {
        let found = 5 + count_tokens_on_line(bytes, i);
        return Err(ParseError::InvalidVectorLength { expected: 5, found });
    }
    if i < bytes.len() && bytes[i] == b'\n' {
        i += 1;
    }
    Ok(((xyz, fixed, atom_id), i))
}

/// Coordinate row at byte offset `i` in a multi-line buffer.
///
/// The returned index is the start of the next line. ASCII rows are valid
/// UTF-8 without a separate scan; a non-ASCII byte is checked only then.
pub(crate) fn parse_coord_row_at(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
    default_id: u64,
) -> Result<(ParsedCoord, usize), ParseError> {
    if i >= bytes.len() {
        return Err(ParseError::IncompleteFrame);
    }
    parse_coord_fields(bytes, i, spec_version, Some(default_id))
}

/// Vector-section row at `i`. The id column is required.
pub(crate) fn parse_vector_row_at(
    bytes: &[u8],
    i: usize,
    spec_version: u32,
) -> Result<(ParsedCoord, usize), ParseError> {
    if i >= bytes.len() {
        return Err(ParseError::IncompleteFrame);
    }
    parse_coord_fields(bytes, i, spec_version, None)
}

/// Scalar section row: one finite float, a flag, and an id. Exact width 3.
fn parse_scalar_section_row(
    line: &str,
    spec_version: u32,
) -> Result<(f64, [bool; 3], u64), ParseError> {
    let bytes = line.as_bytes();
    let i = skip_ascii_ws(bytes, 0);
    let (value, i) = parse_finite_at(line, i)?;
    let i = skip_ascii_ws(bytes, i);
    let (flag_tok, i) = take_token(line, i).ok_or(ParseError::InvalidVectorLength {
        expected: 3,
        found: 1,
    })?;
    let fixed = parse_fixed_flag(flag_tok, spec_version)?;
    let i = skip_ascii_ws(bytes, i);
    let (id_tok, i) = take_token(line, i).ok_or(ParseError::InvalidVectorLength {
        expected: 3,
        found: 2,
    })?;
    let atom_id = parse_atom_id_token(id_tok)?;
    let i = skip_ascii_ws(bytes, i);
    if i < bytes.len() {
        let found = 3 + line[i..].split_ascii_whitespace().count();
        return Err(ParseError::InvalidVectorLength { expected: 3, found });
    }
    Ok((value, fixed, atom_id))
}

fn parse_finite_at(line: &str, i: usize) -> Result<(f64, usize), ParseError> {
    let bytes = line.as_bytes();
    if i >= bytes.len() {
        return Err(ParseError::InvalidVectorLength {
            expected: 3,
            found: 0,
        });
    }
    // "infinity" parses as the prefix "inf" in fast_float2. Name that
    // spelling before the numeric kernel so the leftover is not a format error.
    if looks_like_nonfinite(bytes, i) {
        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
        if is_nonfinite_spelling(token) {
            return Err(ParseError::NonFiniteValue(token.to_string()));
        }
    }
    let (val, consumed) = fast_float2::parse_partial::<f64, _>(&bytes[i..]).map_err(|_| {
        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
        ParseError::InvalidNumberFormat(format!("invalid float: {token}"))
    })?;
    let next = i + consumed;
    let boundary = next == bytes.len() || bytes[next].is_ascii_whitespace();
    if !boundary || !val.is_finite() {
        let token = take_token(line, i).map(|(tok, _)| tok).unwrap_or("");
        if is_nonfinite_spelling(token) || !val.is_finite() {
            return Err(ParseError::NonFiniteValue(token.to_string()));
        }
        return Err(ParseError::InvalidNumberFormat(format!(
            "invalid float: {token}"
        )));
    }
    Ok((val, next))
}

/// True when the token may be a non-finite spelling. Digit and dot
/// tokens, the common atom-line case, are false after one byte.
fn looks_like_nonfinite(bytes: &[u8], i: usize) -> bool {
    let mut j = i;
    if bytes[j] == b'+' || bytes[j] == b'-' {
        j += 1;
        if j >= bytes.len() {
            return false;
        }
    }
    let b = bytes[j];
    !b.is_ascii_digit() && b != b'.'
}

/// Case-insensitive, after collapsing each run of spaces (CON-file.5, D17).
fn labels_equal(found: &str, expected: &str) -> bool {
    let mut found_words = found.split_ascii_whitespace();
    let mut expected_words = expected.split_ascii_whitespace();
    loop {
        match (found_words.next(), expected_words.next()) {
            (Some(a), Some(b)) => {
                if !a.eq_ignore_ascii_case(b) {
                    return false;
                }
            }
            (None, None) => return true,
            _ => return false,
        }
    }
}

/// True when `line`, after the same folding, starts with every word of `prefix`.
fn label_has_prefix(line: &str, prefix: &str) -> bool {
    let mut found_words = line.split_ascii_whitespace();
    for word in prefix.split_ascii_whitespace() {
        match found_words.next() {
            Some(got) if got.eq_ignore_ascii_case(word) => {}
            _ => return false,
        }
    }
    true
}

fn token_count(line: &str) -> usize {
    line.split_ascii_whitespace().count()
}

/// Most whitespace-separated tokens `line` can hold.
///
/// `k` tokens take at least one byte each and one separator between each
/// pair, `2k - 1` bytes in all.
fn max_tokens_on_line(line: &str) -> usize {
    line.len().div_ceil(2)
}

fn json_u64(value: &Value) -> Option<u64> {
    value.as_u64()
}

fn validate_section_arity_value(value: &Value) -> Result<(), ParseError> {
    let obj = value.as_object().ok_or_else(|| {
        metadata_json_error("section_arity must be an object mapping section names to integers")
    })?;
    for (name, entry) in obj {
        let n = json_u64(entry).ok_or_else(|| {
            metadata_json_error(format!("section_arity.{name} must be an integer >= 1"))
        })?;
        if n < 1 {
            return Err(ParseError::InvalidCount(format!(
                "section_arity.{name} must be >= 1"
            )));
        }
        // Reserved names have a fixed value-field count (CON-section.13).
        if let Some(expect) = crate::types::reserved_section_value_arity(name)
            && n != expect
        {
            return Err(ParseError::InvalidVectorLength {
                expected: usize::try_from(expect).unwrap_or(usize::MAX),
                found: usize::try_from(n).unwrap_or(usize::MAX),
            });
        }
    }
    Ok(())
}

/// Integer counts. A sign, a decimal point, or any other non-digit token
/// is `InvalidCount` (CON-error.3). Zero is a legal token here. The caller
/// rejects a per-type count of 0 when the type count is 1 or more (D4).
pub(crate) fn parse_count_line(line: &str, n: usize) -> Result<Vec<usize>, ParseError> {
    let mut values = Vec::with_capacity(n.min(max_tokens_on_line(line)));
    for token in line.split_ascii_whitespace() {
        if token.is_empty() || !token.bytes().all(|b| b.is_ascii_digit()) {
            return Err(ParseError::InvalidCount(format!(
                "count field is not an unsigned integer: {token}"
            )));
        }
        let val: u64 = token.parse::<u64>().map_err(|_| {
            ParseError::InvalidCount(format!("count field is out of range: {token}"))
        })?;
        let val = usize::try_from(val).map_err(|_| {
            ParseError::InvalidCount(format!("count field is out of range: {token}"))
        })?;
        values.push(val);
    }
    if values.len() == n {
        Ok(values)
    } else {
        Err(ParseError::InvalidVectorLength {
            expected: n,
            found: values.len(),
        })
    }
}

/// True when `line` has no tokens. Spaces and tabs count as empty.
pub(crate) fn line_is_whitespace(line: &str) -> bool {
    line.split_ascii_whitespace().next().is_none()
}

/// Lines 8 and 9 of a type count of 0.
///
/// A token on either line is `InvalidCount`. At end of file, a missing
/// line is empty (CON-count.4), and that frame is not `IncompleteHeader`
/// (CON-frame.3). Mid-file, both lines are required.
pub(crate) fn read_zero_atom_tail<'a>(
    mut next_line: impl FnMut() -> Option<&'a str>,
) -> Result<(), ParseError> {
    let bad = || {
        ParseError::InvalidCount("a zero-atom frame requires whitespace-only lines 8 and 9".into())
    };
    match next_line() {
        None => Ok(()),
        Some(line) if line_is_whitespace(line) => match next_line() {
            None => Ok(()),
            Some(line) if line_is_whitespace(line) => Ok(()),
            Some(_) => Err(bad()),
        },
        Some(_) => Err(bad()),
    }
}

fn metadata_json_error(message: impl Into<String>) -> ParseError {
    ParseError::InvalidMetadataJson(message.into())
}

fn validate_metadata_number(key: &str, value: &Value) -> Result<(), ParseError> {
    if value.as_f64().is_some() {
        Ok(())
    } else {
        Err(metadata_json_error(format!(
            "{key} must be a finite number"
        )))
    }
}

fn validate_metadata_integer(key: &str, value: &Value) -> Result<(), ParseError> {
    if value.as_u64().is_some() {
        Ok(())
    } else {
        Err(metadata_json_error(format!(
            "{key} must be a non-negative integer"
        )))
    }
}

/// Validates a parsed metadata JSON object against the spec v2 schema.
///
/// Type-checks the `validate` and `sections` keys, then runs per-key
/// schema checks for the recommended metadata keys. Used by the
/// builder/Python `set_metadata_json` paths to fail fast on malformed
/// input, and by the parser when the file requested strict validation
/// via `"validate": true`.
pub fn validate_metadata_schema(
    json_obj: &serde_json::Map<String, Value>,
) -> Result<(), ParseError> {
    let strict_requested = match json_obj.get(meta::VALIDATE) {
        Some(Value::Bool(b)) => *b,
        Some(_) => return Err(metadata_json_error("validate must be a boolean")),
        None => false,
    };

    match json_obj.get(meta::SECTIONS) {
        Some(Value::Array(values)) => {
            if values.iter().any(|entry| !entry.is_string()) {
                return Err(metadata_json_error("sections must be an array of strings"));
            }
        }
        Some(_) => return Err(metadata_json_error("sections must be an array of strings")),
        None if strict_requested => {
            return Err(metadata_json_error(
                "validate=true requires a sections array, even when empty",
            ));
        }
        None => {}
    }

    for (key, value) in json_obj {
        match key.as_str() {
            meta::CON_SPEC_VERSION | meta::SECTIONS | meta::VALIDATE => {}
            meta::CON_SPEC_MINOR => {
                if json_u64(value).is_none() {
                    return Err(metadata_json_error(
                        "con_spec_minor must be a JSON integer >= 0",
                    ));
                }
            }
            meta::SECTION_ARITY => validate_section_arity_value(value)?,
            meta::ENERGY
            | meta::TIME
            | meta::TIMESTEP
            | meta::CONVERGENCE_FMAX
            | meta::CONVERGENCE_ENERGY
            | meta::FMAX => validate_metadata_number(key, value)?,
            meta::FRAME_INDEX | meta::NEB_BEAD | meta::NEB_BAND => {
                validate_metadata_integer(key, value)?
            }
            meta::GENERATOR if !value.is_string() => {
                return Err(metadata_json_error("generator must be a string"));
            }
            meta::GENERATOR => {}
            meta::UNITS | meta::POTENTIAL if !value.is_object() => {
                return Err(metadata_json_error(format!("{key} must be an object")));
            }
            meta::POTENTIAL => {
                if let Some(potential_type) = value.get("type")
                    && !potential_type.is_string()
                {
                    return Err(metadata_json_error("potential.type must be a string"));
                }
            }
            meta::UNITS => {
                // Full v3 checks (required keys) run when con_spec_version >= 3.
            }
            meta::PBC => validate_pbc_metadata(value)?,
            meta::BONDS => validate_bonds_metadata(value)?,
            meta::LATTICE_VECTORS => validate_lattice_vectors_metadata(value)?,
            meta::CONVERGED if !value.is_boolean() => {
                return Err(metadata_json_error("converged must be a boolean"));
            }
            meta::CONVERGED => {}
            _ => {}
        }
    }

    Ok(())
}

fn validate_pbc_metadata(value: &Value) -> Result<(), ParseError> {
    let Some(values) = value.as_array() else {
        return Err(metadata_json_error("pbc must be a length-3 boolean array"));
    };
    if values.len() != 3 || values.iter().any(|entry| !entry.is_boolean()) {
        return Err(metadata_json_error("pbc must be a length-3 boolean array"));
    }
    Ok(())
}

/// Validate optional `bonds` frame topology metadata.
///
/// Each element is either a length-2 non-negative integer pair `[i, j]` or an
/// object `{"i": i, "j": j, "order"?: integer}`. Indices are 0-based into
/// `atom_data` order (parser does not yet know atom count at metadata time;
/// bounds are enforced when projecting to chemfiles / selection).
fn validate_bonds_metadata(value: &Value) -> Result<(), ParseError> {
    let Some(items) = value.as_array() else {
        return Err(metadata_json_error("bonds must be an array"));
    };
    for (idx, item) in items.iter().enumerate() {
        if let Some(pair) = item.as_array() {
            if pair.len() != 2 {
                return Err(metadata_json_error(format!(
                    "bonds[{idx}] pair must have exactly two indices"
                )));
            }
            for (k, entry) in pair.iter().enumerate() {
                let Some(n) = entry.as_u64() else {
                    return Err(metadata_json_error(format!(
                        "bonds[{idx}][{k}] must be a non-negative integer"
                    )));
                };
                if n > u32::MAX as u64 {
                    return Err(metadata_json_error(format!(
                        "bonds[{idx}][{k}] index exceeds u32"
                    )));
                }
            }
            continue;
        }
        if let Some(obj) = item.as_object() {
            for key in ["i", "j"] {
                let Some(entry) = obj.get(key) else {
                    return Err(metadata_json_error(format!(
                        "bonds[{idx}] object must include \"{key}\""
                    )));
                };
                let Some(n) = entry.as_u64() else {
                    return Err(metadata_json_error(format!(
                        "bonds[{idx}].{key} must be a non-negative integer"
                    )));
                };
                if n > u32::MAX as u64 {
                    return Err(metadata_json_error(format!(
                        "bonds[{idx}].{key} index exceeds u32"
                    )));
                }
            }
            if let Some(order) = obj.get("order")
                && order.as_i64().is_none()
            {
                return Err(metadata_json_error(format!(
                    "bonds[{idx}].order must be an integer when present"
                )));
            }
            continue;
        }
        return Err(metadata_json_error(format!(
            "bonds[{idx}] must be [i, j] or {{\"i\": i, \"j\": j, \"order\"?: ...}}"
        )));
    }
    Ok(())
}

fn validate_lattice_vectors_metadata(value: &Value) -> Result<(), ParseError> {
    let Some(rows) = value.as_array() else {
        return Err(metadata_json_error(
            "lattice_vectors must be a 3x3 numeric array",
        ));
    };
    if rows.len() != 3 {
        return Err(metadata_json_error(
            "lattice_vectors must be a 3x3 numeric array",
        ));
    }
    for row in rows {
        let Some(entries) = row.as_array() else {
            return Err(metadata_json_error(
                "lattice_vectors must be a 3x3 numeric array",
            ));
        };
        if entries.len() != 3 || entries.iter().any(|entry| entry.as_f64().is_none()) {
            return Err(metadata_json_error(
                "lattice_vectors must be a 3x3 numeric array",
            ));
        }
    }
    Ok(())
}

/// Parses a line of whitespace-separated values into a vector of a specific type.
///
/// This generic helper function takes a string slice, splits it by whitespace,
/// and attempts to parse each substring into the target type `T`. The type `T`
/// must implement `std::str::FromStr`.
///
/// # Arguments
///
/// * `line` - A string slice representing a single line of data.
/// * `n` - The exact number of values expected on the line.
///
/// # Errors
///
/// * `ParseError::InvalidVectorLength` if the number of parsed values is not equal to `n`.
/// * Propagates any error from the `parse()` method of the target type `T`.
///
/// # Example
///
/// ```
/// use readcon_core::parser::parse_line_of_n;
/// let line = "10.5 20.0 30.5";
/// let values: Vec<f64> = parse_line_of_n(line, 3).unwrap();
/// assert_eq!(values, vec![10.5, 20.0, 30.5]);
///
/// let result = parse_line_of_n::<i32>(line, 2);
/// assert!(result.is_err());
/// ```
pub fn parse_line_of_n<T: std::str::FromStr>(line: &str, n: usize) -> Result<Vec<T>, ParseError>
where
    ParseError: From<<T as std::str::FromStr>::Err>,
{
    let values: Vec<T> = line
        .split_whitespace()
        .map(|s| s.parse::<T>())
        .collect::<Result<_, _>>()?;

    if values.len() == n {
        Ok(values)
    } else {
        Err(ParseError::InvalidVectorLength {
            expected: n,
            found: values.len(),
        })
    }
}

/// Parses the 9-line header of a `.con` file frame from an iterator.
///
/// This function consumes the next 9 lines from the given line iterator to
/// construct a `FrameHeader`. The iterator is advanced by 9 lines on success.
///
/// # Arguments
///
/// * `lines` - A mutable reference to an iterator that yields string slices.
///
/// # Errors
///
/// * `ParseError::IncompleteHeader` if the iterator has fewer than 9 lines remaining.
/// * Propagates any errors from `parse_line_of_n` if the numeric data within
///   the header is malformed.
///
/// # Panics
///
/// This function will panic if the intermediate vectors for box dimensions or angles,
/// after being successfully parsed, cannot be converted into fixed-size arrays.
/// This should not happen if `parse_line_of_n` is used correctly with `n=3`.
pub fn parse_frame_header<'a>(
    lines: &mut impl Iterator<Item = &'a str>,
) -> Result<FrameHeader, ParseError> {
    let prebox1 = lines
        .next()
        .ok_or(ParseError::IncompleteHeader)?
        .to_string();
    // CON-file.2: a leading BOM is rejected. It would sit on line 1.
    if prebox1.starts_with('\u{feff}') {
        return Err(ParseError::ValidationError(
            "file begins with a byte-order mark".into(),
        ));
    }
    let prebox2_raw = lines.next().ok_or(ParseError::IncompleteHeader)?;

    // Line 2: if it starts with '{', parse as JSON metadata (spec v2+).
    // Otherwise treat as a legacy (pre-v2) file with spec_version = 1.
    // One JSON object and nothing else (CON-line2.1). serde_json::from_str
    // rejects trailing junk after the value.
    let trimmed = prebox2_raw.trim();
    let (spec_version, sections, validate, sections_declared) =
        if trimmed == "{\"con_spec_version\":2}" {
            // The line written by every stock trajectory. Same object the
            // JSON parser would build: major 2, no extra keys.
            (2, Vec::new(), false, false)
        } else if let Some(ver) = simple_metadata_version(trimmed) {
            // A header whose only keys are the spec version, an optional
            // minor, and a units object. Every byte is still read. Any
            // other key falls through to the general parser.
            (ver, Vec::new(), false, false)
        } else if trimmed.starts_with('{') {
            let json_val: serde_json::Value = serde_json::from_str(trimmed)
                .map_err(|e| ParseError::InvalidMetadataJson(e.to_string()))?;
            let json_obj = json_val.as_object().ok_or_else(|| {
                ParseError::InvalidMetadataJson("expected a JSON object".to_string())
            })?;
            let ver_value = json_obj
                .get(meta::CON_SPEC_VERSION)
                .ok_or(ParseError::MissingSpecVersion)?;
            let ver = json_u64(ver_value).ok_or_else(|| {
                ParseError::InvalidMetadataJson(
                    "con_spec_version must be a JSON integer, the major version".into(),
                )
            })?;
            if ver > u64::from(u32::MAX) {
                return Err(ParseError::UnsupportedVersion(u32::MAX));
            }
            let ver = ver as u32;
            // JSON majors 0 and 1 are UnsupportedVersion (CON-line2.5).
            // An unknown major is UnsupportedVersion (CON-line2.6).
            // Unknown minors of a known major are accepted (CON-line2.7, CON-status.1).
            if ver == 0 || ver == 1 || ver > crate::CON_SPEC_VERSION {
                return Err(ParseError::UnsupportedVersion(ver));
            }
            if ver >= 3 {
                match json_obj.get(meta::UNITS) {
                    Some(u) => crate::units::validate_v3_units_metadata(u)
                        .map_err(|e| ParseError::InvalidUnits(format!("v3 units: {e}")))?,
                    None => {
                        return Err(ParseError::InvalidUnits(
                        "con_spec_version >= 3 requires metadata \"units\" with length and energy"
                            .into(),
                    ));
                    }
                }
            }

            // Single pass over the JSON object: collect sections, capture the
            // validate flag, copy the rest into metadata. Folds the previous
            // pre-extract get(validate) + re-iterate pattern into one walk.
            let mut sections: Vec<String> = Vec::new();
            let mut sections_declared = false;
            let mut validate = false;
            for (k, v) in json_obj {
                match k.as_str() {
                    meta::CON_SPEC_VERSION => {}
                    meta::CON_SPEC_MINOR => {
                        if json_u64(v).is_none() {
                            return Err(metadata_json_error(
                                "con_spec_minor must be a JSON integer >= 0",
                            ));
                        }
                    }
                    meta::SECTION_ARITY => {
                        validate_section_arity_value(v)?;
                    }
                    meta::SECTIONS => {
                        sections_declared = true;
                        let arr = v.as_array().ok_or_else(|| {
                            metadata_json_error("sections must be an array of strings")
                        })?;
                        sections.reserve(arr.len());
                        for entry in arr {
                            let s = entry.as_str().ok_or_else(|| {
                                metadata_json_error("sections must be an array of strings")
                            })?;
                            sections.push(s.to_string());
                        }
                    }
                    meta::VALIDATE => {
                        validate = match v {
                            Value::Bool(b) => *b,
                            _ => return Err(metadata_json_error("validate must be a boolean")),
                        };
                    }
                    _ => {}
                }
            }

            // Strict-mode schema check fires only when the file requested
            // it. Hot-path parses (validate=false) skip the per-key match.
            if validate {
                validate_metadata_schema(json_obj)?;
            }

            (ver, sections, validate, sections_declared)
        } else {
            // Legacy file: no JSON metadata line.
            (1_u32, Vec::new(), false, false)
        };
    let prebox2 = prebox2_raw.to_string();

    let boxl_vec = parse_line_of_n_f64(lines.next().ok_or(ParseError::IncompleteHeader)?, 3)?;
    let angles_vec = parse_line_of_n_f64(lines.next().ok_or(ParseError::IncompleteHeader)?, 3)?;
    let postbox1 = lines
        .next()
        .ok_or(ParseError::IncompleteHeader)?
        .to_string();
    let postbox2 = lines
        .next()
        .ok_or(ParseError::IncompleteHeader)?
        .to_string();
    let natm_types_line = lines.next().ok_or(ParseError::IncompleteHeader)?;
    let natm_types = parse_count_line(natm_types_line, 1)?[0];
    // A type count of 0 is a zero-atom frame (CON-count.1, CON-count.4).
    // A per-type count of 0 is InvalidCount only when the type count is >= 1.
    let (natms_per_type, masses_per_type) = if natm_types == 0 {
        read_zero_atom_tail(|| lines.next())?;
        (Vec::new(), Vec::new())
    } else {
        let natms_per_type = parse_count_line(
            lines.next().ok_or(ParseError::IncompleteHeader)?,
            natm_types,
        )?;
        if natms_per_type.contains(&0) {
            return Err(ParseError::InvalidCount(
                "each per-type count must be >= 1".into(),
            ));
        }
        let masses_per_type = parse_line_of_n_f64(
            lines.next().ok_or(ParseError::IncompleteHeader)?,
            natm_types,
        )?;
        (natms_per_type, masses_per_type)
    };
    if validate {
        validate_header_geometry(&boxl_vec, &angles_vec)?;
        validate_masses(&masses_per_type)?;
    }
    let shared_line: std::sync::Arc<str> = std::sync::Arc::from(prebox2);
    let metadata = crate::types::FrameMeta::from_shared(std::sync::Arc::clone(&shared_line));
    Ok(FrameHeader {
        prebox_header: PreboxHeader {
            user: prebox1,
            metadata_line: shared_line,
        },
        boxl: boxl_vec.try_into().unwrap(),
        angles: angles_vec.try_into().unwrap(),
        postbox_header: [postbox1, postbox2],
        natm_types,
        natms_per_type,
        masses_per_type,
        spec_version,
        metadata,
        sections,
        strict_validation: validate,
        sections_declared,
    })
}

/// Spec line limited to `con_spec_version`, optional `con_spec_minor`, and `units`.
///
/// Returns the major version when the object is exactly that shape and, for
/// version 3 or newer, `length` and `energy` are valid units. Anything else
/// is `None` so the general JSON parser can accept or reject it.
fn simple_metadata_version(line: &str) -> Option<u32> {
    let bytes = line.as_bytes();
    let mut i = 0usize;
    let skip = |i: &mut usize| {
        while *i < bytes.len() && bytes[*i].is_ascii_whitespace() {
            *i += 1;
        }
    };
    let eat = |i: &mut usize, byte: u8| -> bool {
        skip(i);
        if *i < bytes.len() && bytes[*i] == byte {
            *i += 1;
            true
        } else {
            false
        }
    };
    let quoted = |i: &mut usize| -> Option<&str> {
        skip(i);
        if *i >= bytes.len() || bytes[*i] != b'"' {
            return None;
        }
        *i += 1;
        let start = *i;
        while *i < bytes.len() && bytes[*i] != b'"' {
            if bytes[*i] == b'\\' {
                return None;
            }
            *i += 1;
        }
        if *i >= bytes.len() {
            return None;
        }
        let text = std::str::from_utf8(&bytes[start..*i]).ok()?;
        *i += 1;
        Some(text)
    };
    let integer = |i: &mut usize| -> Option<u64> {
        skip(i);
        let start = *i;
        if *i < bytes.len() && bytes[*i] == b'-' {
            return None;
        }
        while *i < bytes.len() && bytes[*i].is_ascii_digit() {
            *i += 1;
        }
        if start == *i || (bytes[start] == b'0' && *i > start + 1) {
            return None;
        }
        std::str::from_utf8(&bytes[start..*i]).ok()?.parse().ok()
    };
    if !eat(&mut i, b'{') {
        return None;
    }
    let mut version = None;
    let mut saw_minor = false;
    let mut length = None;
    let mut energy = None;
    let mut extra_unit = false;
    loop {
        skip(&mut i);
        if i < bytes.len() && bytes[i] == b'}' {
            i += 1;
            break;
        }
        if version.is_some() || saw_minor || length.is_some() || energy.is_some() || extra_unit {
            if !eat(&mut i, b',') {
                return None;
            }
        }
        let key = quoted(&mut i)?;
        if !eat(&mut i, b':') {
            return None;
        }
        match key {
            "con_spec_version" if version.is_none() => version = Some(integer(&mut i)?),
            "con_spec_minor" if !saw_minor => {
                integer(&mut i)?;
                saw_minor = true;
            }
            "units" if length.is_none() && energy.is_none() && !extra_unit => {
                if !eat(&mut i, b'{') {
                    return None;
                }
                loop {
                    skip(&mut i);
                    if i < bytes.len() && bytes[i] == b'}' {
                        i += 1;
                        break;
                    }
                    if length.is_some() || energy.is_some() || extra_unit {
                        if !eat(&mut i, b',') {
                            return None;
                        }
                    }
                    let ukey = quoted(&mut i)?;
                    if !eat(&mut i, b':') {
                        return None;
                    }
                    let value = quoted(&mut i)?;
                    match ukey {
                        "length" if length.is_none() => length = Some(value),
                        "energy" if energy.is_none() => energy = Some(value),
                        "mass" | "time" | "velocity" | "force" => {
                            if crate::units::validate_unit_for_quantity(ukey, value).is_err() {
                                return None;
                            }
                            extra_unit = true;
                        }
                        _ => return None,
                    }
                }
            }
            _ => return None,
        }
    }
    skip(&mut i);
    if i != bytes.len() {
        return None;
    }
    let ver = u32::try_from(version?).ok()?;
    if ver == 0 || ver == 1 || ver > crate::CON_SPEC_VERSION {
        return None;
    }
    if ver >= 3 {
        let length = length?;
        let energy = energy?;
        if length.trim().is_empty() || energy.trim().is_empty() {
            return None;
        }
        crate::units::validate_unit_for_quantity("length", length).ok()?;
        crate::units::validate_unit_for_quantity("energy", energy).ok()?;
    }
    Some(ver)
}

/// Parses a complete frame from a `.con` file, including its header and atomic data.
///
/// This function first parses the complete frame header and then uses the information within it
/// (specifically the number of atom types and atoms per type) to parse the subsequent
/// atom coordinate blocks.
///
/// Each atom takes one line, so the atom vectors reserve no more rows than the
/// upper bound of `lines.size_hint()`. With no upper bound, as for `str::lines`,
/// they grow as the rows arrive.
///
/// # Arguments
///
/// * `lines` - A mutable reference to an iterator that yields string slices for the frame.
///
/// # Errors
///
/// * `ParseError::IncompleteFrame` if the iterator ends before all expected
///   atomic data has been read.
/// * Propagates any errors from the underlying calls to `parse_frame_header` and
///   `parse_line_of_n`.
///
/// # Example
///
/// ```
/// use readcon_core::parser::parse_single_frame;
///
/// let frame_text = r#"
///Generated by test
///{"con_spec_version":2}
///10.0 10.0 10.0
///90.0 90.0 90.0
///POSTBOX LINE 1
///POSTBOX LINE 2
///2
///1 1
///12.011 1.008
///C
///Coordinates of Component 1
///1.0 1.0 1.0 0 1
///H
///Coordinates of Component 2
///2.0 2.0 2.0 0 2
/// "#;
///
/// let mut lines = frame_text.trim().lines();
/// let con_frame = parse_single_frame(&mut lines).unwrap();
///
/// assert_eq!(con_frame.header.natm_types, 2);
/// assert_eq!(con_frame.atom_data.len(), 2);
/// assert_eq!(&*con_frame.atom_data[0].symbol, "C");
/// assert_eq!(con_frame.atom_data[1].atom_id, 2);
/// ```
pub fn parse_single_frame<'a>(
    lines: &mut impl Iterator<Item = &'a str>,
) -> Result<ConFrame, ParseError> {
    // The caller owns the iterator and may not be able to clone it. Section
    // detection, which needs a lookahead clone, runs later on a `LineStream`
    // that can probe (`MemchrLines`, or a `Peekable` whose source is `Clone`).
    let max_rows = lines.size_hint().1;
    parse_single_frame_ls(&mut IterStream(lines), max_rows)
}

/// Iterator adapter so [`parse_single_frame`] can satisfy [`LineStream`]
/// without requiring [`Clone`].
struct IterStream<I>(I);

impl<'a, I> Iterator for IterStream<I>
where
    I: Iterator<Item = &'a str>,
{
    type Item = &'a str;
    fn next(&mut self) -> Option<&'a str> {
        self.0.next()
    }
}

impl<'a, I> LineStream<'a> for IterStream<I>
where
    I: Iterator<Item = &'a str>,
{
    fn next_line(&mut self) -> Option<&'a str> {
        Iterator::next(self)
    }
    fn peek_line(&mut self) -> Option<&'a str> {
        None
    }
}

struct CoordShell {
    atoms: Vec<crate::types::AtomDatum>,
    coords: Vec<f64>,
    ids: Vec<u64>,
}

thread_local! {
    static COORD_SHELLS: std::cell::RefCell<Vec<CoordShell>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Allocate `n_frames` coordinate shells on this thread before the parse.
///
/// One tight reservation, then each frame takes a shell. Doing the
/// reservations inside the parse mixed the allocator with the float
/// parse and made eight threads slower than the bytes they write.
pub(crate) fn prestash_coord_shells(n_frames: usize, n_atoms: usize) {
    // Small frames (the 32-atom strong-scaling files) are cheaper to
    // allocate inside the parse. A burst of shells ahead of those frames
    // made eight threads slower. Wide atoms, as in the weak-scaling
    // fixture, are the case the burst is for.
    if n_frames == 0 || n_atoms < 128 {
        return;
    }
    COORD_SHELLS.with(|pool| {
        let mut pool = pool.borrow_mut();
        pool.reserve(n_frames);
        for _ in 0..n_frames {
            pool.push(CoordShell {
                atoms: Vec::with_capacity(n_atoms),
                coords: Vec::with_capacity(n_atoms.saturating_mul(3)),
                ids: Vec::with_capacity(n_atoms),
            });
        }
    });
}

pub(crate) fn clear_coord_shells() {
    COORD_SHELLS.with(|pool| pool.borrow_mut().clear());
}

fn take_coord_shell(n_atoms: usize) -> Option<CoordShell> {
    COORD_SHELLS.with(|pool| {
        let shell = pool.borrow_mut().pop()?;
        if shell.atoms.capacity() >= n_atoms
            && shell.coords.capacity() >= n_atoms.saturating_mul(3)
            && shell.ids.capacity() >= n_atoms
        {
            Some(shell)
        } else {
            None
        }
    })
}

/// Columns every atom line has: x, y, z and the flag (spec "Coordinates",
/// CON-num.9). The id column is optional (CON-id.9).
const COORD_ROW_MIN_COLUMNS: usize = 4;

/// Fewest bytes an atom line takes, as in `0 0 0 0`: one byte for each of
/// the [`COORD_ROW_MIN_COLUMNS`] columns and one separator between each
/// pair. Newlines and the symbol and label lines only add bytes, so `n`
/// unread bytes hold at most `n / MIN_COORD_ROW_BYTES` atom lines.
pub(crate) const MIN_COORD_ROW_BYTES: usize = 2 * COORD_ROW_MIN_COLUMNS - 1;

/// Frame parse over a [`LineStream`].
///
/// Coordinate rows go through [`LineStream::next_coord_row`] so the memchr
/// cursor can fuse the newline scan with numeric parse. Positions, ids, and
/// flags land in flat buffers; [`AtomDatum`] values are built from those
/// buffers afterwards (one `Vec` allocation, no per-atom heap traffic).
///
/// `max_rows` bounds the atom lines the rest of the input can hold, and is
/// `None` when that is unknown. The buffers reserve no more atoms than it
/// allows, so a header that declares more atoms than the input holds
/// cannot force a large allocation. The declared counts still decide how
/// many rows are read, and so which error is reported.
pub(crate) fn parse_single_frame_ls<'a, L>(
    lines: &mut L,
    max_rows: Option<usize>,
) -> Result<ConFrame, ParseError>
where
    L: LineStream<'a> + Iterator<Item = &'a str>,
{
    let header = parse_frame_header(lines)?;
    // A count the unread input can hold stays in this function, on the same
    // reservation and `Arc` bump as before the bound existed. A count that
    // cannot fit is a separate cold function so it does not shape this loop.
    let Some(total_atoms) = fitting_atom_count(&header.natms_per_type, max_rows) else {
        return parse_oversized_frame(lines, header, max_rows);
    };
    let validate = header.strict_validation;
    use crate::storage_dtype::{ElementKind, FloatArray2};
    let dt = header.metadata.dtypes();
    let f64_positions = dt.positions == ElementKind::Float64;
    let shell = take_coord_shell(total_atoms);
    let (mut pos_flat, mut ids, mut atom_data) = match shell {
        Some(shell) => (shell.coords, shell.ids, shell.atoms),
        None => (
            Vec::with_capacity(total_atoms.saturating_mul(3)),
            Vec::with_capacity(total_atoms),
            Vec::with_capacity(total_atoms),
        ),
    };
    let mut positions_other = if f64_positions {
        None
    } else {
        Some(FloatArray2::zeros(dt.positions, total_atoms, 3))
    };
    let mut global_atom_idx: u64 = 0;
    for (type_idx, num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol_line = lines.next().ok_or(ParseError::IncompleteFrame)?;
        let symbol: Arc<str> = Arc::from(symbol_line.trim());
        let coord_label = lines.next().ok_or(ParseError::IncompleteFrame)?;
        if validate {
            validate_coordinate_component(type_idx, symbol.as_ref(), coord_label)?;
        }
        global_atom_idx = ingest_coord_rows(
            lines,
            *num_atoms,
            header.spec_version,
            global_atom_idx,
            &symbol,
            CoordSink {
                pos_flat: &mut pos_flat,
                ids: &mut ids,
                positions_other: &mut positions_other,
                atom_data: &mut atom_data,
            },
        )?;
    }
    let positions = if f64_positions {
        FloatArray2::from_f64_row_major(total_atoms, 3, pos_flat)
    } else {
        positions_other.expect("non-f64 positions allocated")
    };
    Ok(crate::types::con_frame_coords_only_with_ids(
        header, atom_data, positions, ids,
    ))
}

/// Atom total when it can use [`Vec::with_capacity`] safely.
///
/// `None` means the counts wrap, exceed `isize::MAX / 4`, or exceed the
/// unread atom lines. A `u32::MAX` count with no size hint is `None`: that
/// reservation is tens of GiB.
#[inline]
fn fitting_atom_count(counts: &[usize], max_rows: Option<usize>) -> Option<usize> {
    let mut total = 0usize;
    for &count in counts {
        total = total.checked_add(count)?;
    }
    if total > (isize::MAX as usize) / 4 {
        return None;
    }
    match max_rows {
        Some(rows) if total > rows => None,
        None if total > (1 << 20) => None,
        _ => Some(total),
    }
}

/// A header declared more atoms than the rest of the input can hold.
///
/// Reservations stay within `max_rows`. Rows are still read up to the
/// declared count, so a short file is `IncompleteFrame`.
#[cold]
#[inline(never)]
fn parse_oversized_frame<'a, L>(
    lines: &mut L,
    header: FrameHeader,
    max_rows: Option<usize>,
) -> Result<ConFrame, ParseError>
where
    L: LineStream<'a> + Iterator<Item = &'a str>,
{
    let validate = header.strict_validation;
    let total_atoms = header
        .natms_per_type
        .iter()
        .fold(0usize, |sum, &n| sum.saturating_add(n));
    let reserve_atoms = max_rows.map_or(0, |rows| total_atoms.min(rows));
    use crate::storage_dtype::FloatArray2;
    let dt = header.metadata.dtypes();
    let mut pos_flat = Vec::new();
    let _ = pos_flat.try_reserve_exact(reserve_atoms.saturating_mul(3));
    let mut ids = Vec::new();
    let _ = ids.try_reserve_exact(reserve_atoms);
    let mut atom_data: Vec<AtomDatum> = Vec::new();
    let _ = atom_data.try_reserve_exact(reserve_atoms);

    let mut global_atom_idx: u64 = 0;
    for (type_idx, num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol_line = lines.next().ok_or(ParseError::IncompleteFrame)?;
        let symbol: Arc<str> = Arc::from(symbol_line.trim());
        let coord_label = lines.next().ok_or(ParseError::IncompleteFrame)?;
        if validate {
            validate_coordinate_component(type_idx, symbol.as_ref(), coord_label)?;
        }
        global_atom_idx = ingest_coord_rows_cloned(
            lines,
            *num_atoms,
            header.spec_version,
            global_atom_idx,
            &symbol,
            &mut pos_flat,
            &mut ids,
            &mut atom_data,
        )?;
    }
    let mut positions = FloatArray2::from_f64_row_major(total_atoms, 3, pos_flat);
    positions.project_to(dt.positions);
    Ok(crate::types::con_frame_coords_only_with_ids(
        header, atom_data, positions, ids,
    ))
}

struct CoordSink<'a> {
    pos_flat: &'a mut Vec<f64>,
    ids: &'a mut Vec<u64>,
    positions_other: &'a mut Option<crate::storage_dtype::FloatArray2>,
    atom_data: &'a mut Vec<AtomDatum>,
}

/// Parse `n` coordinate rows into flat SoA buffers.
fn ingest_coord_rows<'a, L>(
    lines: &mut L,
    n: usize,
    spec_version: u32,
    global_atom_idx: u64,
    symbol: &Arc<str>,
    sink: CoordSink<'_>,
) -> Result<u64, ParseError>
where
    L: LineStream<'a>,
{
    let CoordSink {
        pos_flat,
        ids,
        positions_other,
        atom_data,
    } = sink;
    if positions_other.is_none() {
        return ingest_coord_rows_f64(
            lines,
            n,
            spec_version,
            global_atom_idx,
            symbol,
            pos_flat,
            ids,
            atom_data,
        );
    }
    let mut global_atom_idx = global_atom_idx;
    for _ in 0..n {
        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
        if let Some(pos) = positions_other.as_mut() {
            pos.set_f64_row(ids.len(), xyz);
        }
        let index = pos_flat.len() / 3;
        pos_flat.extend_from_slice(&xyz);
        let slot = unsafe { pos_flat.as_mut_ptr().add(index * 3) };
        ids.push(atom_id);
        atom_data.push(AtomDatum::at_slot(Arc::clone(symbol), slot, fixed, atom_id));
        global_atom_idx += 1;
    }
    Ok(global_atom_idx)
}

/// Coordinate rows for the f64 storage path.
///
/// The symbol `Arc` is bumped once for the whole block. Cloning it per atom
/// was a visible share of the coordinate parse.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn ingest_coord_rows_f64<'a, L>(
    lines: &mut L,
    n: usize,
    spec_version: u32,
    mut global_atom_idx: u64,
    symbol: &Arc<str>,
    pos_flat: &mut Vec<f64>,
    ids: &mut Vec<u64>,
    atom_data: &mut Vec<AtomDatum>,
) -> Result<u64, ParseError>
where
    L: LineStream<'a>,
{
    let workers = wide_workers();
    if workers >= 2 && n >= 4096 {
        if let Some(mut block) =
            lines.try_take_coord_block(n, spec_version, global_atom_idx, symbol, workers)
        {
            let base = pos_flat.len();
            // Keep a reservation that covers the whole frame. Replacing it
            // with a shorter block makes the next species group reallocate
            // under live pointers.
            if pos_flat.is_empty() && block.xyz.capacity() >= pos_flat.capacity() {
                *pos_flat = block.xyz;
            } else {
                pos_flat.extend_from_slice(&block.xyz);
            }
            let ptr = pos_flat.as_mut_ptr();
            for (i, atom) in block.atoms.iter_mut().enumerate() {
                atom.retarget(unsafe { ptr.add(base + i * 3) });
            }
            if ids.is_empty() {
                *ids = block.ids;
            } else {
                ids.extend_from_slice(&block.ids);
            }
            if atom_data.is_empty() {
                *atom_data = block.atoms;
            } else {
                atom_data.extend(block.atoms);
            }
            return Ok(global_atom_idx + n as u64);
        }
    }
    let mut shares = symbol_shares(symbol, n);
    for _ in 0..n {
        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
        let sym = shares.take();
        let index = pos_flat.len() / 3;
        pos_flat.extend_from_slice(&xyz);
        let slot = unsafe { pos_flat.as_mut_ptr().add(index * 3) };
        ids.push(atom_id);
        atom_data.push(AtomDatum::at_slot(sym, slot, fixed, atom_id));
        global_atom_idx += 1;
    }
    Ok(global_atom_idx)
}

/// Coordinate rows when the declared count must not bump an `Arc` by `n`.
fn ingest_coord_rows_cloned<'a, L>(
    lines: &mut L,
    n: usize,
    spec_version: u32,
    mut global_atom_idx: u64,
    symbol: &Arc<str>,
    pos_flat: &mut Vec<f64>,
    ids: &mut Vec<u64>,
    atom_data: &mut Vec<AtomDatum>,
) -> Result<u64, ParseError>
where
    L: LineStream<'a>,
{
    for _ in 0..n {
        let (xyz, fixed, atom_id) = lines.next_coord_row(spec_version, global_atom_idx)?;
        pos_flat.extend_from_slice(&xyz);
        ids.push(atom_id);
        atom_data.push(AtomDatum::coords(
            Arc::clone(symbol),
            xyz[0],
            xyz[1],
            xyz[2],
            fixed,
            atom_id,
        ));
        global_atom_idx += 1;
    }
    Ok(global_atom_idx)
}

/// `n` extra strong references to `symbol`, taken one at a time.
///
/// `Arc<str>` stores the header (strong count, weak count) immediately
/// before the bytes. One `fetch_add` covers the block; each [`SymbolShares::take`]
/// turns one of those counts into an `Arc`. Leftovers drop with the guard.
struct SymbolShares {
    data: *const u8,
    len: usize,
    left: usize,
}

impl SymbolShares {
    fn raw(&self) -> *const str {
        std::ptr::slice_from_raw_parts(self.data, self.len) as *const str
    }

    fn take(&mut self) -> Arc<str> {
        debug_assert!(self.left > 0);
        self.left -= 1;
        unsafe { Arc::from_raw(self.raw()) }
    }
}

impl Drop for SymbolShares {
    fn drop(&mut self) {
        for _ in 0..self.left {
            drop(unsafe { Arc::from_raw(self.raw()) });
        }
        self.left = 0;
    }
}

fn symbol_shares(symbol: &Arc<str>, n: usize) -> SymbolShares {
    if n == 0 {
        return SymbolShares {
            data: std::ptr::null(),
            len: 0,
            left: 0,
        };
    }
    let data = Arc::as_ptr(symbol);
    let offset = arc_str_header(symbol.as_ref());
    // SAFETY: `Arc::as_ptr` points at the `str` inside the allocation, and
    // the two atomic counts sit in front of it. This is the same subtraction
    // `Arc::increment_strong_count` performs, done once for `n` clones.
    let bytes = data as *const u8;
    let strong = unsafe { bytes.sub(offset) as *const AtomicUsize };
    unsafe { (*strong).fetch_add(n, Ordering::Relaxed) };
    SymbolShares {
        data: bytes,
        len: symbol.len(),
        left: n,
    }
}

fn arc_str_header(text: &str) -> usize {
    let header = 2 * std::mem::size_of::<usize>();
    let align = std::mem::align_of_val(text);
    let rem = header % align;
    if rem == 0 {
        header
    } else {
        header + (align - rem)
    }
}

#[cfg(test)]
mod symbol_share_tests {
    use super::symbol_shares;
    use std::sync::Arc;

    #[test]
    fn one_bump_matches_n_clones() {
        for text in ["", "Cu", "Gold", "a-much-longer-component-symbol"] {
            let symbol: Arc<str> = Arc::from(text);
            let mut shares = symbol_shares(&symbol, 3);
            assert_eq!(Arc::strong_count(&symbol), 4);
            let owned = [shares.take(), shares.take(), shares.take()];
            assert!(owned.iter().all(|arc| arc.as_ref() == text));
            drop(owned);
            assert_eq!(Arc::strong_count(&symbol), 1);
            let mut partial = symbol_shares(&symbol, 2);
            let one = partial.take();
            drop(partial);
            drop(one);
            assert_eq!(Arc::strong_count(&symbol), 1);
        }
    }
}

fn validate_header_geometry(boxl: &[f64], angles: &[f64]) -> Result<(), ParseError> {
    if boxl
        .iter()
        .any(|length| !length.is_finite() || *length <= 0.0)
        || angles
            .iter()
            .any(|angle| !angle.is_finite() || *angle <= 0.0 || *angle >= 180.0)
    {
        return Err(ParseError::ValidationError(
            "cell geometry must have positive lengths and angles between 0 and 180 degrees"
                .to_string(),
        ));
    }
    Ok(())
}

fn validate_masses(masses_per_type: &[f64]) -> Result<(), ParseError> {
    if masses_per_type
        .iter()
        .any(|mass| !mass.is_finite() || *mass <= 0.0)
    {
        return Err(ParseError::ValidationError(
            "component masses must be positive".to_string(),
        ));
    }
    Ok(())
}

fn validate_coordinate_component(
    type_idx: usize,
    symbol: &str,
    label: &str,
) -> Result<(), ParseError> {
    let expected_label = format!("Coordinates of Component {}", type_idx + 1);
    if !labels_equal(label, &expected_label) {
        return Err(ParseError::ValidationError(format!(
            "expected coordinate label {expected_label:?}, found {label:?}"
        )));
    }
    if symbol != "X" && symbol_to_atomic_number(symbol) == 0 {
        return Err(ParseError::ValidationError(format!(
            "unknown component symbol {symbol}"
        )));
    }
    Ok(())
}

fn validate_section_component(
    section: &str,
    type_idx: usize,
    atom_idx: usize,
    symbol: &str,
    label: &str,
    header: &FrameHeader,
    atom_data: &[AtomDatum],
) -> Result<(), ParseError> {
    let expected_label = format!("{section} of Component {}", type_idx + 1);
    if !labels_equal(label, &expected_label) {
        return Err(ParseError::ValidationError(format!(
            "expected section label {expected_label:?}, found {label:?}"
        )));
    }

    if header.natms_per_type[type_idx] == 0 {
        return Ok(());
    }

    let expected_symbol = atom_data
        .get(atom_idx)
        .map(|atom| atom.symbol.as_ref())
        .ok_or_else(|| {
            ParseError::ValidationError(format!(
                "{section} component {} has no coordinate atom to validate against",
                type_idx + 1
            ))
        })?;
    if symbol != expected_symbol {
        return Err(ParseError::ValidationError(format!(
            "{section} component {} symbol mismatch: expected {expected_symbol}, found {symbol}",
            type_idx + 1
        )));
    }

    Ok(())
}

fn validate_section_atom_identity(
    section: &str,
    atom_idx: usize,
    fixed: [bool; 3],
    atom_id: u64,
    atom_data: &[AtomDatum],
) -> Result<(), ParseError> {
    let atom = atom_data.get(atom_idx).ok_or_else(|| {
        ParseError::ValidationError(format!(
            "{section} row {atom_idx} has no coordinate atom to validate against"
        ))
    })?;

    if atom.fixed() != fixed {
        return Err(ParseError::ValidationError(format!(
            "{section} row {atom_idx} fixed mask mismatch for atom_id {}",
            atom.atom_id
        )));
    }
    if atom.atom_id != atom_id {
        return Err(ParseError::ValidationError(format!(
            "{section} row {atom_idx} atom_id mismatch: expected {}, found {atom_id}",
            atom.atom_id
        )));
    }

    Ok(())
}

/// Consume the single blank line that opens a section.
///
/// A blank line followed only by whitespace to EOF does not open a section
/// (CON-frame.5). The lines stay in the stream.
fn frame_minor(header: &FrameHeader) -> u64 {
    header.metadata.spec_minor()
}

fn section_row_arity(header: &FrameHeader, name: &str) -> Option<usize> {
    let obj = header.metadata.get(meta::SECTION_ARITY)?.as_object()?;
    let n = obj.get(name)?.as_u64()?;
    if n >= 1 { Some(n as usize) } else { None }
}

/// Skip one unknown section of a newer minor.
///
/// `arity` is the value-field count (CON-section.12). Each data row holds
/// that many values, then the flag, and an optional id, so the row has
/// `arity + 1` or `arity + 2` tokens (CON-section.14). The label is the
/// section name under CON-file.5, then `of Component N` (CON-section.15).
fn skip_unknown_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    name: &str,
    arity: usize,
) -> Result<(), ParseError> {
    if !open_section(lines)? {
        return Err(ParseError::IncompleteSection(name.to_string()));
    }
    let with_flag = arity.saturating_add(1);
    let with_id = arity.saturating_add(2);
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        if lines.next_line().is_none() {
            return Err(ParseError::IncompleteSection(name.to_string()));
        }
        let label = lines
            .next_line()
            .ok_or_else(|| ParseError::IncompleteSection(name.to_string()))?;
        let expected = format!("{name} of Component {}", type_idx + 1);
        if !labels_equal(label, &expected) {
            return Err(ParseError::IncompleteSection(name.to_string()));
        }
        for _ in 0..num_atoms {
            let row = lines
                .next_line()
                .ok_or_else(|| ParseError::IncompleteSection(name.to_string()))?;
            let found = token_count(row);
            if found != with_flag && found != with_id {
                let expected = if found < with_flag {
                    with_flag
                } else {
                    with_id
                };
                return Err(ParseError::InvalidVectorLength { expected, found });
            }
        }
    }
    Ok(())
}

fn open_section<'a>(lines: &mut impl LineStream<'a>) -> Result<bool, ParseError> {
    match lines.peek_line() {
        Some(line) if line.trim().is_empty() => {
            if lines.remainder_is_whitespace() {
                return Ok(false);
            }
            lines.next_line();
            Ok(true)
        }
        _ => Ok(false),
    }
}

/// Attempts to parse an optional velocity section following coordinate blocks.
///
/// In `.convel` files, after all coordinate blocks there is a blank separator line
/// followed by per-component velocity blocks with the same structure as coordinate
/// blocks (symbol line, "Velocities of Component N" line, then atom lines with
/// `vx vy vz fixed atomID`).
///
/// This function peeks at the next line. If it is blank (or contains only whitespace),
/// it consumes the blank line and writes each velocity into `column` (row-major
/// `n * 3` `f64`s, one allocation). If the next line is not blank (or is absent),
/// no velocities are parsed and `column` is left untouched.
///
/// Returns `Ok(true)` if velocities were found and parsed, `Ok(false)` otherwise.
pub fn parse_velocity_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
    column: &mut Vec<f64>,
) -> Result<bool, ParseError> {
    let validate = header.strict_validation;
    // A blank line followed only by whitespace to EOF is not a velocity
    // block (CON-frame.5, D2). Leave those lines for the iterator.
    match lines.peek_line() {
        Some(line) if line.trim().is_empty() => {
            if lines.remainder_is_whitespace() {
                return Ok(false);
            }
            // CON-section.2 / the legacy fallback: the blank counts only
            // when it begins a complete velocity block. Otherwise it is
            // line 1 of the next frame (CON-frame.7, CON-header.4).
            if !lines.blank_line_opens_section() {
                return Ok(false);
            }
            lines.next_line();
        }
        _ => return Ok(false),
    }

    let n = atom_data.len();
    column.clear();
    column.resize(n.saturating_mul(3), 0.0);
    let mut atom_idx: usize = 0;
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        // Symbol line
        let symbol = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_VELOCITIES.into()))?
            .trim();

        // "Velocities of Component N" line
        let comp_line = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_VELOCITIES.into()))?;
        if !label_has_prefix(comp_line, "Velocities of Component") {
            return Err(ParseError::IncompleteSection(SECTION_VELOCITIES.into()));
        }
        if validate {
            validate_section_component(
                "Velocities",
                type_idx,
                atom_idx,
                symbol,
                comp_line,
                header,
                atom_data,
            )?;
        }

        for _ in 0..num_atoms {
            let (vals, fixed, atom_id) =
                take_vector_row(lines, header.spec_version, SECTION_VELOCITIES)?;
            if validate {
                validate_section_atom_identity("velocities", atom_idx, fixed, atom_id, atom_data)?;
            }
            if atom_idx < n {
                let base = atom_idx * 3;
                column[base] = vals[0];
                column[base + 1] = vals[1];
                column[base + 2] = vals[2];
            }
            atom_idx += 1;
        }
    }

    Ok(true)
}

/// Attempts to parse a force section following coordinate (and optional velocity) blocks.
///
/// Force sections mirror velocity sections: a blank separator line followed by per-component
/// force blocks (symbol line, "Forces of Component N" line, then atom lines with
/// `fx fy fz fixed_flag atom_id`).
///
/// Returns `Ok(true)` if forces were found and parsed, `Ok(false)` otherwise.
pub fn parse_force_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
    column: &mut Vec<f64>,
) -> Result<bool, ParseError> {
    let validate = header.strict_validation;
    if !open_section(lines)? {
        return Ok(false);
    }

    let n = atom_data.len();
    column.clear();
    column.resize(n.saturating_mul(3), 0.0);
    let mut atom_idx: usize = 0;
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_FORCES.into()))?
            .trim();

        let comp_line = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_FORCES.into()))?;
        if !label_has_prefix(comp_line, "Forces of Component") {
            return Err(ParseError::IncompleteSection(SECTION_FORCES.into()));
        }
        if validate {
            validate_section_component(
                "Forces", type_idx, atom_idx, symbol, comp_line, header, atom_data,
            )?;
        }

        for _ in 0..num_atoms {
            let (vals, fixed, atom_id) =
                take_vector_row(lines, header.spec_version, SECTION_FORCES)?;
            if validate {
                validate_section_atom_identity("forces", atom_idx, fixed, atom_id, atom_data)?;
            }
            if atom_idx < n {
                let base = atom_idx * 3;
                column[base] = vals[0];
                column[base + 1] = vals[1];
                column[base + 2] = vals[2];
            }
            atom_idx += 1;
        }
    }

    Ok(true)
}

/// Attempts to parse an energies section following coordinate (and optional
/// velocity / force) blocks.
///
/// Energy sections mirror force sections but with one scalar per atom:
/// blank separator, then per-component blocks of (symbol, "Energies of
/// Component N", and atom lines `e fixed_flag atom_id`). The two
/// trailing identity columns are optional and used only for strict
/// validation; in non-strict mode any whitespace after the energy is
/// ignored.
///
/// Returns `Ok(true)` if energies were found and parsed, `Ok(false)`
/// otherwise.
pub fn parse_energy_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    let validate = header.strict_validation;
    if !open_section(lines)? {
        return Ok(false);
    }

    let mut atom_idx: usize = 0;
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?
            .trim();

        let comp_line = lines
            .next_line()
            .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?;
        if !label_has_prefix(comp_line, "Energies of Component") {
            return Err(ParseError::IncompleteSection(SECTION_ENERGIES.into()));
        }
        if validate {
            validate_section_component(
                "Energies", type_idx, atom_idx, symbol, comp_line, header, atom_data,
            )?;
        }

        for _ in 0..num_atoms {
            let energy_line = lines
                .next_line()
                .ok_or(ParseError::IncompleteSection(SECTION_ENERGIES.into()))?;
            let (value, fixed, atom_id) =
                parse_scalar_section_row(energy_line, header.spec_version)?;
            if validate {
                validate_section_atom_identity("energies", atom_idx, fixed, atom_id, atom_data)?;
            }
            if atom_idx < atom_data.len() {
                atom_data[atom_idx].set_energy(Some(value));
            }
            atom_idx += 1;
        }
    }

    Ok(true)
}

/// Parses declared sections from a frame's header metadata.
///
/// If `header.sections` is non-empty (v2 file with `"sections"` key in JSON),
/// parses each declared section in order. Otherwise falls back to legacy
/// blank-separator velocity detection.
pub fn parse_declared_sections<'a>(
    lines: &mut impl LineStream<'a>,
    frame: &mut ConFrame,
) -> Result<usize, ParseError> {
    let mut applied = 0usize;
    // A zero-atom frame has no coordinate block and no section block.
    // The legacy velocity fallback must not run (CON-count.1).
    if frame.header.natm_types == 0 {
        if !frame.header.sections.is_empty() {
            return Err(ParseError::InvalidCount(
                "a zero-atom frame cannot declare sections".into(),
            ));
        }
        return Ok(0);
    }
    if !frame.header.sections_declared && frame.header.sections.is_empty() {
        // Legacy: try velocity detection via blank separator. A blank
        // line can also be the empty line 1 of the next frame, so look for
        // the velocity label before committing (CON-frame.5).
        let mut column = Vec::new();
        let found = lines.blank_opens_velocity_block()
            && parse_velocity_section(lines, &frame.header, &mut frame.atom_data, &mut column)?;
        if found {
            frame.adopt_velocity_column(column);
            frame.header.sections.push(SECTION_VELOCITIES.into());
            applied = 1;
        }
    } else {
        let sections = std::mem::take(&mut frame.header.sections);
        for section in &sections {
            match section.as_str() {
                SECTION_VELOCITIES => {
                    let mut column = Vec::new();
                    let found = parse_velocity_section(
                        lines,
                        &frame.header,
                        &mut frame.atom_data,
                        &mut column,
                    )?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_VELOCITIES.into()));
                    }
                    frame.adopt_velocity_column(column);
                    applied += 1;
                }
                SECTION_FORCES => {
                    let mut column = Vec::new();
                    let found = parse_force_section(
                        lines,
                        &frame.header,
                        &mut frame.atom_data,
                        &mut column,
                    )?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_FORCES.into()));
                    }
                    frame.adopt_force_column(column);
                    applied += 1;
                }
                SECTION_ENERGIES => {
                    let found = parse_energy_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_ENERGIES.into()));
                    }
                    applied += 1;
                }
                SECTION_CHARGES => {
                    let found = parse_charge_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_CHARGES.into()));
                    }
                    applied += 1;
                }
                SECTION_SPINS => {
                    let found = parse_spin_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_SPINS.into()));
                    }
                    applied += 1;
                }
                SECTION_MAGMOMS => {
                    let found = parse_magmom_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_MAGMOMS.into()));
                    }
                    applied += 1;
                }
                SECTION_DISPLACEMENTS => {
                    let found =
                        parse_displacement_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_DISPLACEMENTS.into()));
                    }
                    applied += 1;
                }
                SECTION_SPREADS => {
                    let found = parse_spread_section(lines, &frame.header, &mut frame.atom_data)?;
                    if !found {
                        return Err(ParseError::IncompleteSection(SECTION_SPREADS.into()));
                    }
                    applied += 1;
                }
                other => {
                    if frame_minor(&frame.header) > u64::from(crate::CON_SPEC_MINOR)
                        && let Some(arity) = section_row_arity(&frame.header, other)
                    {
                        skip_unknown_section(lines, &frame.header, other, arity)?;
                        continue;
                    }
                    return Err(ParseError::UnknownSection(other.to_string()));
                }
            }
        }
        frame.header.sections = sections;
    }
    reject_velocities_without_time(&frame.header)?;
    Ok(applied)
}

/// CON-units.11. Versions 1, 2, and 3.0 do not require `units.time`
/// (CON-units.8, CON-units.9). From minor 1 the key is required when a
/// velocities section is present.
fn reject_velocities_without_time(header: &FrameHeader) -> Result<(), ParseError> {
    if header.spec_version < 3 || frame_minor(header) < 1 {
        return Ok(());
    }
    if !header
        .sections
        .iter()
        .any(|name| name == SECTION_VELOCITIES)
    {
        return Ok(());
    }
    let time_ok = header
        .metadata
        .get(meta::UNITS)
        .and_then(|units| units.get("time"))
        .and_then(|value| value.as_str())
        .is_some_and(|unit| !unit.trim().is_empty());
    if time_ok {
        Ok(())
    } else {
        Err(ParseError::InvalidUnits(
            "minor >= 1 requires units.time when a velocities section is present".into(),
        ))
    }
}

/// Scalar per-atom section: blank separator + per-type blocks
/// (`symbol`, `"X of Component N"`, lines `value fixed atom_id`).
fn parse_scalar_atom_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
    section_name: &str,
    component_label: &str,
    mut set_value: impl FnMut(&mut AtomDatum, f64),
) -> Result<bool, ParseError> {
    let validate = header.strict_validation;
    if !open_section(lines)? {
        return Ok(false);
    }

    let mut atom_idx: usize = 0;
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol = lines
            .next_line()
            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?
            .trim();

        let comp_line = lines
            .next_line()
            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
        if !label_has_prefix(comp_line, component_label) {
            return Err(ParseError::IncompleteSection(section_name.into()));
        }
        if validate {
            validate_section_component(
                component_label.trim_end_matches(" of Component").trim(),
                type_idx,
                atom_idx,
                symbol,
                comp_line,
                header,
                atom_data,
            )?;
        }

        for _ in 0..num_atoms {
            let data_line = lines
                .next_line()
                .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
            let (value, fixed, atom_id) = parse_scalar_section_row(data_line, header.spec_version)?;
            if validate {
                validate_section_atom_identity(section_name, atom_idx, fixed, atom_id, atom_data)?;
            }
            if atom_idx < atom_data.len() {
                set_value(&mut atom_data[atom_idx], value);
            }
            atom_idx += 1;
        }
    }
    Ok(true)
}

pub fn parse_charge_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    parse_scalar_atom_section(
        lines,
        header,
        atom_data,
        SECTION_CHARGES,
        "Charges of Component",
        |a, v| a.set_charge(Some(v)),
    )
}

pub fn parse_spin_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    parse_scalar_atom_section(
        lines,
        header,
        atom_data,
        SECTION_SPINS,
        "Spins of Component",
        |a, v| a.set_spin(Some(v)),
    )
}

fn parse_vector_named_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
    names: (&str, &str, &str),
    mut set_value: impl FnMut(&mut AtomDatum, [f64; 3]),
    mut check_row: impl FnMut(usize, [f64; 3]) -> Result<(), ParseError>,
) -> Result<bool, ParseError> {
    let (section_name, component_label, label_kind) = names;
    let validate = header.strict_validation;
    if !open_section(lines)? {
        return Ok(false);
    }
    let mut atom_idx: usize = 0;
    for (type_idx, &num_atoms) in header.natms_per_type.iter().enumerate() {
        let symbol = lines
            .next_line()
            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?
            .trim();
        let comp_line = lines
            .next_line()
            .ok_or_else(|| ParseError::IncompleteSection(section_name.into()))?;
        if !label_has_prefix(comp_line, component_label) {
            return Err(ParseError::IncompleteSection(section_name.into()));
        }
        if validate {
            validate_section_component(
                label_kind, type_idx, atom_idx, symbol, comp_line, header, atom_data,
            )?;
        }
        for _ in 0..num_atoms {
            let (vals, fixed, atom_id) = take_vector_row(lines, header.spec_version, section_name)?;
            check_row(atom_idx, vals)?;
            if validate {
                validate_section_atom_identity(section_name, atom_idx, fixed, atom_id, atom_data)?;
            }
            if atom_idx < atom_data.len() {
                set_value(&mut atom_data[atom_idx], vals);
            }
            atom_idx += 1;
        }
    }
    Ok(true)
}

/// Magmoms: 3-vector per atom, same layout as velocities/forces.
pub fn parse_magmom_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    parse_vector_named_section(
        lines,
        header,
        atom_data,
        (SECTION_MAGMOMS, "Magmoms of Component", "Magmoms"),
        |a, v| a.set_magmom(Some(v)),
        |_, _| Ok(()),
    )
}

/// Displacements: 3-vector per atom (Angstrom), same layout as velocities/forces.
pub fn parse_displacement_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    parse_vector_named_section(
        lines,
        header,
        atom_data,
        (
            SECTION_DISPLACEMENTS,
            "Displacements of Component",
            "Displacements",
        ),
        |a, v| a.set_displacement(Some(v)),
        |_, _| Ok(()),
    )
}

/// Spreads: per-atom root-mean-square spread `[sx, sy, sz]` (Angstrom, each
/// non-negative), same layout as velocities/forces.
pub fn parse_spread_section<'a>(
    lines: &mut impl LineStream<'a>,
    header: &FrameHeader,
    atom_data: &mut [AtomDatum],
) -> Result<bool, ParseError> {
    parse_vector_named_section(
        lines,
        header,
        atom_data,
        (SECTION_SPREADS, "Spreads of Component", "Spreads"),
        |a, v| a.set_spread(Some(v)),
        |atom_idx, vals| {
            if !vals.iter().all(|v| v.is_finite()) {
                return Err(ParseError::NonFiniteValue(format!(
                    "spreads atom {atom_idx}"
                )));
            }
            if vals.iter().any(|v| *v < 0.0) {
                return Err(crate::types::invalid_spread(atom_idx));
            }
            Ok(())
        },
    )
}

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

    #[test]
    fn test_parse_line_of_n_success() {
        let line = "1.0 2.5 -3.0";
        let values = parse_line_of_n::<f64>(line, 3).unwrap();
        assert_eq!(values, vec![1.0, 2.5, -3.0]);
    }

    #[test]
    fn test_parse_line_of_n_too_short() {
        let line = "1.0 2.5";
        let result = parse_line_of_n::<f64>(line, 3);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidVectorLength {
                expected: 3,
                found: 2
            }
        ));
    }

    #[test]
    fn test_parse_line_of_n_too_long() {
        let line = "1.0 2.5 -3.0 4.0";
        let result = parse_line_of_n::<f64>(line, 3);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidVectorLength {
                expected: 3,
                found: 4
            }
        ));
    }

    #[test]
    fn test_parse_line_of_n_invalid_float() {
        let line = "1.0 abc -3.0";
        let result = parse_line_of_n::<f64>(line, 3);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidNumberFormat(_)
        ));
    }

    #[test]
    fn test_parse_frame_header_success() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        match parse_frame_header(&mut line_it) {
            Ok(header) => {
                assert_eq!(header.prebox_header.user, "PREBOX1");
                assert_eq!(header.spec_version, 2);
                assert_eq!(header.boxl, [10.0, 20.0, 30.0]);
                assert_eq!(header.angles, [90.0, 90.0, 90.0]);
                assert_eq!(header.postbox_header, ["POSTBOX1", "POSTBOX2"]);
                assert_eq!(header.natm_types, 2);
                assert_eq!(header.natms_per_type, vec![1, 1]);
                assert_eq!(header.masses_per_type, vec![12.011, 1.008]);
            }
            Err(e) => {
                panic!("Parsing failed when it should have succeeded. Error: {e:?}");
            }
        }
    }

    #[test]
    fn test_parse_frame_header_missing_line() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            // Missing masses_per_type
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_frame_header(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ParseError::IncompleteHeader));
    }

    #[test]
    fn test_parse_frame_header_missing_spec_version() {
        let lines = [
            "PREBOX1",
            "{}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_frame_header(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::MissingSpecVersion
        ));
    }

    #[test]
    fn test_parse_frame_header_legacy_no_json() {
        // A non-JSON line 2 is treated as a legacy (v1) file.
        let lines = [
            "PREBOX1",
            "0.0000 TIME",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let header = parse_frame_header(&mut line_it).unwrap();
        assert_eq!(header.spec_version, 1);
        assert!(header.metadata.is_empty());
    }

    #[test]
    fn test_parse_frame_header_malformed_json() {
        // Line 2 starts with '{' but is not valid JSON -- this IS an error.
        let lines = [
            "PREBOX1",
            "{broken json",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_frame_header(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidMetadataJson(_)
        ));
    }

    #[test]
    fn test_parse_frame_header_unsupported_version() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":999}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_frame_header(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::UnsupportedVersion(999)
        ));
    }

    #[test]
    fn test_v3_missing_units_rejected() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":3}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "1.0",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("units") || msg.contains("v3"),
            "expected units error, got {msg}"
        );
    }

    #[test]
    fn test_v3_invalid_units_rejected() {
        let lines = [
            "PREBOX1",
            r#"{"con_spec_version":3,"units":{"length":"eV","energy":"angstrom"}}"#,
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "1.0",
        ];
        let mut line_it = lines.iter().copied();
        assert!(parse_frame_header(&mut line_it).is_err());
    }

    #[test]
    fn test_v3_valid_units_exposes_length_energy() {
        let lines = [
            "PREBOX1",
            r#"{"con_spec_version":3,"units":{"length":"angstrom","energy":"eV","mass":"amu","time":"fs"}}"#,
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "1.0",
        ];
        let mut line_it = lines.iter().copied();
        let header = parse_frame_header(&mut line_it).unwrap();
        assert_eq!(header.spec_version, 3);
        assert_eq!(header.length_unit(), Some("angstrom"));
        assert_eq!(header.energy_unit(), Some("eV"));
        let f = header.conversion_factor_to("length", "nm").unwrap();
        assert!((f - 0.1).abs() < 1e-12);
    }

    #[test]
    fn test_parse_frame_header_extra_metadata_preserved() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"generator\":\"test\"}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let header = parse_frame_header(&mut line_it).unwrap();
        assert_eq!(header.spec_version, 2);
        assert_eq!(
            header.metadata.get("generator"),
            Some(&serde_json::Value::String("test".to_string()))
        );
    }

    #[test]
    fn test_parse_frame_header_invalid_natms_per_type() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1 1", // 3 values, but natm_types is 2
            "12.011 1.008",
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_frame_header(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidVectorLength {
                expected: 2,
                found: 3
            }
        ));
    }

    #[test]
    fn test_parse_single_frame_success() {
        let lines = vec![
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "3 3",
            "12.011 1.008",
            "1",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 0 1",
            "1.0940 0.0 0.0 0 2",
            "-0.5470 0.9499 0.0 0 3",
            "2",
            "Coordinates of Component 2",
            "5.0 5.0 5.0 0 4",
            "6.0940 5.0 5.0 0 5",
            "5.5470 5.9499 5.0 0 6",
        ];
        let mut line_it = lines.iter().copied();
        let frame = parse_single_frame(&mut line_it).unwrap();

        assert_eq!(frame.header.natm_types, 2);
        assert_eq!(frame.header.natms_per_type, vec![3, 3]);
        assert_eq!(frame.header.masses_per_type, vec![12.011, 1.008]);
        assert_eq!(frame.atom_data.len(), 6);
        assert_eq!(&*frame.atom_data[0].symbol, "1");
        assert_eq!(frame.atom_data[0].atom_id, 1);
        assert_eq!(&*frame.atom_data[5].symbol, "2");
        assert_eq!(frame.atom_data[5].atom_id, 6);
    }

    #[test]
    fn test_column_4_value_1_is_x_only_on_spec_2() {
        let lines = [
            "Generated by probe",
            "{\"con_spec_version\":2}",
            "20.0 20.0 20.0",
            "90.0 90.0 90.0",
            "",
            "",
            "1",
            "1",
            "63.5",
            "Cu",
            "Coordinates of component   1",
            "1.0 2.0 3.0 1 1",
        ];
        let mut line_it = lines.iter().copied();
        let frame = parse_single_frame(&mut line_it).unwrap();
        assert_eq!(frame.header.spec_version, 2);
        assert_eq!(frame.atom_data[0].fixed(), [true, false, false]);
    }

    #[test]
    fn test_column_4_value_1_is_all_fixed_on_spec_1() {
        let lines = [
            "Generated by probe",
            "0.0000 TIME",
            "20.0 20.0 20.0",
            "90.0 90.0 90.0",
            "",
            "",
            "1",
            "1",
            "63.5",
            "Cu",
            "Coordinates of component   1",
            "1.0 2.0 3.0 1 1",
        ];
        let mut line_it = lines.iter().copied();
        let frame = parse_single_frame(&mut line_it).unwrap();
        assert_eq!(frame.header.spec_version, 1);
        assert_eq!(frame.atom_data[0].fixed(), [true, true, true]);
    }

    #[test]
    fn test_parse_single_frame_missing_line() {
        // With a valid header but truncated atom data, we get IncompleteFrame.
        let lines = vec![
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "3 3",
            "12.011 1.008",
            "1",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 0 1",
            "1.0940 0.0 0.0 0 2",
            "-0.5470 0.9499 0.0 0 3",
            // Missing Component 2 entirely
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_single_frame(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ParseError::IncompleteFrame));
    }

    #[test]
    fn test_parse_single_frame_missing_atom_index_defaults_sequential() {
        // Column 5 (atom_index) is optional; when absent, defaults to sequential.
        let lines = vec![
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "3 3",
            "12.011 1.008",
            "1",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 0 1",
            "1.0940 0.0 0.0 0 2",
            "-0.5470 0.9499 0.0 0 3",
            "2",
            "Coordinates of Component 2",
            "5.0 5.0 5.0 0",       // No atom_index: defaults to 3
            "6.0940 5.0 5.0 0 10", // Explicit atom_index: 10
            "5.5470 5.9499 5.0 0", // No atom_index: defaults to 5
        ];
        let mut line_it = lines.iter().copied();
        let frame = parse_single_frame(&mut line_it).unwrap();
        assert_eq!(frame.atom_data.len(), 6);
        // First type: explicit atom_index values
        assert_eq!(frame.atom_data[0].atom_id, 1);
        assert_eq!(frame.atom_data[1].atom_id, 2);
        assert_eq!(frame.atom_data[2].atom_id, 3);
        // Second type: mixed explicit and defaulted
        assert_eq!(frame.atom_data[3].atom_id, 3); // defaulted (global idx 3)
        assert_eq!(frame.atom_data[4].atom_id, 10); // explicit
        assert_eq!(frame.atom_data[5].atom_id, 5); // defaulted (global idx 5)
    }

    #[test]
    fn test_parse_single_frame_too_few_columns_fails() {
        // Only 3 columns (missing fixed_flag too) should still fail.
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
            "C",
            "Coordinates of Component 1",
            "0.0 0.0 0.0", // Only 3 values
        ];
        let mut line_it = lines.iter().copied();
        let result = parse_single_frame(&mut line_it);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ParseError::InvalidVectorLength {
                expected: 5,
                found: 3
            }
        ));
    }

    #[test]
    fn test_parse_velocity_section_present() {
        let lines = vec![
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "2",
            "1 1",
            "63.546 1.008",
            "Cu",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 1 0",
            "H",
            "Coordinates of Component 2",
            "1.0 2.0 3.0 0 1",
            "",
            "Cu",
            "Velocities of Component 1",
            "0.1 0.2 0.3 1 0",
            "H",
            "Velocities of Component 2",
            "0.4 0.5 0.6 0 1",
        ];
        let mut line_it = lines.iter().copied().peekable();
        // Parse the frame first (consuming 15 lines)
        let mut frame =
            parse_single_frame(&mut line_it).expect("coordinate parsing should succeed");
        assert!(!frame.has_velocities());

        // Now parse the velocity section
        let mut column = Vec::new();
        let has_vel = parse_velocity_section(
            &mut line_it,
            &frame.header,
            &mut frame.atom_data,
            &mut column,
        )
        .expect("velocity parsing should succeed");
        assert!(has_vel);
        frame.adopt_velocity_column(column);
        assert_eq!(frame.atom_data[0].velocity(), Some([0.1, 0.2, 0.3]));
        assert_eq!(frame.atom_data[1].velocity(), Some([0.4, 0.5, 0.6]));
    }

    #[test]
    fn test_validate_true_accepts_matching_section_identity() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":["velocities"],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
2
1 1
63.546 1.008
Cu
Coordinates of Component 1
0.0 0.0 0.0 5 0
H
Coordinates of Component 2
1.0 2.0 3.0 0 1

Cu
Velocities of Component 1
0.1 0.2 0.3 5 0
H
Velocities of Component 2
0.4 0.5 0.6 0 1
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let frame = iter.next().unwrap().unwrap();

        assert!(frame.has_velocities());
        assert_eq!(
            frame
                .header
                .metadata
                .get("validate")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[test]
    fn test_validate_true_rejects_section_atom_id_mismatch() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":["velocities"],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 5 0

Cu
Velocities of Component 1
0.1 0.2 0.3 5 99
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(err, ParseError::ValidationError(_)));
        assert!(err.to_string().contains("atom_id mismatch"));
    }

    #[test]
    fn test_validate_true_rejects_section_symbol_mismatch() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":["forces"],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 5 0

H
Forces of Component 1
0.1 0.2 0.3 5 0
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(err, ParseError::ValidationError(_)));
        assert!(err.to_string().contains("symbol mismatch"));
    }

    #[test]
    fn test_validate_absent_allows_legacy_duplicate_identity_mismatch() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":["velocities"]}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 5 0

Cu
Velocities of Component 1
0.1 0.2 0.3 0 99
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let frame = iter.next().unwrap().unwrap();

        assert!(frame.has_velocities());
        assert_eq!(frame.atom_data[0].atom_id, 0);
        assert_eq!(frame.atom_data[0].fixed(), [true, false, true]);
    }

    #[test]
    fn test_validate_must_be_boolean_when_present() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"validate\":\"yes\",\"sections\":[]}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
        assert!(err.to_string().contains("validate"));
    }

    #[test]
    fn test_validate_true_requires_sections_key() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"validate\":true}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
        assert!(err.to_string().contains("sections"));
    }

    #[test]
    fn test_sections_must_be_string_array_when_present() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"sections\":[\"velocities\",7]}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
        assert!(err.to_string().contains("sections"));
    }

    #[test]
    fn test_validate_true_rejects_non_integer_coordinate_identity_columns() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":[],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 5.0 0
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(err, ParseError::InvalidFixedFlag(_)));
        assert!(err.to_string().contains("5.0"));
    }

    #[test]
    fn test_validate_true_rejects_non_exact_coordinate_label() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":[],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates Component 1
0.0 0.0 0.0 5 0
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(err, ParseError::ValidationError(_)));
        assert!(err.to_string().contains("Coordinates of Component 1"));
    }

    #[test]
    fn test_validate_true_rejects_unknown_component_symbol() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":[],"validate":true}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Qq
Coordinates of Component 1
0.0 0.0 0.0 0 0
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(err, ParseError::ValidationError(_)));
        assert!(err.to_string().contains("symbol"));
    }

    #[test]
    fn test_declared_section_must_be_present() {
        let text = r#"
PREBOX1
{"con_spec_version":2,"sections":["velocities"]}
10.0 20.0 30.0
90.0 90.0 90.0
POSTBOX1
POSTBOX2
1
1
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 0 0
"#;
        let mut iter = ConFrameIterator::new(text.trim());
        let err = iter.next().unwrap().unwrap_err();

        assert!(matches!(
            err,
            ParseError::IncompleteSection(ref name) if name == "velocities"
        ));
    }

    #[test]
    fn test_non_finite_cell_geometry_rejected_in_strict_mode() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true}",
            "10.0 NaN 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::NonFiniteValue(_)));
        assert!(err.to_string().contains("NaN"));
    }

    #[test]
    fn test_validate_true_rejects_non_physical_cell_geometry() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true}",
            "0.0 20.0 30.0",
            "90.0 180.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::ValidationError(_)));
        assert!(err.to_string().contains("cell"));
    }

    #[test]
    fn test_validate_true_rejects_reserved_metadata_type_mismatch() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true,\"energy\":\"low\"}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();

        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
        assert!(err.to_string().contains("energy"));
    }

    #[test]
    fn test_validate_true_rejects_malformed_bonds() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"sections\":[],\"validate\":true,\"bonds\":[[0]]}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let err = parse_frame_header(&mut line_it).unwrap_err();
        assert!(matches!(err, ParseError::InvalidMetadataJson(_)));
        assert!(err.to_string().contains("bonds"));
    }

    #[test]
    fn test_bonds_metadata_round_trip_in_header() {
        use crate::types::{Bond, meta};
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2,\"bonds\":[[0,1],{\"i\":0,\"j\":2,\"order\":1}]}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
        ];
        let mut line_it = lines.iter().copied();
        let header = parse_frame_header(&mut line_it).expect("header");
        let bonds = header.bonds();
        assert_eq!(bonds.len(), 2);
        assert_eq!(bonds[0], Bond::new(0, 1));
        assert_eq!(bonds[1].i, 0);
        assert_eq!(bonds[1].j, 2);
        assert_eq!(bonds[1].order, Some(1));
        assert!(header.metadata.contains_key(meta::BONDS));
    }

    #[test]
    fn test_parse_velocity_section_absent() {
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 20.0 30.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "1",
            "12.011",
            "C",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 0 1",
        ];
        let mut line_it = lines.iter().copied().peekable();
        let mut frame = parse_single_frame(&mut line_it).expect("parse should succeed");
        let mut column = Vec::new();
        let has_vel = parse_velocity_section(
            &mut line_it,
            &frame.header,
            &mut frame.atom_data,
            &mut column,
        )
        .expect("should succeed with no velocities");
        assert!(!has_vel);
        assert!(column.is_empty());
        assert_eq!(frame.atom_data[0].velocity(), None);
    }

    /// The velocity column is the storage `atom.velocity` reads. Writing the
    /// atom updates that buffer in place, and the bytes match the file.
    #[test]
    fn velocity_column_aliases_soa_bytes() {
        let text = "\
bulk
{\"con_spec_version\":2}
4.0 5.0 6.0
90.0 90.0 90.0
0 0
0 0
1
2
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 7 0
1.0 0.0 0.0 0 1

Cu
Velocities of Component 1
0.125 -0.25 0.5 7 0
-0.125 0.25 -0.5 0 1
";
        let mut frame = ConFrameIterator::new(text)
            .next()
            .expect("frame")
            .expect("parse");
        let soa = frame.velocities.f64_slice().expect("f64 column");
        let mut packed = Vec::with_capacity(soa.len());
        for atom in &frame.atom_data {
            packed.extend_from_slice(&atom.velocity().expect("velocity"));
        }
        assert_eq!(soa, packed.as_slice());
        assert_eq!(soa, &[0.125, -0.25, 0.5, -0.125, 0.25, -0.5][..]);
        assert_eq!(frame.atom_data[0].velocity_slot(), soa.as_ptr());
        frame.atom_data[0].set_velocity(Some([9.0, 8.0, 7.0]));
        assert_eq!(frame.velocities.as_f64_row(0), [9.0, 8.0, 7.0]);
        assert_eq!(frame.velocities.as_f64_row(1), [-0.125, 0.25, -0.5]);
    }

    #[test]
    fn force_column_aliases_soa_bytes() {
        let text = "\
bulk
{\"con_spec_version\":2,\"sections\":[\"forces\"]}
4.0 5.0 6.0
90.0 90.0 90.0
0 0
0 0
1
2
63.546
Cu
Coordinates of Component 1
0.0 0.0 0.0 0 0
1.0 1.0 1.0 7 1

Cu
Forces of Component 1
0.1 0.2 0.3 0 0
-0.4 0.5 -0.6 7 1
";
        let mut frame = ConFrameIterator::new(text)
            .next()
            .expect("frame")
            .expect("parse");
        let soa = frame.forces.f64_slice().expect("f64 column");
        let mut packed = Vec::with_capacity(soa.len());
        for atom in &frame.atom_data {
            packed.extend_from_slice(&atom.force().expect("force"));
        }
        assert_eq!(soa, packed.as_slice());
        assert_eq!(soa, &[0.1, 0.2, 0.3, -0.4, 0.5, -0.6][..]);
        assert_eq!(frame.atom_data[0].force_slot(), soa.as_ptr());
        frame.atom_data[1].set_force(Some([1.0, 2.0, 3.0]));
        assert_eq!(frame.forces.as_f64_row(1), [1.0, 2.0, 3.0]);
    }

    /// Million-atom `.convel` parse. Release builds must stay under the
    /// per-atom box path (about 0.7 s on this host).
    #[test]
    #[ignore = "times a million-atom convel parse"]
    fn microbench_convel_column_parse() {
        let n = 1_000_000usize;
        let mut text = String::with_capacity(n * 64);
        text.push_str("bench\n{\"con_spec_version\":2}\n4 5 6\n90 90 90\n0 0\n0 0\n1\n");
        text.push_str(&format!("{n}\n63.546\nCu\nCoordinates of Component 1\n"));
        for i in 0..n {
            text.push_str(&format!("0 0 0 0 {i}\n"));
        }
        text.push_str("\nCu\nVelocities of Component 1\n");
        for i in 0..n {
            let v = (i % 1000) as f64 * 0.001;
            text.push_str(&format!("{v} 0 0 0 {i}\n"));
        }
        let started = std::time::Instant::now();
        let frame = ConFrameIterator::new(&text)
            .next()
            .expect("frame")
            .expect("parse");
        let elapsed = started.elapsed().as_secs_f64();
        eprintln!("convel column parse {n} atoms {elapsed:.4} s");
        let soa = frame.velocities.f64_slice().expect("f64");
        assert_eq!(frame.atom_data[0].velocity_slot(), soa.as_ptr());
        assert_eq!(frame.atom_data[n - 1].velocity().unwrap()[0], 0.999);
        assert_eq!(soa[(n - 1) * 3], 0.999);
        if !cfg!(debug_assertions) {
            assert!(elapsed < 0.35, "convel parse {elapsed:.4} s");
        }
        let real = std::path::Path::new("bench/h2h/work/thread-reads/con-h2h.convel");
        if let Ok(bytes) = std::fs::read(real) {
            let started = std::time::Instant::now();
            let frame = ConFrameIterator::from_bytes(&bytes)
                .next()
                .expect("frame")
                .expect("parse");
            let elapsed = started.elapsed().as_secs_f64();
            eprintln!("real convel column parse {elapsed:.4} s");
            let soa = frame.velocities.f64_slice().expect("f64");
            assert_eq!(frame.atom_data[0].velocity_slot(), soa.as_ptr());
            assert_eq!(
                frame.atom_data[0].velocity().unwrap(),
                frame.velocities.as_f64_row(0)
            );
        }
    }

    #[test]
    fn test_parse_line_of_range_f64_exact() {
        let vals = parse_line_of_range_f64("1.0 2.0 3.0 0.0 42", 4, 5, &[0.0; 5]).unwrap();
        assert_eq!(vals, vec![1.0, 2.0, 3.0, 0.0, 42.0]);
    }

    #[test]
    fn test_byte_scan_stack_parses_realistic_coord_line() {
        // Typical CON atom line: x y z fixed_mask [atom_id]
        let line = "   0.63939999999999997    0.90449999999999997   -0.00009999999999977 1    0";
        let defaults = [0.0, 0.0, 0.0, 0.0, 99.0];
        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
        let n = parse_line_of_range_f64_stack(line, 4, 5, &defaults, &mut buf).unwrap();
        assert_eq!(n, 5);
        assert!((buf[0] - 0.6394).abs() < 1e-4);
        assert!((buf[1] - 0.9045).abs() < 1e-4);
        assert_eq!(buf[3] as u8, 1);
        assert_eq!(buf[4] as u64, 0);
        // trailing junk must error
        let bad = "1.0 2.0 3.0 1 0 EXTRA";
        assert!(parse_line_of_range_f64_stack(bad, 4, 5, &defaults, &mut buf).is_err());
        // partial non-boundary token must error
        let glued = "1.0 2.0 3.0abc 1 0";
        assert!(parse_line_of_range_f64_stack(glued, 4, 5, &defaults, &mut buf).is_err());
    }

    #[test]
    fn test_parse_line_of_range_f64_stack_matches_vec_api() {
        let defaults = [0.0, 0.0, 0.0, 0.0, 7.0];
        let line = "1.0 2.0 3.0 0.0";
        let mut buf = [0.0f64; NUMERIC_STACK_WIDTH];
        parse_line_of_range_f64_stack(line, 4, 5, &defaults, &mut buf).unwrap();
        let via_vec = parse_line_of_range_f64(line, 4, 5, &defaults).unwrap();
        assert_eq!(&buf[..5], via_vec.as_slice());
        assert_eq!(buf[4], 7.0);
    }

    #[test]
    fn test_parse_line_of_range_f64_padded() {
        let defaults = [0.0, 0.0, 0.0, 0.0, 99.0];
        let vals = parse_line_of_range_f64("1.0 2.0 3.0 0.0", 4, 5, &defaults).unwrap();
        assert_eq!(vals, vec![1.0, 2.0, 3.0, 0.0, 99.0]);
    }

    #[test]
    fn test_parse_line_of_range_f64_too_few() {
        let result = parse_line_of_range_f64("1.0 2.0 3.0", 4, 5, &[0.0; 5]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_line_of_range_f64_too_many() {
        let result = parse_line_of_range_f64("1.0 2.0 3.0 0.0 5.0 6.0", 4, 5, &[0.0; 5]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_all_four_column_lines() {
        // All atom lines have only 4 columns; atom_index defaults to sequential.
        let lines = [
            "PREBOX1",
            "{\"con_spec_version\":2}",
            "10.0 10.0 10.0",
            "90.0 90.0 90.0",
            "POSTBOX1",
            "POSTBOX2",
            "1",
            "3",
            "12.011",
            "C",
            "Coordinates of Component 1",
            "0.0 0.0 0.0 0",
            "1.0 0.0 0.0 0",
            "2.0 0.0 0.0 1",
        ];
        let mut line_it = lines.iter().copied();
        let frame = parse_single_frame(&mut line_it).unwrap();
        assert_eq!(frame.atom_data[0].atom_id, 0);
        assert_eq!(frame.atom_data[1].atom_id, 1);
        assert_eq!(frame.atom_data[2].atom_id, 2);
        assert!(frame.atom_data[2].is_fixed());
    }

    #[test]
    fn test_positions_take_the_storage_dtype_of_the_metadata() {
        use crate::storage_dtype::{ElementKind, FloatArray2};
        let rows = [[0.5, -1.25, 3.0], [1.0e-3, 2.5e4, -7.75]];
        let atom_lines: Vec<String> = rows
            .iter()
            .enumerate()
            .map(|(id, [x, y, z])| format!("{x} {y} {z} 0 {id}"))
            .collect();
        for &kind in ElementKind::all_hosted() {
            let metadata = format!(
                "{{\"con_spec_version\":3,\"units\":{{\"length\":\"angstrom\",\"energy\":\"eV\"}},\
                 \"storage_dtypes\":{{\"positions\":\"{}\"}}}}",
                kind.as_str()
            );
            let mut lines = vec![
                "PREBOX1",
                metadata.as_str(),
                "10.0 10.0 10.0",
                "90.0 90.0 90.0",
                "POSTBOX1",
                "POSTBOX2",
                "1",
                "2",
                "1.008",
                "H",
                "Coordinates of Component 1",
            ];
            lines.extend(atom_lines.iter().map(String::as_str));
            let frame = parse_single_frame(&mut lines.iter().copied()).unwrap();
            assert_eq!(frame.positions.kind(), kind);
            assert_eq!(frame.positions.nrows(), rows.len());
            for (i, &xyz) in rows.iter().enumerate() {
                let mut expected = FloatArray2::zeros(kind, 1, 3);
                expected.set_f64_row(0, xyz);
                assert_eq!(
                    frame.positions.as_f64_row(i),
                    expected.as_f64_row(0),
                    "{kind:?} row {i}"
                );
            }
        }
    }
}

#[cfg(all(test, feature = "parallel"))]
mod newline_index_bench {
    use super::newline_index_at;

    #[test]
    fn index_matches_memchr() {
        let mut bytes = vec![b'x'; 80_000];
        for index in (20..bytes.len()).step_by(23) {
            bytes[index] = b'\n';
        }
        let serial: Vec<usize> = memchr::memchr_iter(b'\n', &bytes).collect();
        assert_eq!(newline_index_at(&bytes, 0, 8), serial);
        // Above the 1 MiB serial cutoff, including a buffer of bare newlines.
        let mut long = Vec::new();
        while long.len() < (1 << 20) + 64 {
            long.extend_from_slice(b"01234567 1.25 -2.5 3.5 0 7\n");
        }
        let long_serial: Vec<usize> = memchr::memchr_iter(b'\n', &long).collect();
        assert_eq!(newline_index_at(&long, 40, 8), {
            let mut shifted = long_serial.clone();
            for offset in &mut shifted {
                *offset += 40;
            }
            shifted
        });
        let bare = vec![b'\n'; (1 << 20) + 64];
        let bare_serial: Vec<usize> = memchr::memchr_iter(b'\n', &bare).collect();
        assert_eq!(newline_index_at(&bare, 0, 8), bare_serial);
    }
}