bstack 0.4.0

A persistent, fsync-durable binary stack backed by a single file
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
//! A persistent, fsync-durable binary stack backed by a single file.
//!
//! # Overview
//!
//! [`BStack`] treats a file as a flat byte buffer that grows and shrinks from
//! the tail.  Every mutating operation — [`push`](BStack::push),
//! [`extend`](BStack::extend), [`pop`](BStack::pop), [`discard`](BStack::discard), (with the `set`
//! feature) [`set`](BStack::set), [`zero`](BStack::zero), and
//! [`repeat`](BStack::repeat), (with the `atomic` feature)
//! [`replace`](BStack::replace), and (with both `set` and `atomic`)
//! [`process`](BStack::process) — calls a *durable sync* before returning,
//! so the data survives a process crash or an unclean system shutdown.
//! Read-only operations — [`peek`](BStack::peek),
//! [`peek_into`](BStack::peek_into), [`get`](BStack::get), and
//! [`get_into`](BStack::get_into) — never modify the file and on Unix and
//! Windows can run concurrently with each other.
//! [`pop_into`](BStack::pop_into) is the buffer-passing counterpart of `pop`,
//! carrying the same durability and atomicity guarantees.
//! [`discard`](BStack::discard) is like `pop` but discards the removed bytes
//! without reading or returning them, avoiding any allocation or copy.
//!
//! The crate depends on **`libc`** (Unix) and **`windows-sys`** (Windows) for
//! platform-specific syscalls, and uses **no `unsafe` code beyond the required
//! FFI calls**.
//!
//! # File format
//!
//! Every file begins with a fixed 32-byte header, then the concatenated payload
//! (push 0, push 1, …):
//!
//! ```text
//!   bytes      field
//!   ─────      ─────
//!    0 ..  8   magic[8]
//!    8 .. 16   clen      — committed payload length (u64 LE)
//!   16 .. 24   wip_ptr   — write-in-progress journal target (u64 LE; 0 when idle)
//!   24 .. 32   wip_aux   — write-in-progress journal mode (u64 LE)
//!   32 ..      payload   — push 0, push 1, … concatenated
//! ```
//!
//! * **`magic`** — 8 bytes: `BSTK` + major(1 B) + minor(1 B) + patch(1 B) + reserved(1 B).
//!   This version writes `BSTK\x00\x04\x00\x00` (0.4.0).  [`open`](BStack::open)
//!   accepts any file whose first 6 bytes match `BSTK\x00\x04` (any 0.4.x) and
//!   rejects anything with a different major or minor.
//! * **`clen`** — little-endian `u64` recording the *committed* payload length.
//!   It is updated atomically with each [`push`](BStack::push) or
//!   [`pop`](BStack::pop) and is used for crash recovery on the next
//!   [`open`](BStack::open).
//! * **`wip_ptr` / `wip_aux`** — two little-endian `u64` fields holding the
//!   write-in-progress journal that makes in-place mutations crash-atomic.
//!   `wip_ptr` is the physical offset an interrupted in-place write must be
//!   replayed into (`0` in the steady state); `wip_aux` names the journal mode
//!   (`Set` — verbatim replay of the staged tail; `Repeat` — repeat a staged
//!   pattern; `Copy` — replay a disjoint copy from its still-intact source, of
//!   which only the coordinate is staged; `SpliceGrow`/`SpliceShrink` — a
//!   length-changing tail replace, whose new committed length recovery derives
//!   from the file size and the recorded direction). Recovery interprets them on
//!   [`open`](BStack::open) — see *Crash
//!   recovery*. Legacy 0.1.x files (16-byte header) are upgraded in place by
//!   [`BStack::migrate`].
//!
//! All user-visible offsets are **logical** (0-based from the start of the
//! payload region, i.e. from file byte 32).
//!
//! # Crash recovery
//!
//! On [`open`](BStack::open), recovery first checks the write-in-progress journal
//! (`wip_ptr`); if disarmed, it reconciles the committed length against the file
//! size:
//!
//! | Condition | Cause | Recovery |
//! |-----------|-------|----------|
//! | `wip_ptr != 0`, `wip_aux = Set` | an in-place `set`/`swap`/`cas`/`copy`/`cross_exchange` crashed mid-commit | replay the staged tail verbatim into `[wip_ptr, …)`, disarm, truncate to `32 + clen` |
//! | `wip_ptr != 0`, `wip_aux = Repeat` | a `zero`/`repeat` crashed mid-fill | write `count` copies of the staged pattern into `[wip_ptr, …)`, disarm, truncate |
//! | `wip_ptr != 0`, `wip_aux = Copy` | a disjoint `copy` crashed mid-copy | replay `move_chunked(src → wip_ptr)` from the untouched source (the tail stages only `[src \| n]`), disarm, truncate |
//! | `wip_ptr != 0`, `wip_aux = SpliceGrow`/`SpliceShrink` | a length-changing `atrunc`/`splice`/`splice_into`/`replace` crashed mid-replace | derive `clen'` from the file size and direction, replay the staged new tail into `[wip_ptr, …)`, commit `clen'` while disarming, truncate |
//! | `wip_ptr != 0`, `wip_aux` unrecognized | a mode armed by a newer build | roll back: disarm, truncate to `32 + clen` |
//! | `wip_ptr == 0`, `wip_aux = MultiWrite` | a `set_batched`/`inplace_gen` multi-write batch crashed after all blocks were staged | replay each staged `[s \| e \| data]` block into `[s, e)`, disarm, truncate to `32 + clen` (a corrupt tail rolls back, applying nothing) |
//! | `wip_ptr == 0`, `file_size − 32 > clen` | partial tail write (push, or a crashed journal or multi-write stage) before the header update | truncate to `32 + clen` |
//! | `wip_ptr == 0`, `file_size − 32 < clen` | partial truncation (pop crashed before the header update) | set `clen = file_size − 32` |
//!
//! Each replay is idempotent — the staged tail is immutable and disjoint from
//! its target — so a crash during recovery itself is safe to re-run. After
//! recovery a `durable_sync` ensures the repaired state is on stable storage
//! before any caller can observe or modify the file.
//!
//! # Durability
//!
//! **In-place same-length writes** — [`set`](BStack::set), [`zero`](BStack::zero),
//! [`repeat`](BStack::repeat), [`swap`](BStack::swap),
//! [`swap_into`](BStack::swap_into), [`cas`](BStack::cas), [`copy`](BStack::copy),
//! [`cross_exchange`](BStack::cross_exchange), [`process`](BStack::process),
//! [`set_batched`](BStack::set_batched), [`inplace_gen`](BStack::inplace_gen), and
//! the `crds` family — leave the payload length unchanged and are each
//! **crash-atomic**, committing by one of three strategies (recovered on the next
//! [`open`](BStack::open); see *Crash recovery*):
//!
//! * **Aligned-block write** — when the target lies within one power-fail-atomic
//!   block, a single `write` + `durable_sync` is already all-or-nothing; no
//!   journal is armed.
//! * **Write-in-progress journal** — otherwise: stage a backup past `clen` →
//!   `durable_sync` → arm `wip_ptr` → `durable_sync` → write in place →
//!   `durable_sync` → clear `wip_ptr` → `durable_sync` → `ftruncate` the backup.
//!   `zero`/`repeat` stage only `[count | pattern]`; `cross_exchange` stages one
//!   region and commits at a single atomic `wip_ptr` flip; moves and fills stream
//!   through a bounded buffer (O(1) memory).
//! * **Multi-write journal** — [`set_batched`](BStack::set_batched) and
//!   [`inplace_gen`](BStack::inplace_gen) commit several non-overlapping in-place
//!   writes as one unit: stage every `[s | e | data]` block past `clen` →
//!   `durable_sync` → arm the `MultiWrite` sentinel (`wip_ptr` stays `0`, so it
//!   never collides with a single-region journal) → `durable_sync` → replay each
//!   block in place → `durable_sync` → disarm → `ftruncate`. A batch that reduces
//!   to one write falls back to the single-write strategies above.
//!
//! Below, *commit* denotes whichever of those two strategies applies to the bytes
//! being written; anything before it is read/compare/callback work under the lock.
//!
//! | Operation | Syscall sequence |
//! |-----------|-----------------|
//! | `push` | `lseek(END)` → `write(data)` → `lseek(8)` → `write(clen)` → `durable_sync` |
//! | `extend` | `lseek(END)` → `set_len(new_end)` → `lseek(8)` → `write(clen)` → `durable_sync` |
//! | `pop`, `pop_into` | `lseek` → `read` → `ftruncate` → `lseek(8)` → `write(clen)` → `durable_sync` |
//! | `discard` | `ftruncate` → `lseek(8)` → `write(clen)` → `durable_sync` |
//! | `set` *(feature)* | *commit* `data` |
//! | `zero`, `repeat` *(feature)* | *commit* the repeated pattern (the journal stages only `[count \| pattern]`) |
//! | `atrunc` *(feature: atomic)* | dispatch on the tail-replace shape: pure truncation → `ftruncate` → *commit* `clen`; pure append → `set_len(new_end)` → `write(buf)` → `durable_sync` → *commit* `clen`; same-length → *commit* `buf` in place; length change → **splice journal** (stage the new tail past the payload → arm `SpliceGrow`/`SpliceShrink` → replay into place → atomically commit `clen'` + disarm → truncate, a `durable_sync` at each barrier) |
//! | `splice`, `splice_into` *(feature: atomic)* | `lseek(tail)` → `read(n)` → *(then as `atrunc`)* |
//! | `try_extend` *(feature: atomic)* | `lseek(END)` — conditional `push` sequence if size matches |
//! | `try_discard` *(feature: atomic)* | `lseek(END)` — conditional `discard` sequence if size matches |
//! | `try_extend_zeros` *(feature: atomic)* | `lseek(END)` — conditional `extend(n)` sequence if size matches |
//! | `swap`, `swap_into` *(features: set+atomic)* | `read` old bytes → *commit* `buf` |
//! | `cas` *(features: set+atomic)* | `read` → compare — conditional *commit* of `new` |
//! | `process` *(features: set+atomic)* | `read(start..end)` → *(callback)* → *commit* the buffer |
//! | `process_gen` *(features: set+atomic)* | closure-driven reads, ending in at most one mutating step: `Write` *commits*; `Swap` uses the exchange journal (as `cross_exchange`); `Push`/`Pop`/`Discard`/`Atrunc`/`Splice` behave as their standalone forms |
//! | `set_batched` *(features: set+atomic)* | validate + reject overlap → **multi-write journal**: stage every `[s \| e \| data]` block past `clen` → arm the `MultiWrite` sentinel (`wip_ptr` stays `0`) → replay each block in place → disarm → `ftruncate` (a `durable_sync` at each barrier); a lone effective write takes the ordinary single-write *commit* |
//! | `inplace_gen` *(features: set+atomic)* | closure-driven reads (each overlaid with the batch-so-far edits) interleaved with accumulated `Write`s (later overrides earlier on overlap); on `None` the pending edits commit together via the multi-write journal (as `set_batched`) |
//! | `replace` *(feature: atomic)* | `lseek(tail)` → `read(n)` → *(callback)* → *(then as `atrunc`)* |
//! | `cross_exchange` *(features: set+atomic)* | `read(a)`, `read(b)` → exchange journal: stage `a` → arm at `a` → write `b`→`a` → flip `wip_ptr` to `b` → write `a`→`b` → disarm → `ftruncate` (a `durable_sync` at each barrier) |
//! | `copy` *(features: set+atomic)* | same-location → no-op; single-block dest → *commit*; overlapping → stream source→tail→dest (`Set` journal); disjoint → **copy journal** (stage only `[src \| n]` → arm `Copy` → stream source→dest → disarm; recovery replays from the untouched source) |
//! | `eq_crds`, `ne_crds` *(features: set+atomic)* | `read(a)` → compare — conditional *commit* of `b_buf` |
//! | `masked_eq_crds`, `masked_ne_crds` *(features: set+atomic)* | `read(a)` → mask+compare — conditional *commit* of `b_buf` |
//! | `peek`, `peek_into`, `get`, `get_into`, `get_batched`, `get_batched_into`, `get_batched_gen` | `pread(2)` on Unix; `ReadFile`+`OVERLAPPED` on Windows; `lseek` → `read` elsewhere (no sync — read-only) |
//!
//! **`durable_sync` on macOS** issues `fcntl(F_FULLFSYNC)`, which flushes the
//! drive's hardware write cache.  Plain `fdatasync` is not sufficient on macOS
//! because the kernel may acknowledge it before the drive controller has
//! committed the data.  If `F_FULLFSYNC` is not supported by the device the
//! implementation falls back to `sync_data` (`fdatasync`).
//!
//! **`durable_sync` on other Unix** calls `sync_data` (`fdatasync`), which is
//! sufficient on Linux and BSD.
//!
//! **`durable_sync` on Windows** calls `sync_data`, which maps to
//! `FlushFileBuffers`.  This flushes the kernel write-back cache and waits for
//! the drive to acknowledge, providing equivalent durability to `fdatasync`.
//!
//! # Multi-process safety
//!
//! On Unix, [`open`](BStack::open) acquires an **exclusive advisory `flock`**
//! on the file (`LOCK_EX | LOCK_NB`).  If another process already holds the
//! lock, `open` returns immediately with [`io::ErrorKind::WouldBlock`] rather
//! than blocking indefinitely.  The lock is released automatically when the
//! [`BStack`] is dropped (the underlying file descriptor is closed).
//!
//! On Windows, [`open`](BStack::open) acquires an **exclusive `LockFileEx`**
//! lock (`LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY`) covering the
//! entire file range.  If another process already holds the lock, `open`
//! returns immediately with [`io::ErrorKind::WouldBlock`]
//! (`ERROR_LOCK_VIOLATION`).  The lock is released when the [`BStack`] is
//! dropped (the underlying file handle is closed).
//!
//! > **Note:** Both `flock` (Unix) and `LockFileEx` (Windows) are advisory
//! > and per-process.  They prevent well-behaved concurrent opens across
//! > processes but do not protect against processes that bypass the lock or
//! > against raw writes to the file.
//!
//! # Correct usage
//!
//! bstack files must only be opened through this crate or a compatible
//! implementation that understands the file format, the header protocol, and
//! the locking semantics.  Reading or writing the underlying file with raw
//! tools or syscalls while a [`BStack`] instance is live — or manually editing
//! the header fields — can silently corrupt the committed-length sentinel or
//! bypass the advisory lock.
//!
//! **The authors make no guarantees about the behaviour of this crate —
//! including freedom from data loss or logical corruption — when the file has
//! been accessed outside of this crate's controlled interface.**
//!
//! # Thread safety
//!
//! `BStack` wraps the file in a [`std::sync::RwLock`]. The committed payload
//! length is also cached in memory and kept in sync with the on-disk header
//! by every write-lock-held operation, so [`len`](BStack::len) and
//! [`is_empty`](BStack::is_empty) can be answered under the read lock without
//! any `File::metadata` syscall.
//!
//! | Operation | Lock (Unix / Windows) | Lock (other) |
//! |-----------|-----------------------|--------------|
//! | `push`, `extend`, `pop`, `pop_into`, `discard` | write | write |
//! | `set`, `zero`, `repeat` *(feature)* | write | write |
//! | `atrunc`, `splice`, `splice_into`, `try_extend`, `try_extend_zeros` *(feature: atomic)* | write | write |
//! | `try_discard(s, n > 0)` *(feature: atomic)* | write | write |
//! | `try_discard(s, 0)` *(feature: atomic)* | **read** | **read** |
//! | `get_batched`, `get_batched_into`, `get_batched_gen` *(feature: atomic)* | **read** | write |
//! | `swap`, `swap_into`, `cas` *(features: set+atomic)* | write | write |
//! | `cross_exchange`, `copy`, `process`, `process_gen`, `set_batched`, `inplace_gen` *(features: set+atomic)* | write | write |
//! | `eq_crds`, `ne_crds`, `masked_eq_crds`, `masked_ne_crds` *(features: set+atomic)* | write | write |
//! | `replace` *(feature: atomic)* | write | write |
//! | `peek`, `peek_into`, `get`, `get_into` | **read** | write |
//! | `len` | read | read |
//!
//! On Unix and Windows, `peek`, `peek_into`, `get`, and `get_into` use a
//! cursor-safe positional read (`pread(2)` on Unix; `ReadFile` with
//! `OVERLAPPED` on Windows) that does not modify the file-position cursor.
//! This allows multiple concurrent calls to any of these methods to run in
//! parallel while any ongoing `push`, `pop`, or `pop_into` still serialises
//! all writers via the write lock.  For [`get`](BStack::get) and
//! [`get_into`](BStack::get_into), reads that lie entirely within the
//! [locked region](#locked-region-lock_up_to) bypass the rwlock — see that
//! section for the concurrency model.
//!
//! On other platforms a seek is required, so `peek`, `peek_into`, `get`, and
//! `get_into` fall back to the write lock and all reads serialise.
//!
//! Unlike [`get_batched_gen`](BStack::get_batched_gen), which only ever takes
//! the **read** lock (Unix/Windows), [`process_gen`](BStack::process_gen) and
//! [`inplace_gen`](BStack::inplace_gen) *always* take the **write** lock — even
//! for sequences that turn out to be read-only and end in `None` — because the
//! closure may decide, only after seeing earlier reads, to mutate; the lock
//! therefore has to be acquired before the first read so the whole sequence
//! runs as one indivisible step.
//!
//! # Locked region (`lock_up_to`)
//!
//! [`BStack`] maintains an in-memory **monotonically growing partition
//! boundary** named the *locked region*.  Bytes in `[0, locked_len())` are
//! declared permanently immutable for the lifetime of the open file.
//!
//! The locked length starts at `0` on every [`open`](BStack::open) and is
//! **not persisted to disk** — the file format is unchanged.  Callers extend
//! the boundary by calling [`lock_up_to`](BStack::lock_up_to) (or open and
//! lock in one step with [`open_locked_up_to`](BStack::open_locked_up_to)).
//! It can only grow; attempts to shrink it return
//! [`io::ErrorKind::InvalidInput`].
//!
//! Opening with [`open_cached`](BStack::open_cached) (or
//! [`open_locked_up_to_cached`](BStack::open_locked_up_to_cached)) enables
//! an in-memory mirror of the locked region: each `lock_up_to` call reads the
//! newly locked bytes from disk into a heap buffer, and subsequent reads whose
//! range falls entirely within the cached region are served with no syscall.
//!
//! ## Effects
//!
//! * **`get`/`get_into` fast-path reads.**  When [`get`](BStack::get) or
//!   [`get_into`](BStack::get_into) are called with a range that lies entirely
//!   within the locked region, the internal `RwLock` is bypassed.
//!   - On **non-cached** stacks (Unix/Windows), reads are lock-free and use
//!     `pread(2)` (Unix) or `ReadFile` + `OVERLAPPED` (Windows).
//!   - On **cached** stacks (all platforms), reads are served from the
//!     in-memory buffer under a `Mutex` (so RwLock-free, but not lock-free).
//!     The `fstat` size check is skipped on this path — the locked length is a
//!     sufficient upper bound.
//!
//! * **Write protection.**  [`set`](BStack::set), [`zero`](BStack::zero),
//!   [`repeat`](BStack::repeat),
//!   [`swap`](BStack::swap), [`swap_into`](BStack::swap_into),
//!   [`cas`](BStack::cas), [`process`](BStack::process),
//!   [`cross_exchange`](BStack::cross_exchange), [`copy`](BStack::copy)
//!   (destination only), [`eq_crds`](BStack::eq_crds),
//!   [`ne_crds`](BStack::ne_crds), [`masked_eq_crds`](BStack::masked_eq_crds),
//!   and [`masked_ne_crds`](BStack::masked_ne_crds) (region B) return
//!   [`io::ErrorKind::InvalidInput`] when their write target range overlaps
//!   the locked region.  [`atrunc`](BStack::atrunc), [`splice`](BStack::splice),
//!   [`splice_into`](BStack::splice_into), and [`replace`](BStack::replace)
//!   return the same error when the operation would modify bytes inside it.
//!
//! * **Shrink protection.**  [`pop`](BStack::pop),
//!   [`pop_into`](BStack::pop_into), [`discard`](BStack::discard), and
//!   [`try_discard`](BStack::try_discard) return
//!   [`io::ErrorKind::InvalidInput`] when they would shrink the payload
//!   below the locked length.
//!
//! Callers that never invoke `lock_up_to` see no behavioural change — every
//! read and write path adds only a single uncontended `AtomicU64::load` and
//! a comparison.
//!
//! ## Concurrency model
//!
//! `lock_up_to(n)` acquires the exclusive write lock before publishing the
//! new boundary with a `Release` store.  Locked-region fast-path readers
//! `Acquire`-load `locked` before each call.  Two consequences follow:
//!
//! * A stale load is always safe.  If a reader sees an older (smaller)
//!   `locked` value, it falls through to the rwlock path; if it sees a
//!   newer value, the entire range it now reads is by definition immutable.
//!
//! * Locked-region checks on writers are evaluated **under the write lock**,
//!   so they cannot race against a concurrent `lock_up_to` extending the
//!   boundary across the write target.
//!
//! On cached stacks the cache `Mutex` is acquired and fully populated
//! *before* `locked` is advanced with the `Release` store.  A reader that
//! `Acquire`-loads `locked` and then locks the cache `Mutex` therefore always
//! sees a buffer whose valid range covers at least `[0, locked)`.
//!
//! ## Typical use
//!
//! ```no_run
//! use bstack::BStack;
//!
//! # fn main() -> std::io::Result<()> {
//! // A fixed 64-byte metadata block at the head of the file, read by many
//! // threads but never modified after first write.
//! let stack = BStack::open_locked_up_to("meta.bin", 64)?;
//! assert_eq!(stack.locked_len(), 64);
//!
//! // Reads of the metadata bypass the rwlock on Unix and Windows.
//! let header = stack.get(0, 64)?;
//! # let _ = header;
//! # Ok(())
//! # }
//! ```
//!
//! On cached stacks this locked-region fast path is available on all
//! platforms (served from the cache under a `Mutex`).
//!
//! # Standard I/O adapters
//!
//! ## Writing
//!
//! `BStack` implements [`std::io::Write`] (and so does `&BStack`, mirroring
//! [`std::io::Write` for `&File`]).  Each call to `write` is forwarded to
//! [`push`](BStack::push), so every write is atomically appended and durably
//! synced before returning.  `flush` is a no-op.
//!
//! ```no_run
//! use std::io::Write;
//! use bstack::BStack;
//!
//! # fn main() -> std::io::Result<()> {
//! let mut stack = BStack::open("log.bin")?;
//! stack.write_all(b"hello")?;
//! stack.write_all(b"world")?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Reading
//!
//! [`BStackReader`] wraps a `&BStack` with a cursor and implements
//! [`std::io::Read`] and [`std::io::Seek`].  Use [`BStack::reader`] or
//! [`BStack::reader_at`] to construct one.
//!
//! ```no_run
//! use std::io::{Read, Seek, SeekFrom};
//! use bstack::BStack;
//!
//! # fn main() -> std::io::Result<()> {
//! let stack = BStack::open("log.bin")?;
//! stack.push(b"hello world")?;
//!
//! let mut reader = stack.reader();
//! let mut buf = [0u8; 5];
//! reader.read_exact(&mut buf)?;  // b"hello"
//! reader.seek(SeekFrom::Start(6))?;
//! reader.read_exact(&mut buf)?;  // b"world"
//! # Ok(())
//! # }
//! ```
//!
//! # Trait implementations
//!
//! ## `BStack`
//!
//! | Trait | Semantics |
//! |-------|-----------|
//! | `Debug` | Shows `version` (semver string from the magic header, e.g. `"0.4.0"`) and `len` (`Option<u64>`, `None` on I/O failure). |
//! | `PartialEq` / `Eq` | **Pointer identity.** Two values are equal iff they are the same instance. No two distinct `BStack` values in one process can refer to the same file. |
//! | `Hash` | Hashes the instance address — consistent with pointer-identity `PartialEq`. |
//!
//! ## `BStackReader`
//!
//! | Trait | Semantics |
//! |-------|-----------|
//! | `PartialEq` / `Eq` | Equal when both the `BStack` pointer (identity) and the cursor `offset` match. |
//! | `Hash` | Hashes `(BStack pointer, offset)` — consistent with `PartialEq`. |
//! | `PartialOrd` / `Ord` | Ordered by `BStack` instance address, then by cursor `offset`. Groups all readers over the same stack and within that group orders by position. |
//!
//! # Feature flags
//!
//! * **`set`** — In-place overwrite of existing payload bytes without changing
//!   the file size ([`BStack::set`], [`BStack::zero`], [`BStack::repeat`]).
//!
//! * **`alloc`** — Region-based sub-allocation over a `BStack` payload.
//!   Adds the allocator traits, handle types ([`BStackRange`],
//!   [`BStackOwnedSlice`], [`BStackSlice`]), and [`LinearBStackAllocator`] /
//!   [`GhostTreeBstackAllocator`].  Combined with `set`, also enables
//!   [`BStackSliceWriter`], [`FirstFitBStackAllocator`],
//!   [`SlabBStackAllocator`], [`CheckedSlabBStackAllocator`], and
//!   [`BStackByteVec`].
//!
//! * **`atomic`** — Compound read-modify-write operations that hold the write
//!   lock across what would otherwise be separate calls.  Combined with `set`,
//!   also enables atomic swap, CAS, in-place batch writes, and cross-region
//!   operations.
//!
//! Enable with:
//!
//! ```toml
//! [dependencies]
//! bstack = { version = "0.4", features = ["set"] }
//! # or
//! bstack = { version = "0.4", features = ["alloc"] }
//! # or both
//! bstack = { version = "0.4", features = ["alloc", "set"] }
//! ```
//!
//! # Allocator (`alloc` feature)
//!
//! The `alloc` feature adds a region-management layer on top of [`BStack`].
//!
//! ## Key types
//!
//! * [`BStackAllocator`] — trait for types that own a [`BStack`] and manage
//!   contiguous byte regions within its payload.  Requires `stack()`,
//!   `into_stack()`, `alloc()`, and `realloc()`; provides a default no-op
//!   `dealloc()` and delegation helpers `len()` / `is_empty()`.
//!
//! * [`BStackBulkAllocator`] — extension trait for [`BStackAllocator`] that
//!   adds atomic bulk operations.  Both methods are required with no default; on error
//!   the backing store is left unchanged unless a crash occur.
//!
//! * [`BStackUninitAllocator`] — opt-in extension trait for [`BStackAllocator`]
//!   whose `alloc_uninit` / `realloc_uninit` skip zero-initialising newly
//!   allocated or grown bytes.  The returned bytes are **unspecified** (leftover
//!   from a prior allocation) but always valid to read, saving the zero-fill
//!   write for callers that overwrite the region before reading it.  Existing
//!   bytes are preserved exactly as `realloc`.  Implementing it is optional and
//!   signals that the allocator actually has a cheaper uninitialised path.
//!
//! * [`BStackAllocError`]`<'a, A>` — error returned by `realloc` / `dealloc`.
//!   Carries the failing `source` plus `handle: Option<A::Allocated<'a>>`, the
//!   surviving allocation handed back to the caller so a failed resize/free is
//!   not a silent leak.  [`BStackBulkAllocError`] is its `dealloc_bulk`
//!   counterpart, returning a `Vec` of the handles it did not free.
//!
//! * [`BStackRange`] — raw `(offset, len)` pair; `Copy`, no pointer, no I/O.
//!   Serialises to/from `[u8; 16]` for persistent bookkeeping.
//!
//! * [`BStackOwnedSlice`]`<'a, A>` — ownership handle returned by `alloc` /
//!   `realloc`.  Non-Copy, non-Clone; owns the allocation lifetime `'a`.
//!   Exposes `as_slice()` / `as_slice_mut()` to obtain a borrowed view, and also
//!   provides convenience `read*` / `write*` / `zero*` methods that delegate via
//!   those views. Passed by value to `realloc` and `dealloc`; Drop is a no-op.
//!
//! * [`BStackSlice`]`<'a>` — borrowed I/O view over a region.  Non-Copy;
//!   obtained from `BStackOwnedSlice::as_slice[_mut]()` or directly from
//!   `BStackSlice::from_raw_parts`.  Exposes `read`, `read_into`,
//!   `read_range_into`, `subslice`, `subslice_range`, `reader`, `reader_at`,
//!   and (with the `set` feature) `write`, `write_range`, `zero`, `zero_range`.
//!
//! * [`BStackSliceReader`]`<'a>` — cursor-based reader over a
//!   [`BStackSlice`], implementing [`io::Read`] and [`io::Seek`] in the
//!   slice's coordinate space.
//!
//! * [`LinearBStackAllocator`] — reference bump allocator that appends regions
//!   sequentially.  `realloc` is O(1) for the tail allocation and returns
//!   `Unsupported` for non-tail slices.  `dealloc` reclaims the tail via
//!   [`BStack::discard`] (or [`BStack::try_discard`] with `atomic`); non-tail
//!   deallocations are a no-op.  Every operation maps to exactly one [`BStack`]
//!   call and is crash-safe by inheritance.  `Send` in all configurations;
//!   also `Sync` with the `atomic` feature.  Implements [`BStackAllocator`]
//!   and [`BStackBulkAllocator`].
//!
//! * [`FirstFitBStackAllocator`] — A persistent first-fit free-list allocator
//!   that reuses freed regions to prevent unbounded file growth.  Requires both
//!   `alloc` and `set` features.  `Send` in all configurations; also `Sync`
//!   with the `atomic` feature, where an internal `Mutex` serializes free-list
//!   mutation and stack extension.
//!
//! * [`GhostTreeBstackAllocator`] — A pure-AVL general-purpose allocator with
//!   zero-overhead live allocations.  Free blocks store their AVL node inline,
//!   and the tree is keyed on `(size, address)` for best-fit allocation.
//!   Provides O(log n) allocation and deallocation with crash recovery through
//!   tree rebalancing on mount.  `Send` in all configurations; `Send + Sync`
//!   with the `atomic` feature, where an internal `Mutex` serialises AVL tree
//!   mutations.
//!
//! * [`SlabBStackAllocator`] — Fixed-block slab allocator.
//!   All blocks are exactly `block_size` bytes with no per-block header or footer;
//!   freed blocks are tracked via an intrusive singly-linked free list stored in
//!   the first 8 bytes of each free block.  O(1) alloc and dealloc.
//!   Use [`SlabBStackAllocator::new`] to initialise an empty stack and
//!   [`SlabBStackAllocator::open`] to reopen an existing one.
//!   Requires both `alloc` and `set` features.
//!
//! * [`CheckedSlabBStackAllocator`] — Crash-recoverable
//!   variant of [`SlabBStackAllocator`].  Prefixes every block with an 8-byte
//!   overhead field (zero when free, high bit set with a block count when in
//!   use) so leaked blocks are recoverable by a linear scan and double-frees
//!   are caught at runtime before the free list can be corrupted.  Constructor
//!   takes `data_size` (usable bytes per block, ≥ 8); the on-disk `block_size`
//!   is `data_size + 8`.  Use [`CheckedSlabBStackAllocator::new`] to initialise
//!   an empty stack and [`CheckedSlabBStackAllocator::open`] to reopen one
//!   ([`open`](CheckedSlabBStackAllocator::open) runs
//!   [`recover`](CheckedSlabBStackAllocator::recover) automatically).
//!   Requires both `alloc` and `set` features.
//!
//!
//! * [`BStackByteVec`]`<'a, A>` — a growable byte (`u8`) vector backed by a
//!   [`BStack`] allocation (requires `alloc` + `set`).  Mirrors the core
//!   [`Vec<u8>`] API: `new`, `with_capacity`, `from_slice`, `push`, `pop`,
//!   `get`, `read_bytes`, `as_slice`, `truncate`, `clear`, `reserve`,
//!   `resize`, and `iter`.
//!   The block stores a 16-byte header (`len`, `cap`) followed by the byte
//!   data; the header is re-read on every call for crash recoverability.
//!   `push` doubles capacity (minimum 4); `pop` decrements `len` then zeros
//!   the vacated slot; `truncate` writes `len` then zeros all removed slots.
//!
//! ## Lifetime model
//!
//! `BStackOwnedSlice<'a, A>` borrows the **allocator** for `'a`.
//! The borrow checker statically prevents calling
//! [`BStackAllocator::into_stack`] — which consumes the allocator by value —
//! while any owned slice is still in scope.  `BStackSlice<'a>` views obtained
//! via `as_slice[_mut]()` have a shorter lifetime tied to the borrow of the
//! owned slice, preventing them from outliving the handle that owns the region.
//!
//! ## Quick example
//!
//! ```skip
//! use bstack::{BStack, BStackAllocator, LinearBStackAllocator};
//!
//! # fn main() -> std::io::Result<()> {
//! let alloc = LinearBStackAllocator::new(BStack::open("data.bstack")?);
//!
//! let mut slice = alloc.alloc(128)?;      // reserve 128 zero bytes
//! let data = slice.read()?;    // read them back
//! alloc.dealloc(slice)?;                  // release (tail, so O(1))
//!
//! let stack = alloc.into_stack();         // reclaim the BStack
//! # Ok(())
//! # }
//! ```
//!
//! # Examples
//!
//! ```no_run
//! use bstack::BStack;
//!
//! # fn main() -> std::io::Result<()> {
//! let stack = BStack::open("log.bin")?;
//!
//! // push returns the logical byte offset where the payload starts.
//! let off0 = stack.push(b"hello")?;  // 0
//! let off1 = stack.push(b"world")?;  // 5
//!
//! assert_eq!(stack.len()?, 10);
//!
//! // peek reads from a logical offset to the end without removing anything.
//! assert_eq!(stack.peek(off1)?, b"world");
//!
//! // get reads an arbitrary half-open logical byte range.
//! assert_eq!(stack.get(3, 8)?, b"lowor");
//!
//! // pop removes bytes from the tail and returns them.
//! assert_eq!(stack.pop(5)?, b"world");
//! assert_eq!(stack.len()?, 5);
//! # Ok(())
//! # }
//! ```

// This crate-doc section is emitted only when the dev/test-only fault-injection
// machinery is actually compiled in (see the [`fault`] module).
#![cfg_attr(
    all(debug_assertions, feature = "fault-injection"),
    doc = "# Fault injection (`fault-injection` feature)",
    doc = "",
    doc = "This build has the dev/test-only `fault-injection` feature active, so",
    doc = "`BStack` I/O can be made to fail on demand. Implement [`FaultPolicy`] and arm",
    doc = "it with [`BStack::with_fault_policy`] (at construction) or",
    doc = "[`BStack::set_fault_policy`] (arm, re-arm, or disarm mid-test); every I/O",
    doc = "method then consults the policy once, **after** validating its arguments. This",
    doc = "exercises error-handling and rollback paths that a successful sequence of calls",
    doc = "can never reach. The whole mechanism is gated on `all(debug_assertions, feature",
    doc = "= \"fault-injection\")`, so a `--release` build carries none of it and its",
    doc = "performance is unaffected. See the [`fault`] module for details."
)]

mod io_core;
use io_core::*;

pub mod fault;
use fault::fault_point;
#[cfg(all(debug_assertions, feature = "fault-injection"))]
pub use fault::{FaultPolicy, FaultState};
#[cfg(all(test, feature = "alloc", feature = "set"))]
mod alloc_fuzz_tests;
mod test;

#[cfg(feature = "alloc")]
mod alloc;
#[cfg(feature = "alloc")]
pub use alloc::{
    BStackAllocError, BStackAllocator, BStackBulkAllocError, BStackBulkAllocator, BStackOwnedSlice,
    BStackOwnedSliceAllocator, BStackRange, BStackSlice, BStackSliceReader, BStackUninitAllocator,
    LinearBStackAllocator,
};
#[cfg(all(feature = "alloc", feature = "set"))]
pub use alloc::{
    BStackByteVec, BStackByteVecIter, BStackSliceWriter, CheckedSlabBStackAllocator,
    FirstFitBStackAllocator, GhostTreeBstackAllocator, SlabBStackAllocator,
};

#[cfg(all(feature = "guarded", feature = "atomic"))]
pub use alloc::{BStackAtomicGuardedSlice, BStackAtomicGuardedSliceSubview};
#[cfg(feature = "guarded")]
pub use alloc::{BStackGuardedSlice, BStackGuardedSliceSubview};

use std::fmt;
use std::fs::{File, OpenOptions};
use std::hash::{Hash, Hasher};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, RwLock};

#[cfg(unix)]
use std::os::unix::io::AsRawFd;
#[cfg(unix)]
use std::os::unix::io::RawFd;

#[cfg(windows)]
use std::os::windows::io::AsRawHandle;
#[cfg(windows)]
use windows_sys::Win32::Foundation::HANDLE;
#[cfg(windows)]
use windows_sys::Win32::Storage::FileSystem::{
    LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, ReadFile,
};
#[cfg(windows)]
use windows_sys::Win32::System::IO::OVERLAPPED;

/// On-disk **format** version encoded in the magic header. This is independent
/// of the crate version: it bumps only when the file format changes in a way an
/// older reader cannot handle. 0.4.0 introduces the 32-byte write-in-progress
/// journal header (see `algos/WIP.md`); bumping the minor here makes older binaries
/// reject the new files loudly instead of misreading them.
const FORMAT_MAJOR: u8 = 0;
const FORMAT_MINOR: u8 = 4;
const FORMAT_PATCH: u8 = 0;

/// Full magic for files written by this version
/// (`BSTK` + major + minor + patch + reserved(0)).
const MAGIC: [u8; 8] = [
    b'B',
    b'S',
    b'T',
    b'K',
    FORMAT_MAJOR,
    FORMAT_MINOR,
    FORMAT_PATCH,
    0,
];

/// Compatibility prefix checked on open: `BSTK` + format major + minor. A file
/// is accepted only when its first 6 bytes match — i.e. the same format
/// `major.minor`. The patch byte is informational and is not compared.
const MAGIC_PREFIX: [u8; 6] = [b'B', b'S', b'T', b'K', FORMAT_MAJOR, FORMAT_MINOR];

/// Magic prefix of the pre-0.4.0 (0.1.x) format that [`BStack::migrate`]
/// upgrades from: `BSTK` + major 0 + minor 1.
const LEGACY_MAGIC_PREFIX: [u8; 6] = [b'B', b'S', b'T', b'K', 0, 1];

/// Header size of the pre-0.4.0 (0.1.x) format: `magic[8] + committed_len[8]`.
const LEGACY_HEADER_SIZE: u64 = 16;

/// Compute `base + len`, mapping `u64` overflow to an `InvalidInput` error
/// carrying `msg`.
#[cfg(any(feature = "set", feature = "atomic"))]
pub(crate) fn checked_end(base: u64, len: u64, msg: &'static str) -> io::Result<u64> {
    base.checked_add(len)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, msg))
}

/// Reject an in-place write whose range `[offset, end)` starts inside the locked
/// prefix `[0, locked)`. `op` names the operation for the error message.
///
/// Shared by the single-range in-place mutators (`set`, `zero`, `swap`,
/// `swap_into`, `cas`); callers must load `locked` under the write lock so the
/// check cannot race a concurrent `lock_up_to`.
#[cfg(feature = "set")]
pub(crate) fn check_offset_unlocked(
    op: &str,
    offset: u64,
    end: u64,
    locked: u64,
) -> io::Result<()> {
    if offset < locked {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{op}: range [{offset}, {end}) overlaps locked region [0, {locked})"),
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------

/// A persistent, fsync-durable binary stack backed by a single file.
///
/// See the [crate-level documentation](crate) for the file format, durability
/// guarantees, crash recovery, multi-process safety, and thread-safety model.
pub struct BStack {
    /// The file handle together with a cached copy of the on-disk header's
    /// committed payload length (`clen`).
    ///
    /// `clen` (the `.1` field) is seeded from the validated header at
    /// construction time (after recovery) and kept in sync by every
    /// write-lock-held operation that commits a new `clen` to the header, via
    /// `write_committed_len`. [`BStack::len`] and [`BStack::is_empty`] read it
    /// under the same lock used for the on-disk state, so no extra
    /// synchronisation is needed.
    lock: RwLock<(File, u64)>,
    /// Monotonically growing partition boundary.  Bytes in `[0, locked)` are
    /// immutable and can be read without the rwlock on supported platforms.
    /// Not persisted — resets to 0 on every open.
    locked: AtomicU64,
    /// Copy of the raw file descriptor used for lock-free positional reads
    /// on the locked region.  The `File` inside `lock` retains ownership and
    /// will close the descriptor when `BStack` is dropped.
    #[cfg(unix)]
    fd: RawFd,
    /// Copy of the Windows HANDLE stored as `isize` so the field is
    /// `Send + Sync`.  Same lifetime guarantee as `fd` above.
    #[cfg(windows)]
    handle: isize,
    /// Whether in-memory caching of the locked region is enabled.
    /// Set once at construction; never mutated afterwards.
    cache_enabled: bool,
    /// In-memory mirror of `[0, locked)`.  Empty until the first `lock_up_to`
    /// call on a cached stack.  Capacity follows a power-of-two growth rule;
    /// `self.locked` is the count of valid bytes within the buffer.
    cache: Mutex<Vec<u8>>,
    /// Deterministic I/O-fault injection state, consulted at the API boundary of
    /// every instrumented method (see the [`fault`] module). Present only in
    /// builds with `debug_assertions` on and the `fault-injection` feature
    /// enabled; release builds carry neither the field nor its per-call branch.
    #[cfg(all(debug_assertions, feature = "fault-injection"))]
    fault: fault::FaultState,
}

// `BStack` is auto-`Send + Sync` on every platform: all fields
// (`RwLock<File>`, `AtomicU64`, and the `RawFd` / `isize` handle) already
// implement both traits.  The lock-free `pread` / `ReadFile`+`OVERLAPPED`
// paths are cursor-independent and safe to call from any thread, and the raw
// fd / handle remains valid for as long as `BStack` owns the `File`.

impl BStack {
    /// Write the 32-byte header into a brand-new (empty) file.
    fn init_header(file: &mut File) -> io::Result<()> {
        file.seek(SeekFrom::Start(0))?;
        file.write_all(&MAGIC)?;
        // committed_len[8] + wip_ptr[8] + wip_aux[8], all zero on a fresh file.
        file.write_all(&[0u8; (HEADER_SIZE - 8) as usize])
    }

    /// Read and validate the 32-byte header; return `(committed_len, wip_ptr,
    /// wip_aux)`.
    fn read_header(file: &mut File) -> io::Result<(u64, u64, u64)> {
        file.seek(SeekFrom::Start(0))?;
        let mut hdr = [0u8; HEADER_SIZE as usize];
        file.read_exact(&mut hdr)?;
        if hdr[0..6] != MAGIC_PREFIX {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "bstack: bad magic number — not a bstack file or incompatible version",
            ));
        }
        let committed_len = u64::from_le_bytes(hdr[8..16].try_into().unwrap());
        let wip_ptr = u64::from_le_bytes(hdr[16..24].try_into().unwrap());
        let wip_aux = u64::from_le_bytes(hdr[24..32].try_into().unwrap());
        Ok((committed_len, wip_ptr, wip_aux))
    }

    /// Open or create a stack file at `path`.
    ///
    /// On a **new** file the 32-byte header is written and durably synced
    /// before returning.
    ///
    /// On an **existing** file the header is validated and, if a previous crash
    /// left the file in an inconsistent state, the file is repaired and durably
    /// synced before returning (see *Crash recovery* in the crate docs).
    ///
    /// On Unix an **exclusive advisory `flock`** is acquired; if another
    /// process already holds the lock this function returns immediately with
    /// [`io::ErrorKind::WouldBlock`].
    ///
    /// # Errors
    ///
    /// * [`io::ErrorKind::WouldBlock`] — another process holds the exclusive
    ///   lock (Unix only).
    /// * [`io::ErrorKind::InvalidData`] — the file exists but its header magic
    ///   is wrong (not a bstack file, or created by an incompatible version),
    ///   or the file is too short to contain a valid header.
    /// * Any [`io::Error`] from [`OpenOptions::open`], `read`, `write`, or
    ///   `durable_sync`.
    pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(path)?;

        #[cfg(unix)]
        flock_exclusive(&file)?;

        #[cfg(windows)]
        lock_file_exclusive(&file)?;

        let raw_size = file.metadata()?.len();

        let mut clen = 0u64;
        if raw_size == 0 {
            Self::init_header(&mut file)?;
            durable_sync(&file)?;
        } else if raw_size < HEADER_SIZE {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "bstack: file is {raw_size} bytes — too small to contain the {HEADER_SIZE}-byte header"
                ),
            ));
        } else {
            let (committed_len, wip_ptr, wip_aux) = Self::read_header(&mut file)?;
            clen = committed_len;
            if wip_ptr != 0 {
                // An in-place write was in flight. Replay or roll it back, then
                // restore the at-rest invariant. A splice changes the committed
                // length, so adopt whatever recovery commits.
                clen = recover_wip(&mut file, committed_len, wip_ptr, wip_aux, raw_size)?;
            } else if wip_aux == u64::from(WipAux::MultiWrite) {
                // A multi-write batch was in flight (armed with `wip_ptr == 0`
                // and the intent-complete sentinel). All blocks were fully
                // staged before the arm, so replay the sequence and disarm. The
                // committed length is unchanged.
                clen = recover_multi_write(&mut file, committed_len, raw_size)?;
            } else {
                // No journal armed: reconcile the committed length against the
                // file size, using whichever is smaller (the committed value is
                // the last successfully synced boundary). This drops a stale tail
                // from a crashed push/extend or a crashed journal stage.
                let actual_data_len = raw_size - HEADER_SIZE;
                if actual_data_len != committed_len {
                    let correct_len = committed_len.min(actual_data_len);
                    file.set_len(HEADER_SIZE + correct_len)?;
                    write_committed_len(&mut file, &mut clen, correct_len)?;
                    durable_sync(&file)?;
                }
            }
        }

        #[cfg(unix)]
        let fd = file.as_raw_fd();
        #[cfg(windows)]
        let handle = file.as_raw_handle() as isize;

        Ok(BStack {
            #[cfg(unix)]
            fd,
            #[cfg(windows)]
            handle,
            lock: RwLock::new((file, clen)),
            locked: AtomicU64::new(0),
            cache_enabled: false,
            cache: Mutex::new(Vec::new()),
            #[cfg(all(debug_assertions, feature = "fault-injection"))]
            fault: fault::FaultState::new(),
        })
    }

    /// Upgrade a legacy pre-0.4.0 (0.1.x, 16-byte header) file at `path` to the
    /// current 0.4.0 layout (32-byte header), in place.
    ///
    /// The file is rewritten into a sibling `"<path>.migrating"` — a fresh 0.4.0
    /// header followed by the old payload shifted from offset 16 to offset 32 —
    /// which is then atomically renamed onto the original (a crash leaves either
    /// the intact original or the finished new file, never neither). The
    /// committed length is preserved (clamped to the bytes actually present,
    /// mirroring [`open`](BStack::open)'s recovery).
    ///
    /// The caller must not hold the file open elsewhere. On success `path` is a
    /// valid 0.4.0 file ready for [`open`](BStack::open).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidData`] if `path` is not a legacy 0.1.x
    /// file (wrong magic, or shorter than the 16-byte legacy header), and
    /// propagates any I/O error from reading, writing, syncing, removing, or
    /// renaming.
    pub fn migrate(path: impl AsRef<Path>) -> io::Result<()> {
        let path = path.as_ref();

        // Read and validate the legacy 16-byte header.
        let mut old = OpenOptions::new().read(true).open(path)?;
        let old_size = old.metadata()?.len();
        if old_size < LEGACY_HEADER_SIZE {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "bstack: file is {old_size} bytes — too small to be a legacy {LEGACY_HEADER_SIZE}-byte-header file"
                ),
            ));
        }
        let mut hdr = [0u8; LEGACY_HEADER_SIZE as usize];
        old.read_exact(&mut hdr)?;
        if hdr[0..6] != LEGACY_MAGIC_PREFIX {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "bstack: not a legacy 0.1.x file — nothing to migrate",
            ));
        }
        // Committed length, clamped to the payload actually present.
        let clen =
            u64::from_le_bytes(hdr[8..16].try_into().unwrap()).min(old_size - LEGACY_HEADER_SIZE);

        // Sibling path "<path>.migrating", in the same directory so the final
        // rename stays within one filesystem.
        let mut tmp = path.as_os_str().to_owned();
        tmp.push(".migrating");
        let tmp = PathBuf::from(tmp);

        // Write the new file: 32-byte 0.4.0 header, then the old payload shifted
        // from offset 16 to offset 32.
        {
            let mut new = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&tmp)?;
            new.write_all(&MAGIC)?; // magic[8]
            new.write_all(&clen.to_le_bytes())?; // committed_len[8]
            new.write_all(&[0u8; 16])?; // wip_ptr[8] | wip_aux[8] = 0
            old.seek(SeekFrom::Start(LEGACY_HEADER_SIZE))?;
            let mut src = (&mut old).take(clen);
            let copied = io::copy(&mut src, &mut new)?;
            if copied != clen {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "bstack: legacy payload shorter than committed length during migration",
                ));
            }
            new.sync_all()?;
        }
        drop(old);

        // Atomically swap the sibling in for the original. `rename` replaces the
        // destination in a single step on both Unix (`rename(2)`) and Windows
        // (`MoveFileExW` with `MOVEFILE_REPLACE_EXISTING`), so a crash leaves
        // either the intact original or the completed 0.4.0 file at `path` —
        // never neither. (Removing the original first would open a window where
        // a crash leaves only the sibling.)
        std::fs::rename(&tmp, path)?;
        Ok(())
    }

    /// Append `data` to the end of the file.
    ///
    /// Returns the **logical** byte offset at which `data` begins — i.e. the
    /// payload size immediately before the write.  An empty slice is valid; it
    /// writes nothing and returns the current end offset.
    ///
    /// # Atomicity
    ///
    /// Either the full payload is written, the header committed-length is
    /// updated, and the whole thing is durably synced, or the file is
    /// left unchanged (best-effort rollback via `ftruncate` + header reset).
    ///
    /// # Errors
    ///
    /// Returns any [`io::Error`] from `write_all`, `durable_sync`, or the
    /// fallback `set_len`.
    pub fn push(&self, data: impl AsRef<[u8]>) -> io::Result<u64> {
        let data = data.as_ref();
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let logical_offset = file_end - HEADER_SIZE;

        if data.is_empty() {
            return Ok(logical_offset);
        }

        fault_point!(self, "push");
        if let Err(e) = file.write_all(data) {
            let _ = file.set_len(file_end);
            return Err(e);
        }

        let new_len = logical_offset + data.len() as u64;
        commit_grow(file, clen, new_len, logical_offset, file_end)?;
        Ok(logical_offset)
    }

    /// Append `n` zero bytes to the end of the file.
    ///
    /// Returns the **logical** byte offset at which the zeros begin — i.e. the
    /// payload size immediately before the write.  `n = 0` is valid; it writes
    /// nothing and returns the current end offset.
    ///
    /// # Atomicity
    ///
    /// Either the file is extended, the header committed-length is updated,
    /// and the whole thing is durably synced, or the file is left unchanged
    /// (best-effort rollback via `ftruncate` + header reset).
    ///
    /// # Errors
    ///
    /// Returns any [`io::Error`] from `set_len`, `durable_sync`, or the
    /// fallback `set_len`.
    pub fn extend(&self, n: u64) -> io::Result<u64> {
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let logical_offset = file_end - HEADER_SIZE;

        if n == 0 {
            return Ok(logical_offset);
        }

        fault_point!(self, "extend");
        let new_file_end = file_end + n;
        file.set_len(new_file_end)?;

        let new_len = logical_offset + n;
        commit_grow(file, clen, new_len, logical_offset, file_end)?;
        Ok(logical_offset)
    }

    /// Remove and return the last `n` bytes of the file.
    ///
    /// `n = 0` is valid: no bytes are removed and an empty `Vec` is returned.
    /// `n` may span across multiple previous [`push`](Self::push) boundaries.
    ///
    /// # Atomicity
    ///
    /// The bytes are read before the file is truncated.  The committed-length
    /// in the header is updated and durably synced after the truncation.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Also propagates any I/O error from `read_exact`,
    /// `set_len`, `write_all`, or `durable_sync`.
    pub fn pop(&self, n: u64) -> io::Result<Vec<u8>> {
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let raw_size = file.seek(SeekFrom::End(0))?;
        let data_size = raw_size - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("pop({n}) exceeds payload size ({data_size})"),
            ));
        }
        let new_data_len = data_size - n;
        let locked = self.locked.load(Ordering::Acquire);
        if new_data_len < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("pop({n}) would shrink payload below locked length ({locked})"),
            ));
        }
        let mut buf = vec![0u8; n as usize];
        fault_point!(self, "pop");
        read_at(file, new_data_len, &mut buf)?;
        commit_shrink(file, clen, new_data_len)?;
        Ok(buf)
    }

    /// Return a copy of every payload byte from `offset` to the end of the
    /// file.
    ///
    /// `offset` is a **logical** offset (as returned by [`push`](Self::push)).
    /// `offset == len()` is valid and returns an empty `Vec`.  The file is not
    /// modified.
    ///
    /// # Concurrency
    ///
    /// On Unix and Windows this uses a cursor-safe positional read (`pread(2)`
    /// on Unix; `ReadFile`+`OVERLAPPED` on Windows), so the method takes only
    /// the **read lock**, allowing multiple concurrent `peek` and `get` calls
    /// to run in parallel.
    ///
    /// On other platforms a seek is required; the method falls back to the
    /// write lock and concurrent reads serialise.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset` exceeds the current
    /// payload size.
    pub fn peek(&self, offset: u64) -> io::Result<Vec<u8>> {
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            if offset > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("peek offset ({offset}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "peek");
            pread_exact(file, HEADER_SIZE + offset, (data_size - offset) as usize)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let raw_size = file.seek(SeekFrom::End(0))?;
            let data_size = raw_size.saturating_sub(HEADER_SIZE);
            if offset > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("peek offset ({offset}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "peek");
            file.seek(SeekFrom::Start(HEADER_SIZE + offset))?;
            let mut buf = vec![0u8; (data_size - offset) as usize];
            file.read_exact(&mut buf)?;
            Ok(buf)
        }
    }

    /// Return a copy of the bytes in the half-open logical range `[start, end)`.
    ///
    /// `start == end` is valid and returns an empty `Vec`.  The file is not
    /// modified.
    ///
    /// # Concurrency
    ///
    /// Same as [`peek`](Self::peek): on Unix and Windows the read lock is
    /// taken and concurrent `get`/`peek`/`len` calls may run in parallel.  On
    /// other platforms the write lock is taken and reads serialise.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `end < start` or if `end`
    /// exceeds the current payload size.
    pub fn get(&self, start: u64, end: u64) -> io::Result<Vec<u8>> {
        if end < start {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("get: end ({end}) < start ({start})"),
            ));
        }
        // Fast-path: if the range lies entirely within the locked region,
        // serve from the in-memory cache (if enabled) or fall back to a
        // lock-free pread — locked bytes are immutable so no rwlock needed.
        #[cfg(any(unix, windows))]
        {
            let locked = self.locked.load(Ordering::Acquire);
            if end <= locked {
                if self.cache_enabled {
                    let len = (end - start) as usize;
                    let mut buf = vec![0u8; len];
                    let cache = self.cache.lock().unwrap();
                    buf.copy_from_slice(&cache[start as usize..end as usize]);
                    return Ok(buf);
                }
                #[cfg(unix)]
                {
                    let mut buf = vec![0u8; (end - start) as usize];
                    pread_exact_raw(self.fd, HEADER_SIZE + start, &mut buf)?;
                    return Ok(buf);
                }
                #[cfg(windows)]
                {
                    let mut buf = vec![0u8; (end - start) as usize];
                    pread_exact_raw_handle(self.handle, HEADER_SIZE + start, &mut buf)?;
                    return Ok(buf);
                }
            }
        }
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("get: end ({end}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "get");
            pread_exact(file, HEADER_SIZE + start, (end - start) as usize)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let locked = self.locked.load(Ordering::Acquire);
            if end <= locked && self.cache_enabled {
                let cache = self.cache.lock().unwrap();
                return Ok(cache[start as usize..end as usize].to_vec());
            }
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let raw_size = file.seek(SeekFrom::End(0))?;
            let data_size = raw_size.saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("get: end ({end}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "get");
            file.seek(SeekFrom::Start(HEADER_SIZE + start))?;
            let mut buf = vec![0u8; (end - start) as usize];
            file.read_exact(&mut buf)?;
            Ok(buf)
        }
    }

    /// Fill `buf` with bytes from logical `offset` to `offset + buf.len()`.
    ///
    /// Reads exactly `buf.len()` bytes from `offset` into the caller-supplied
    /// buffer.  An empty buffer is a valid no-op.  The file is not modified.
    ///
    /// Use this instead of [`peek`](Self::peek) when the destination buffer is
    /// already allocated and you want to avoid the extra heap allocation.
    ///
    /// # Concurrency
    ///
    /// Same as [`peek`](Self::peek): on Unix and Windows only the read lock is
    /// taken; on other platforms the write lock serialises all reads.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + buf.len()` overflows
    /// `u64` or exceeds the current payload size.
    pub fn peek_into(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        let len = buf.len() as u64;
        let end = offset.checked_add(len).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "peek_into: offset + len overflows u64",
            )
        })?;
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "peek_into: range [{offset}, {end}) exceeds payload size ({data_size})"
                    ),
                ));
            }
            fault_point!(self, "peek_into");
            pread_exact_into(file, HEADER_SIZE + offset, buf)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "peek_into: range [{offset}, {end}) exceeds payload size ({data_size})"
                    ),
                ));
            }
            fault_point!(self, "peek_into");
            file.seek(SeekFrom::Start(HEADER_SIZE + offset))?;
            file.read_exact(buf)
        }
    }

    /// Fill `buf` with bytes from the half-open logical range
    /// `[start, start + buf.len())`.
    ///
    /// An empty buffer is a valid no-op.  The file is not modified.
    ///
    /// Use this instead of [`get`](Self::get) when the destination buffer is
    /// already allocated and you want to avoid the extra heap allocation.
    ///
    /// # Concurrency
    ///
    /// Same as [`get`](Self::get): on Unix and Windows only the read lock is
    /// taken; on other platforms the write lock serialises all reads.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `start + buf.len()` overflows
    /// `u64` or exceeds the current payload size.
    pub fn get_into(&self, start: u64, buf: &mut [u8]) -> io::Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        let len = buf.len() as u64;
        let end = start.checked_add(len).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "get_into: start + len overflows u64",
            )
        })?;
        // Fast-path: locked region is immutable — serve from cache or pread.
        #[cfg(any(unix, windows))]
        {
            let locked = self.locked.load(Ordering::Acquire);
            if end <= locked {
                if self.cache_enabled {
                    let cache = self.cache.lock().unwrap();
                    buf.copy_from_slice(&cache[start as usize..end as usize]);
                    return Ok(());
                }
                #[cfg(unix)]
                return pread_exact_raw(self.fd, HEADER_SIZE + start, buf);
                #[cfg(windows)]
                return pread_exact_raw_handle(self.handle, HEADER_SIZE + start, buf);
            }
        }
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("get_into: end ({end}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "get_into");
            pread_exact_into(file, HEADER_SIZE + start, buf)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let locked = self.locked.load(Ordering::Acquire);
            if end <= locked && self.cache_enabled {
                let cache = self.cache.lock().unwrap();
                buf.copy_from_slice(&cache[start as usize..end as usize]);
                return Ok(());
            }
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("get_into: end ({end}) exceeds payload size ({data_size})"),
                ));
            }
            fault_point!(self, "get_into");
            file.seek(SeekFrom::Start(HEADER_SIZE + start))?;
            file.read_exact(buf)
        }
    }

    /// Remove the last `buf.len()` bytes from the file and write them into `buf`.
    ///
    /// An empty buffer is a valid no-op: no bytes are removed.
    ///
    /// Use this instead of [`pop`](Self::pop) when the destination buffer is
    /// already allocated and you want to avoid the extra heap allocation.
    ///
    /// # Atomicity
    ///
    /// Same guarantees as [`pop`](Self::pop).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `buf.len()` exceeds the
    /// current payload size.  Also propagates any I/O error from `read_exact`,
    /// `set_len`, `write_all`, or `durable_sync`.
    pub fn pop_into(&self, buf: &mut [u8]) -> io::Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        let n = buf.len() as u64;
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let raw_size = file.seek(SeekFrom::End(0))?;
        let data_size = raw_size - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("pop_into({n}) exceeds payload size ({data_size})"),
            ));
        }
        let new_data_len = data_size - n;
        let locked = self.locked.load(Ordering::Acquire);
        if new_data_len < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("pop_into({n}) would shrink payload below locked length ({locked})"),
            ));
        }
        fault_point!(self, "pop_into");
        read_at(file, new_data_len, buf)?;
        commit_shrink(file, clen, new_data_len)?;
        Ok(())
    }

    /// Remove (discard) the last `n` bytes from the file without returning them.
    ///
    /// Equivalent to [`pop`](Self::pop) but avoids allocating a buffer for the
    /// removed bytes.  `n = 0` is valid and is a no-op.
    ///
    /// # Atomicity
    ///
    /// Same guarantees as [`pop`](Self::pop).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Also propagates any I/O error from `set_len`,
    /// `write_all`, or `durable_sync`.
    pub fn discard(&self, n: u64) -> io::Result<()> {
        if n == 0 {
            return Ok(());
        }
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let raw_size = file.seek(SeekFrom::End(0))?;
        let data_size = raw_size - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("discard({n}) exceeds payload size ({data_size})"),
            ));
        }
        let new_data_len = data_size - n;
        let locked = self.locked.load(Ordering::Acquire);
        if new_data_len < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("discard({n}) would shrink payload below locked length ({locked})"),
            ));
        }
        fault_point!(self, "discard");
        commit_shrink(file, clen, new_data_len)?;
        Ok(())
    }

    /// Overwrite `data` bytes in place starting at logical `offset`.
    ///
    /// The file size is never changed: if `offset + data.len()` would exceed
    /// the current payload size the call is rejected.  An empty slice is a
    /// valid no-op.
    ///
    /// # Feature flag
    ///
    /// Only available when the `set` Cargo feature is enabled.
    ///
    /// # Durability & atomicity
    ///
    /// Crash-atomic: after a crash the slice holds either its old contents or the
    /// full new `data`, never a partial mix. A write confined to a single aligned
    /// storage block is committed with one durably-synced write; a larger write
    /// goes through the write-in-progress journal (stage → arm → commit → disarm),
    /// which recovery replays or rolls back on the next [`open`](Self::open). The
    /// overwritten bytes are durably synced before the call returns.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + data.len()`
    /// exceeds the current payload size, or if the addition overflows `u64`.
    /// Propagates any I/O error from `write_all`, `set_len`, or `durable_sync`.
    #[cfg(feature = "set")]
    pub fn set(&self, offset: u64, data: impl AsRef<[u8]>) -> io::Result<()> {
        let data = data.as_ref();
        if data.is_empty() {
            return Ok(());
        }
        let end = checked_end(offset, data.len() as u64, "set: offset + len overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock — otherwise a concurrent
        // `lock_up_to` could extend the locked region between our check and
        // our write, letting us mutate a now-immutable byte.
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("set", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("set: write end ({end}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "set");
        set_in_place(file, data_size, offset, data)
    }

    /// Overwrite `n` bytes with zeros in place starting at logical `offset`.
    ///
    /// The file size is never changed: if `offset + n` would exceed
    /// the current payload size the call is rejected.  `n = 0` is a
    /// valid no-op.
    ///
    /// # Feature flag
    ///
    /// Only available when the `set` Cargo feature is enabled.
    ///
    /// # Durability & atomicity
    ///
    /// Crash-atomic on the same terms as [`set`](Self::set): the zeroed slice
    /// survives a crash as either its old contents or all-zeros, never a mix.
    /// Small writes take the single-block atomic path; larger ones go through the
    /// write-in-progress journal. The overwritten bytes are durably synced before
    /// the call returns.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + n`
    /// exceeds the current payload size, or if the addition overflows `u64`.
    /// Propagates any I/O error from `write_all`, `set_len`, or `durable_sync`.
    #[cfg(feature = "set")]
    pub fn zero(&self, offset: u64, n: u64) -> io::Result<()> {
        if n == 0 {
            return Ok(());
        }
        let end = checked_end(offset, n, "zero: offset + n overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("zero", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("zero: write end ({end}) exceeds payload size ({data_size})"),
            ));
        }
        // Zeroing is a repeat-fill of the single-byte pattern `[0x00]` `n` times:
        // the journal stages a fixed 9-byte `[k | s]` tail instead of `n` bytes.
        fault_point!(self, "zero");
        repeat_fill(file, data_size, offset, &[0u8], n)
    }

    /// Fill `count` copies of `pattern` in place starting at logical `offset` —
    /// i.e. overwrite `[offset, offset + count * pattern.len())` with the pattern
    /// repeated back to back.
    ///
    /// The file size is never changed: if the filled region would exceed the
    /// current payload size the call is rejected. An empty `pattern` or
    /// `count == 0` is a valid no-op.
    ///
    /// This is the general form of [`zero`](Self::zero) (which is `repeat` of the
    /// single byte `0x00`). Because only the pattern and count are journaled, a
    /// crash-safe fill of a large region costs a fixed-size journal rather than
    /// one proportional to the region — cheap for e.g. clearing or stamping a
    /// large area with a small repeating value.
    ///
    /// # Feature flag
    ///
    /// Only available when the `set` Cargo feature is enabled.
    ///
    /// # Durability & atomicity
    ///
    /// Crash-atomic on the same terms as [`set`](Self::set): after a crash the
    /// region holds either its old contents or the fully repeated pattern, never a
    /// mix. A fill confined to one aligned block takes the single-block atomic
    /// path; a larger one goes through the write-in-progress journal, which stages
    /// only `[count | pattern]` and replays it on the next [`open`](Self::open).
    /// The written bytes are durably synced before the call returns.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `count * pattern.len()` or
    /// `offset + count * pattern.len()` overflows `u64`, or if the filled region
    /// exceeds the current payload size. Propagates any I/O error from `write_all`,
    /// `set_len`, or `durable_sync`.
    #[cfg(feature = "set")]
    pub fn repeat(&self, offset: u64, pattern: impl AsRef<[u8]>, count: u64) -> io::Result<()> {
        let pattern = pattern.as_ref();
        if pattern.is_empty() || count == 0 {
            return Ok(());
        }
        let total = (pattern.len() as u64).checked_mul(count).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "repeat: count * pattern.len() overflows u64",
            )
        })?;
        let end = checked_end(
            offset,
            total,
            "repeat: offset + count*pattern.len() overflows u64",
        )?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("repeat", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("repeat: write end ({end}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "repeat");
        repeat_fill(file, data_size, offset, pattern, count)
    }
}

// ---------------------------------------------------------------------------
// Atomic compound operations

#[cfg(feature = "atomic")]
impl BStack {
    /// Cut `n` bytes off the tail then append `buf` as a single atomic operation.
    ///
    /// **Crash-atomic:** after a crash the tail holds either its old contents or
    /// the full replacement, never a mix. The commit dispatches on the shape of
    /// the replacement (see *Durability* in the crate docs and `algos/WIP.md`):
    ///
    /// * **Pure truncation** (`buf` empty): drop the tail and commit the smaller
    ///   `clen` — the truncation is the commit point.
    /// * **Pure append** (`n == 0`): the bytes land beyond the committed end,
    ///   uncommitted until the `clen` write, so a crash rolls back by truncation.
    /// * **Same length** (`buf.len() == n`): overwrite in place via the `Set`
    ///   write-in-progress journal (or a single-block atomic write).
    /// * **Length change** (`buf.len() != n`, both non-zero): the **splice
    ///   journal** (`SpliceGrow`/`SpliceShrink`) — stage the new tail past the
    ///   live payload, arm the direction, replay it into place, then commit the
    ///   new `clen` and disarm in one atomic header write. Recovery derives the
    ///   new length from the file size and rolls a crash forward, or rolls back
    ///   if the arm never landed.
    ///
    /// `n = 0` with an empty `buf` is a valid no-op.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Propagates any I/O error from `set_len`, `write_all`,
    /// or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn atrunc(&self, n: u64, buf: impl AsRef<[u8]>) -> io::Result<()> {
        let buf = buf.as_ref();
        let buf_len = buf.len() as u64;
        if n == 0 && buf_len == 0 {
            return Ok(());
        }
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("atrunc: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        let locked = self.locked.load(Ordering::Acquire);
        let new_tail_start = data_size - n;
        if new_tail_start < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("atrunc: operation would modify locked region [0, {locked})"),
            ));
        }
        fault_point!(self, "atrunc");
        commit_tail_replace(file, clen, new_tail_start, n, buf, file_end)
    }

    /// Pop `n` bytes off the tail then append `buf`, returning the removed bytes.
    ///
    /// The bytes are read before any mutation, so they are always available in
    /// the returned `Vec` even if the subsequent write fails.  The replacement
    /// commits with the same crash-atomic, shape-dispatched strategy as
    /// [`atrunc`](Self::atrunc).
    ///
    /// `n = 0` with an empty `buf` is a valid no-op and returns an empty `Vec`.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Propagates any I/O error from `read_exact`, `set_len`,
    /// `write_all`, or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn splice(&self, n: u64, buf: impl AsRef<[u8]>) -> io::Result<Vec<u8>> {
        let buf = buf.as_ref();
        let buf_len = buf.len() as u64;
        if n == 0 && buf_len == 0 {
            return Ok(Vec::new());
        }
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("splice: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        let locked = self.locked.load(Ordering::Acquire);
        let new_tail_start = data_size - n;
        if new_tail_start < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("splice: operation would modify locked region [0, {locked})"),
            ));
        }
        fault_point!(self, "splice");
        // Read the bytes to remove before any mutation.
        let mut removed = vec![0u8; n as usize];
        read_at(file, new_tail_start, &mut removed)?;

        commit_tail_replace(file, clen, new_tail_start, n, buf, file_end)?;
        Ok(removed)
    }

    /// Pop `old.len()` bytes off the tail into `old`, then append `new`.
    ///
    /// Buffer-reuse counterpart of [`splice`](Self::splice): avoids allocating
    /// a `Vec` for the removed bytes by writing them into the caller-supplied
    /// `old` slice.  The replacement commits with the same crash-atomic,
    /// shape-dispatched strategy as [`atrunc`](Self::atrunc).
    ///
    /// An empty `old` with an empty `new` is a valid no-op.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `old.len()` exceeds the
    /// current payload size.  Propagates any I/O error from `read_exact`,
    /// `set_len`, `write_all`, or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn splice_into(&self, old: &mut [u8], new: impl AsRef<[u8]>) -> io::Result<()> {
        let new = new.as_ref();
        let n = old.len() as u64;
        let new_len = new.len() as u64;
        if n == 0 && new_len == 0 {
            return Ok(());
        }
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("splice_into: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        let locked = self.locked.load(Ordering::Acquire);
        let new_tail_start = data_size - n;
        if new_tail_start < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("splice_into: operation would modify locked region [0, {locked})"),
            ));
        }
        fault_point!(self, "splice_into");
        // Read the bytes to remove before any mutation.
        read_at(file, new_tail_start, old)?;

        commit_tail_replace(file, clen, new_tail_start, n, new, file_end)
    }

    /// Append `buf` only if the current logical payload size equals `s`.
    ///
    /// Returns `Ok(true)` if the size matched and `buf` was appended (or `buf`
    /// is empty and no I/O was needed).  Returns `Ok(false)` without modifying
    /// the file if the size does not match.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Propagates any I/O error from `write_all`, `write_committed_len`, or
    /// `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn try_extend(&self, s: u64, buf: impl AsRef<[u8]>) -> io::Result<bool> {
        let buf = buf.as_ref();
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if data_size != s {
            return Ok(false);
        }
        if buf.is_empty() {
            return Ok(true);
        }
        fault_point!(self, "try_extend");
        if let Err(e) = file.write_all(buf) {
            let _ = file.set_len(file_end);
            return Err(e);
        }
        let new_len = data_size + buf.len() as u64;
        commit_grow(file, clen, new_len, data_size, file_end)?;
        Ok(true)
    }

    /// Append `n` zero bytes only if the current logical payload size equals `s`.
    ///
    /// Returns `Ok(true)` if the size matched and `n` zero bytes were appended
    /// (or `n = 0` and no I/O was needed).  Returns `Ok(false)` without
    /// modifying the file if the size does not match.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if adding `n` to the current
    /// payload size would overflow `u64`.  Propagates any I/O error from
    /// `set_len`, `write_committed_len`, or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn try_extend_zeros(&self, s: u64, n: u64) -> io::Result<bool> {
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if data_size != s {
            return Ok(false);
        }
        if n == 0 {
            return Ok(true);
        }
        let new_len = checked_end(
            data_size,
            n,
            "try_extend_zeros: data_size + n overflows u64",
        )?;
        fault_point!(self, "try_extend_zeros");
        file.set_len(HEADER_SIZE + new_len)?;
        commit_grow(file, clen, new_len, data_size, file_end)?;
        Ok(true)
    }

    /// Discard `n` bytes only if the current logical payload size equals `s`.
    ///
    /// Returns `Ok(true)` if the size matched and `n` bytes were removed (or
    /// `n = 0` and the size check passed without I/O).  Returns `Ok(false)`
    /// without modifying the file if the size does not match.
    ///
    /// When `n = 0` only the read lock is taken (no file mutation occurs).
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Propagates any I/O error from `set_len`,
    /// `write_committed_len`, or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn try_discard(&self, s: u64, n: u64) -> io::Result<bool> {
        if n == 0 {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            return Ok(data_size == s);
        }
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let raw_size = file.seek(SeekFrom::End(0))?;
        let data_size = raw_size - HEADER_SIZE;
        if data_size != s {
            return Ok(false);
        }
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("try_discard: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        let new_data_len = data_size - n;
        let locked = self.locked.load(Ordering::Acquire);
        if new_data_len < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("try_discard: would shrink payload below locked length ({locked})"),
            ));
        }
        fault_point!(self, "try_discard");
        commit_shrink(file, clen, new_data_len)?;
        Ok(true)
    }

    /// Read multiple logical ranges in a single lock acquisition.
    ///
    /// Takes any iterator whose items are [`Range<u64>`](std::ops::Range) and
    /// returns a [`Vec`] of owned byte buffers, one per input range, in the
    /// same order.  An empty iterator returns an empty `Vec`.  An empty range
    /// (`start == end`) produces an empty inner `Vec`.
    ///
    /// All reads happen under the same shared lock, so no write can interleave
    /// between them.  On Unix and Windows the shared read lock is taken once
    /// for all non-locked ranges; on other platforms the write lock serialises
    /// all reads.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if any range has `end < start`
    /// or if any `end` exceeds the current payload size.
    #[cfg(feature = "atomic")]
    pub fn get_batched<I>(&self, ranges: I) -> io::Result<Vec<Vec<u8>>>
    where
        I: IntoIterator<Item = std::ops::Range<u64>>,
    {
        let ranges: Vec<std::ops::Range<u64>> = ranges.into_iter().collect();
        if ranges.is_empty() {
            return Ok(Vec::new());
        }
        for r in &ranges {
            if r.end < r.start {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("get_batched: end ({}) < start ({})", r.end, r.start),
                ));
            }
        }
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched");
            let mut results = Vec::with_capacity(ranges.len());
            for r in &ranges {
                if r.end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!(
                            "get_batched: end ({}) exceeds payload size ({data_size})",
                            r.end
                        ),
                    ));
                }
                results.push(pread_exact(
                    file,
                    HEADER_SIZE + r.start,
                    (r.end - r.start) as usize,
                )?);
            }
            Ok(results)
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched");
            let mut results = Vec::with_capacity(ranges.len());
            for r in &ranges {
                if r.end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!(
                            "get_batched: end ({}) exceeds payload size ({data_size})",
                            r.end
                        ),
                    ));
                }
                file.seek(SeekFrom::Start(HEADER_SIZE + r.start))?;
                let mut buf = vec![0u8; (r.end - r.start) as usize];
                file.read_exact(&mut buf)?;
                results.push(buf);
            }
            Ok(results)
        }
    }

    /// Read multiple logical ranges into caller-provided buffers in a single lock acquisition.
    ///
    /// Takes any iterator whose items are `(u64, &mut [u8])` — a start offset
    /// and a mutable buffer to fill.  The number of bytes read for each entry
    /// equals `buf.len()`.  An empty iterator returns immediately.
    ///
    /// All reads happen under the same shared lock, so no write can interleave
    /// between them.  On Unix and Windows the shared read lock is taken once
    /// for all reads; on other platforms the write lock serialises all reads.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if any `offset + buf.len()`
    /// overflows `u64` or if any read would extend beyond the current payload
    /// size.
    #[cfg(feature = "atomic")]
    pub fn get_batched_into<'a, I>(&self, bufs: I) -> io::Result<()>
    where
        I: IntoIterator<Item = (u64, &'a mut [u8])>,
    {
        let bufs: Vec<(u64, &'a mut [u8])> = bufs.into_iter().collect();
        if bufs.is_empty() {
            return Ok(());
        }
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched_into");
            for (ptr, buf) in bufs {
                let end = ptr.checked_add(buf.len() as u64).ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "get_batched_into: offset + buf.len() overflows u64",
                    )
                })?;
                if end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("get_batched_into: end ({end}) exceeds payload size ({data_size})",),
                    ));
                }
                pread_exact_into(file, HEADER_SIZE + ptr, buf)?;
            }
            Ok(())
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched_into");
            for (ptr, buf) in bufs {
                let end = ptr.checked_add(buf.len() as u64).ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "get_batched_into: offset + buf.len() overflows u64",
                    )
                })?;
                if end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("get_batched_into: end ({end}) exceeds payload size ({data_size})",),
                    ));
                }
                file.seek(SeekFrom::Start(HEADER_SIZE + ptr))?;
                file.read_exact(buf)?;
            }
            Ok(())
        }
    }

    /// Read a dependent chain of logical ranges in a single lock acquisition.
    ///
    /// `gen` is called once per read step.  Each call returns `Some((offset,
    /// buf))` to request a read of `buf.len()` bytes starting at `offset` into
    /// `buf`, or `None` to stop.  When `gen` is called, the buffer supplied by
    /// the *previous* call has already been filled with its data — the call
    /// itself signals that the prior buffer is ready.
    ///
    /// All reads happen under the same shared lock (Unix/Windows: read lock;
    /// other platforms: write lock), so no write can interleave between steps.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if any `offset + buf.len()`
    /// overflows `u64` or exceeds the current payload size.
    #[cfg(feature = "atomic")]
    pub fn get_batched_gen<'a, F>(&self, mut f: F) -> io::Result<()>
    where
        F: FnMut() -> Option<(u64, &'a mut [u8])>,
    {
        #[cfg(any(unix, windows))]
        {
            let guard = self.lock.read().unwrap();
            let file = &guard.0;
            let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched_gen");
            while let Some((offset, buf)) = f() {
                let end = offset.checked_add(buf.len() as u64).ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "get_batched_gen: offset + buf.len() overflows u64",
                    )
                })?;
                if end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("get_batched_gen: end ({end}) exceeds payload size ({data_size})"),
                    ));
                }
                pread_exact_into(file, HEADER_SIZE + offset, buf)?;
            }
            Ok(())
        }
        #[cfg(not(any(unix, windows)))]
        {
            let mut guard = self.lock.write().unwrap();
            let file = &mut guard.0;
            let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
            fault_point!(self, "get_batched_gen");
            while let Some((offset, buf)) = f() {
                let end = offset.checked_add(buf.len() as u64).ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "get_batched_gen: offset + buf.len() overflows u64",
                    )
                })?;
                if end > data_size {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("get_batched_gen: end ({end}) exceeds payload size ({data_size})"),
                    ));
                }
                file.seek(SeekFrom::Start(HEADER_SIZE + offset))?;
                file.read_exact(buf)?;
            }
            Ok(())
        }
    }

    /// Pop `n` bytes off the tail, pass them read-only to a callback that
    /// returns the new tail bytes, then write the new tail.
    ///
    /// The read, callback invocation, and write all happen under the same write
    /// lock, so no other thread can observe the state between the pop and the
    /// push.  The callback may return a [`Vec<u8>`] of any length — the file
    /// will grow or shrink accordingly using the same crash-safe ordering
    /// strategy as [`atrunc`](Self::atrunc).
    ///
    /// `n = 0` is valid: the callback receives an empty slice and whatever it
    /// returns is appended.
    ///
    /// # Feature flag
    ///
    /// Only available when the `atomic` Cargo feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the current
    /// payload size.  Propagates any I/O error from `read_exact`, `set_len`,
    /// `write_all`, or `durable_sync`.
    #[cfg(feature = "atomic")]
    pub fn replace<F>(&self, n: u64, f: F) -> io::Result<()>
    where
        F: FnOnce(&[u8]) -> Vec<u8>,
    {
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let file_end = file.seek(SeekFrom::End(0))?;
        let data_size = file_end - HEADER_SIZE;
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("replace: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        let locked = self.locked.load(Ordering::Acquire);
        let new_tail_start = data_size - n;
        if new_tail_start < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("replace: operation would modify locked region [0, {locked})"),
            ));
        }
        fault_point!(self, "replace");
        let mut old_tail = vec![0u8; n as usize];
        read_at(file, new_tail_start, &mut old_tail)?;
        let new_tail = f(&old_tail);

        commit_tail_replace(file, clen, new_tail_start, n, &new_tail, file_end)
    }
}

/// A request to read from, or write to, a region of the payload.
///
/// A value of this type describes a single request and carries no protocol of
/// its own — how a sequence of requests is assembled, interpreted, and
/// brought to an end is entirely up to the primitive that consumes them.
/// Different primitives may impose different rules over the same variants:
/// how many writes are permitted, whether a write ends the sequence, how the
/// sequence itself signals that it is done, and so on. The "ending the
/// sequence" notes below describe [`process_gen`](BStack::process_gen);
/// [`inplace_gen`](BStack::inplace_gen) instead accumulates multiple `Write`s
/// (none ends the sequence) and permits only `Read`, `Write`, and `Len`.
///
/// # Variants
///
/// - `Read { offset, buf }` — read some number of bytes starting at logical
///   `offset` into the caller-supplied buffer `buf`.
/// - `Write { offset, data }` — write `data` starting at logical `offset`,
///   ending the sequence.
/// - `Swap { a_offset, b_offset, len }` — atomically exchange `len` bytes at
///   `a_offset` with `len` bytes at `b_offset`, ending the sequence.
/// - `Push { data }` — append `data` to the end of the file, growing the
///   payload, and ending the sequence.
/// - `Pop { buf }` — remove the last `buf.len()` bytes from the end of the
///   file into `buf`, shrinking the payload, and ending the sequence.
/// - `Discard { len }` — remove the last `len` bytes without reading them back,
///   shrinking the payload, and ending the sequence.
/// - `Atrunc { n, data }` — cut `n` bytes off the tail then append `data`
///   (no readback), ending the sequence.
/// - `Splice { old, new }` — pop `old.len()` bytes off the tail into `old` then
///   append `new`, ending the sequence.
/// - `Len { out }` — write the current logical payload size into `out`.
/// - `#[non_exhaustive]` — later versions may add further variants, for
///   richer write ownership or multi-write protocols, for instance, without
///   a breaking change.
///
/// # Feature flags
///
/// Only available when both the `set` and `atomic` Cargo features are enabled.
#[cfg(all(feature = "set", feature = "atomic"))]
#[non_exhaustive]
// Intentionally not `PartialEq`/`Eq`/`Hash`: each value is a transient,
// single-use request consumed immediately by `process_gen`'s loop, and for
// `Read` "equality" would mean comparing the destination buffer's stale
// pre-read contents — not a meaningful notion of identity.
#[derive(Debug)]
pub enum BStackGenOp<'a> {
    /// Read `buf.len()` bytes starting at logical `offset` into `buf`.
    Read {
        /// Logical offset to read from.
        offset: u64,
        /// Destination buffer; its length determines how many bytes are read.
        buf: &'a mut [u8],
    },
    /// Write `data` to logical `offset..offset + data.len()`, ending the
    /// sequence.
    Write {
        /// Logical offset to write to.
        offset: u64,
        /// Bytes to write.
        data: &'a [u8],
    },
    /// Atomically exchange `len` bytes at `a_offset` with `len` bytes at
    /// `b_offset`, ending the sequence.
    ///
    /// Both regions are read and then swapped under the same held write
    /// lock — the in-sequence equivalent of [`cross_exchange`](BStack::cross_exchange),
    /// useful when one or both offsets are only known once earlier `Read`s
    /// in the sequence have been resolved (e.g. "read the free-list head,
    /// then swap this block into that slot"). The regions must not overlap.
    Swap {
        /// Logical offset of the first region.
        a_offset: u64,
        /// Logical offset of the second region.
        b_offset: u64,
        /// Number of bytes to exchange.
        len: u64,
    },
    /// Append `data` to the end of the file, growing the payload by
    /// `data.len()` bytes, and ending the sequence.
    Push {
        /// Bytes to append.
        data: &'a [u8],
    },
    /// Remove the last `buf.len()` bytes from the end of the file into
    /// `buf`, shrinking the payload by `buf.len()` bytes, and ending the
    /// sequence.
    Pop {
        /// Destination buffer; its length determines how many bytes are
        /// popped.
        buf: &'a mut [u8],
    },
    /// Remove the last `len` bytes from the end of the file, shrinking the
    /// payload by `len` bytes, and ending the sequence.
    ///
    /// The dropped bytes are **not** read back — the in-sequence equivalent of
    /// [`discard`](BStack::discard), and the buffer-free counterpart of
    /// [`Pop`](Self::Pop) (mirroring a C `pop` with a `NULL` destination).
    /// Useful for truncating a tail whose size is only known once earlier
    /// `Read`s have been resolved, without allocating a throwaway buffer.
    Discard {
        /// Number of bytes to remove from the end of the file.
        len: u64,
    },
    /// Cut `n` bytes off the tail then append `data` as a single operation,
    /// ending the sequence.
    ///
    /// The removed bytes are **not** read back — the in-sequence equivalent of
    /// [`atrunc`](BStack::atrunc), and the buffer-free counterpart of
    /// [`Splice`](Self::Splice) (as [`Discard`](Self::Discard) is to
    /// [`Pop`](Self::Pop)). The net payload change is `data.len() − n`; useful
    /// for replacing a tail whose size is only known once earlier `Read`s have
    /// been resolved, without allocating a buffer for the discarded bytes.
    Atrunc {
        /// Number of bytes to cut off the tail before appending.
        n: u64,
        /// Bytes to append after the cut.
        data: &'a [u8],
    },
    /// Pop `old.len()` bytes off the tail into `old`, then append `new`, ending
    /// the sequence.
    ///
    /// The removed bytes are read into `old` before any mutation — the
    /// in-sequence equivalent of [`splice_into`](BStack::splice_into), and the
    /// readback counterpart of [`Atrunc`](Self::Atrunc) (as [`Pop`](Self::Pop)
    /// is to [`Discard`](Self::Discard)). The net payload change is
    /// `new.len() − old.len()`.
    Splice {
        /// Destination for the removed tail bytes; its length determines how
        /// many bytes are popped.
        old: &'a mut [u8],
        /// Bytes to append after the pop.
        new: &'a [u8],
    },
    /// Write the current logical payload size, in bytes, into `out`, then
    /// call `f` again — does not end the sequence.
    Len {
        /// Destination for the current payload size.
        out: &'a mut u64,
    },
}

#[cfg(all(feature = "set", feature = "atomic"))]
impl BStack {
    /// Atomically read `buf.len()` bytes at `offset` and overwrite them with
    /// `buf`, returning the old contents.
    ///
    /// Both the read and the write happen under the same write lock, so no
    /// other thread can observe either the pre-swap or mid-swap state.  The
    /// file size is never changed.
    ///
    /// An empty `buf` is a valid no-op and returns an empty `Vec`.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Crash atomicity
    ///
    /// Crash-atomic: after a crash the region holds either its old or its new
    /// contents, never a mix — the write commits via a single-block atomic write
    /// or the write-in-progress journal (see the crate-level *Durability* docs).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + buf.len()`
    /// overflows `u64` or exceeds the current payload size.  Propagates any
    /// I/O error from `read_exact`, `write_all`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn swap(&self, offset: u64, buf: impl AsRef<[u8]>) -> io::Result<Vec<u8>> {
        let buf = buf.as_ref();
        if buf.is_empty() {
            return Ok(Vec::new());
        }
        let end = checked_end(offset, buf.len() as u64, "swap: offset + len overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("swap", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("swap: range [{offset}, {end}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "swap");
        let mut old = vec![0u8; buf.len()];
        read_at(file, offset, &mut old)?;
        set_in_place(file, data_size, offset, buf)?;
        Ok(old)
    }

    /// Atomically read `buf.len()` bytes at `offset` into `buf` while writing
    /// the original contents of `buf` into that position.
    ///
    /// On return, `buf` contains the bytes that were previously at `offset`,
    /// and the file contains what `buf` held on entry.  Buffer-reuse
    /// counterpart of [`swap`](Self::swap).
    ///
    /// An empty `buf` is a valid no-op.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Crash atomicity
    ///
    /// Crash-atomic, on the same terms as [`swap`](Self::swap).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + buf.len()`
    /// overflows `u64` or exceeds the current payload size.  Propagates any
    /// I/O error from `read_exact`, `write_all`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn swap_into(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
        if buf.is_empty() {
            return Ok(());
        }
        let end = checked_end(
            offset,
            buf.len() as u64,
            "swap_into: offset + len overflows u64",
        )?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("swap_into", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("swap_into: range [{offset}, {end}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "swap_into");
        let mut tmp = vec![0u8; buf.len()];
        read_at(file, offset, &mut tmp)?;
        set_in_place(file, data_size, offset, buf)?;
        buf.copy_from_slice(&tmp);
        Ok(())
    }

    /// Compare-and-exchange: read `old.len()` bytes at `offset` and, if they
    /// equal `old`, overwrite them with `new`.
    ///
    /// Returns `Ok(true)` if the comparison succeeded and the exchange was
    /// performed.  Returns `Ok(false)` without modifying the file if
    /// `old.len() != new.len()` or if the current bytes do not match `old`.
    ///
    /// Both the compare and the exchange happen under the same write lock.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Crash atomicity
    ///
    /// When the exchange is performed it is crash-atomic, on the same terms as
    /// [`set`](Self::set): after a crash the region holds either `old` or `new`,
    /// never a mix.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `offset + old.len()`
    /// overflows `u64` or exceeds the current payload size.  Propagates any
    /// I/O error from `read_exact`, `write_all`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn cas(
        &self,
        offset: u64,
        old: impl AsRef<[u8]>,
        new: impl AsRef<[u8]>,
    ) -> io::Result<bool> {
        let old = old.as_ref();
        let new = new.as_ref();
        if old.len() != new.len() {
            return Ok(false);
        }
        if old.is_empty() {
            return Ok(true);
        }
        let end = checked_end(offset, old.len() as u64, "cas: offset + len overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        check_offset_unlocked("cas", offset, end, locked)?;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cas: range [{offset}, {end}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "cas");
        let mut current = vec![0u8; old.len()];
        read_at(file, offset, &mut current)?;
        if current != old {
            return Ok(false);
        }
        set_in_place(file, data_size, offset, new)?;
        Ok(true)
    }

    /// Atomically swap two equal-size, non-overlapping regions within the file.
    ///
    /// Bytes at `[a, a + n)` and `[b, b + n)` are exchanged under a single
    /// write lock, so no other thread can observe an intermediate state.
    /// The at-rest file size is never changed.  `n = 0` is a valid no-op (bounds
    /// are still checked).
    ///
    /// # Crash atomicity
    ///
    /// Crash-safe: after a crash the two regions hold either their original
    /// contents or the fully swapped contents, never a half-swap. Region A's
    /// bytes are staged in a tail backup and the swap commits at a single atomic
    /// `wip_ptr` flip; recovery on the next [`open`](Self::open) rolls the
    /// exchange back (before the flip) or forward (after it). During the operation
    /// the file grows by `n` bytes to hold the backup, which is dropped on
    /// completion.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if either `a + n` or `b + n`
    /// overflows `u64`, if the regions overlap, if either region exceeds the
    /// current payload size, or if either region overlaps the locked prefix.
    /// Propagates any I/O error from `read_exact`, `write_all`, or
    /// `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn cross_exchange(&self, a: u64, b: u64, n: u64) -> io::Result<()> {
        let a_end = checked_end(a, n, "cross_exchange: a + n overflows u64")?;
        let b_end = checked_end(b, n, "cross_exchange: b + n overflows u64")?;
        if n > 0 {
            let (lo, hi) = if a < b { (a, b) } else { (b, a) };
            if lo + n > hi {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("cross_exchange: regions [{a}, {a_end}) and [{b}, {b_end}) overlap"),
                ));
            }
        }
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if a < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "cross_exchange: region [{a}, {a_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        if b < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "cross_exchange: region [{b}, {b_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if a_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cross_exchange: region [{a}, {a_end}) exceeds payload size ({data_size})"),
            ));
        }
        if b_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("cross_exchange: region [{b}, {b_end}) exceeds payload size ({data_size})"),
            ));
        }
        if n == 0 {
            return Ok(());
        }
        fault_point!(self, "cross_exchange");
        journaled_exchange(file, data_size, a, b, n)
    }

    /// Copy `n` bytes from `from..from+n` to `to..to+n` under a single write lock.
    ///
    /// Overlapping source and destination are handled correctly: the bytes route
    /// through the journal's tail region, disjoint from both.  `n = 0` is a valid
    /// no-op (bounds are still checked).  The file size is never changed.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Durability & atomicity
    ///
    /// Crash-atomic: after a crash the destination holds either its old contents
    /// or the full copy, never a mix.  A destination within one aligned block
    /// takes the single-block atomic path.  A larger *overlapping* copy streams
    /// source→tail→dest through the write-in-progress journal in O(1) memory.  A
    /// larger *disjoint* copy uses the copy journal, which stages only the source
    /// coordinate (not the bytes) and replays directly from the untouched source —
    /// O(1) staging as well.  A copy onto the same location is a no-op.  All paths
    /// are replayed on the next [`open`](Self::open).
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if either `from + n` or `to + n`
    /// overflows `u64`, if either region exceeds the current payload size, or
    /// if the destination region overlaps the locked prefix.
    /// Propagates any I/O error from `read_exact`, `write_all`, or
    /// `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn copy(&self, from: u64, to: u64, n: u64) -> io::Result<()> {
        let from_end = checked_end(from, n, "copy: from + n overflows u64")?;
        let to_end = checked_end(to, n, "copy: to + n overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if to < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("copy: destination [{to}, {to_end}) overlaps locked region [0, {locked})"),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if from_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("copy: source [{from}, {from_end}) exceeds payload size ({data_size})"),
            ));
        }
        if to_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("copy: destination [{to}, {to_end}) exceeds payload size ({data_size})"),
            ));
        }
        if n == 0 {
            return Ok(());
        }
        // A copy onto its own location leaves every byte unchanged — a no-op once
        // the bounds above are validated.
        if from == to {
            return Ok(());
        }
        fault_point!(self, "copy");
        // Write-strategy hierarchy (see `algos/WIP.md`):
        //  * destination within one aligned block → single-block atomic write
        //    (read the source into a bounded buffer — `n` is at most one block
        //    here — and write it);
        //  * overlapping source/destination → route the bytes through the tail
        //    backup (source→tail→dest) so a replay never reads clobbered source
        //    bytes — `journaled_move`, O(1) memory but staging the full `n` bytes;
        //  * disjoint source/destination → copy journal: stage only the source
        //    coordinate `[src | n]`, since the untouched source lets recovery
        //    replay the copy directly — `journaled_copy`, O(1) staging.
        if is_atomic_write(to, n) {
            let mut buf = vec![0u8; n as usize];
            read_at(file, from, &mut buf)?;
            write_at(file, to, &buf)?;
            durable_sync(file)
        } else if from < to_end && to < from_end {
            journaled_move(file, data_size, from, to, n)
        } else {
            journaled_copy(file, data_size, from, to, n)
        }
    }

    /// Read bytes in the half-open logical range `[start, end)`, pass them to
    /// a callback that may mutate them in place, then write the modified bytes
    /// back.
    ///
    /// The read, callback invocation, and write all happen under the same write
    /// lock, so no other thread can observe an intermediate state.  The file
    /// size is never changed.
    ///
    /// `start == end` is a valid no-op: `f` is called with an empty slice and
    /// no I/O is performed beyond the initial size check.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Crash atomicity
    ///
    /// Crash-atomic, on the same terms as [`set`](Self::set): after a crash the
    /// range holds either its pre-callback bytes or the callback's output, never a
    /// mix. (The callback runs in memory, under the lock, before the commit.)
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `end < start` or if `end`
    /// exceeds the current payload size.  Propagates any I/O error from
    /// `read_exact`, `write_all`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn process<F>(&self, start: u64, end: u64, f: F) -> io::Result<()>
    where
        F: FnOnce(&mut [u8]),
    {
        if end < start {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("process: end ({end}) < start ({start})"),
            ));
        }
        let n = end - start;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("process: end ({end}) exceeds payload size ({data_size})"),
            ));
        }
        let locked = self.locked.load(Ordering::Acquire);
        if start < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("process: range [{start}, {end}) overlaps locked region [0, {locked})"),
            ));
        }
        fault_point!(self, "process");
        let mut buf = vec![0u8; n as usize];
        if n > 0 {
            read_at(file, start, &mut buf)?;
        }
        f(&mut buf);
        if n > 0 {
            set_in_place(file, data_size, start, &buf)?;
        }
        Ok(())
    }

    /// Run a sequence of dependent reads, optionally followed by a single
    /// write, all under one held write lock.
    ///
    /// `f` is called in a loop and drives the sequence through [`BStackGenOp`]:
    ///
    /// - `Some(BStackGenOp::Read { offset, buf })` reads `offset..offset +
    ///   buf.len()` into `buf` and calls `f` again.  By the time `f` is called,
    ///   the buffer from the *previous* `Read` already holds its data, so each
    ///   step can use earlier results to decide the next one — e.g. "read the
    ///   head pointer, then read the node it points to".
    /// - `Some(BStackGenOp::Write { offset, data })` writes `data` to
    ///   `offset..offset + data.len()` and ends the sequence; `f` is not
    ///   called again.
    /// - `Some(BStackGenOp::Swap { a_offset, b_offset, len })` atomically
    ///   exchanges `len` bytes at `a_offset` with `len` bytes at `b_offset`
    ///   and ends the sequence — the in-sequence equivalent of
    ///   [`cross_exchange`](Self::cross_exchange), useful when a swap target
    ///   is only known once an earlier `Read` has resolved it (e.g. "read the
    ///   free-list head, then splice this block in as the new head").
    /// - `Some(BStackGenOp::Push { data })` appends `data` to the end of the
    ///   file, growing the payload, and ends the sequence — the in-sequence
    ///   equivalent of [`push`](Self::push).
    /// - `Some(BStackGenOp::Pop { buf })` removes the last `buf.len()` bytes
    ///   from the end of the file into `buf`, shrinking the payload, and ends
    ///   the sequence — the in-sequence equivalent of [`pop`](Self::pop).
    /// - `Some(BStackGenOp::Discard { len })` removes the last `len` bytes from
    ///   the end of the file without reading them back, shrinking the payload,
    ///   and ends the sequence — the in-sequence equivalent of
    ///   [`discard`](Self::discard) and the buffer-free counterpart of `Pop`.
    /// - `Some(BStackGenOp::Atrunc { n, data })` cuts `n` bytes off the tail
    ///   then appends `data` (without reading the removed bytes), changing the
    ///   payload by `data.len() − n`, and ends the sequence — the in-sequence
    ///   equivalent of [`atrunc`](Self::atrunc) and the buffer-free counterpart
    ///   of `Splice`.
    /// - `Some(BStackGenOp::Splice { old, new })` pops `old.len()` bytes off the
    ///   tail into `old` then appends `new`, changing the payload by
    ///   `new.len() − old.len()`, and ends the sequence — the in-sequence
    ///   equivalent of [`splice_into`](Self::splice_into).
    /// - `Some(BStackGenOp::Len { out })` writes the current logical payload
    ///   size into `out` and calls `f` again — the in-sequence equivalent of
    ///   [`len`](Self::len), useful when a later step's offset depends on the
    ///   payload size (e.g. "read the size, then read the last element").
    /// - `None` ends the sequence without writing anything — useful when the
    ///   reads alone inform a decision, including the decision to change
    ///   nothing.
    ///
    /// `Write`, `Swap`, `Push`, `Pop`, `Discard`, `Atrunc`, and `Splice` are the
    /// only mutating operations, exactly one is permitted per call, and any one
    /// of them ends the sequence immediately — `f` is not called again
    /// afterwards.
    ///
    /// Holding the write lock across every read and the final mutation means
    /// no other thread can observe or modify any region of the file in
    /// between — the guarantee that [`get_batched_gen`](Self::get_batched_gen)
    /// followed by a separate [`cas`](Self::cas) cannot provide, since the two
    /// separate lock acquisitions leave an ABA window.  The mutated region(s)
    /// need not overlap any region that was read.  `Push`, `Pop`, `Discard`,
    /// `Atrunc`, and `Splice` are the steps that change the file size.
    ///
    /// Reads of the locked region `[0, locked_len())` are permitted, matching
    /// [`get`](Self::get) — locked bytes are immutable, so observing them
    /// mid-sequence is always safe.  `Write` and `Swap` ranges that touch the
    /// locked region are rejected, matching [`set`](Self::set) and
    /// [`cross_exchange`](Self::cross_exchange); an `Atrunc` or `Splice` whose
    /// cut point falls inside the locked region is likewise rejected, matching
    /// [`atrunc`](Self::atrunc) and [`splice_into`](Self::splice_into).
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if any `offset + len` overflows
    /// `u64`, if a read, write, or swap range exceeds the current payload
    /// size, if the two `Swap` regions overlap, if a write or swap range
    /// overlaps the locked region `[0, locked_len())`, if a `Pop`, `Discard`,
    /// `Atrunc`, or `Splice` removes more bytes than the current payload size,
    /// or if it would shrink the payload below (or cut into) the locked length.
    /// Propagates any I/O error from `read_exact`, `write_all`, `set_len`, or
    /// `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn process_gen<'a, F>(&self, mut f: F) -> io::Result<()>
    where
        F: FnMut() -> Option<BStackGenOp<'a>>,
    {
        let mut guard = self.lock.write().unwrap();
        let (file, clen) = &mut *guard;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        let locked = self.locked.load(Ordering::Acquire);
        fault_point!(self, "process_gen");
        loop {
            match f() {
                Some(BStackGenOp::Read { offset, buf }) => {
                    let end = checked_end(
                        offset,
                        buf.len() as u64,
                        "process_gen: read offset + buf.len() overflows u64",
                    )?;
                    if end > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: read range [{offset}, {end}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    // Fast path: locked bytes are immutable, so they can be
                    // served from the cache or via a lock-free pread instead
                    // of going through the held file handle — mirroring how
                    // `get_into` treats reads of the locked region.
                    #[cfg(any(unix, windows))]
                    {
                        if end <= locked {
                            if self.cache_enabled {
                                let cache = self.cache.lock().unwrap();
                                buf.copy_from_slice(&cache[offset as usize..end as usize]);
                            } else {
                                #[cfg(unix)]
                                pread_exact_raw(self.fd, HEADER_SIZE + offset, buf)?;
                                #[cfg(windows)]
                                pread_exact_raw_handle(self.handle, HEADER_SIZE + offset, buf)?;
                            }
                        } else {
                            pread_exact_into(file, HEADER_SIZE + offset, buf)?;
                        }
                    }
                    #[cfg(not(any(unix, windows)))]
                    {
                        if end <= locked && self.cache_enabled {
                            let cache = self.cache.lock().unwrap();
                            buf.copy_from_slice(&cache[offset as usize..end as usize]);
                        } else {
                            read_at(file, offset, buf)?;
                        }
                    }
                }
                Some(BStackGenOp::Write { offset, data }) => {
                    let end = checked_end(
                        offset,
                        data.len() as u64,
                        "process_gen: write offset + data.len() overflows u64",
                    )?;
                    if offset < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: write range [{offset}, {end}) overlaps locked region [0, {locked})"
                            ),
                        ));
                    }
                    if end > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: write range [{offset}, {end}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    if !data.is_empty() {
                        set_in_place(file, data_size, offset, data)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Swap {
                    a_offset,
                    b_offset,
                    len,
                }) => {
                    let a_end =
                        checked_end(a_offset, len, "process_gen: a_offset + len overflows u64")?;
                    let b_end =
                        checked_end(b_offset, len, "process_gen: b_offset + len overflows u64")?;
                    if len > 0 {
                        let (lo, hi) = if a_offset < b_offset {
                            (a_offset, b_offset)
                        } else {
                            (b_offset, a_offset)
                        };
                        if lo + len > hi {
                            return Err(io::Error::new(
                                io::ErrorKind::InvalidInput,
                                format!(
                                    "process_gen: swap regions [{a_offset}, {a_end}) and [{b_offset}, {b_end}) overlap"
                                ),
                            ));
                        }
                    }
                    if a_offset < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: swap region [{a_offset}, {a_end}) overlaps locked region [0, {locked})"
                            ),
                        ));
                    }
                    if b_offset < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: swap region [{b_offset}, {b_end}) overlaps locked region [0, {locked})"
                            ),
                        ));
                    }
                    if a_end > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: swap region [{a_offset}, {a_end}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    if b_end > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: swap region [{b_offset}, {b_end}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    if len > 0 {
                        journaled_exchange(file, data_size, a_offset, b_offset, len)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Push { data }) => {
                    if !data.is_empty() {
                        let file_end = file.seek(SeekFrom::End(0))?;
                        let logical_offset = file_end - HEADER_SIZE;
                        if let Err(e) = file.write_all(data) {
                            let _ = file.set_len(file_end);
                            return Err(e);
                        }
                        let new_len = logical_offset + data.len() as u64;
                        commit_grow(file, clen, new_len, logical_offset, file_end)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Pop { buf }) => {
                    let n = buf.len() as u64;
                    if n > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!("process_gen: pop({n}) exceeds payload size ({data_size})"),
                        ));
                    }
                    let new_data_len = data_size - n;
                    if new_data_len < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: pop({n}) would shrink payload below locked length ({locked})"
                            ),
                        ));
                    }
                    if n > 0 {
                        read_at(file, new_data_len, buf)?;
                        commit_shrink(file, clen, new_data_len)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Discard { len }) => {
                    if len > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: discard({len}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    let new_data_len = data_size - len;
                    if new_data_len < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: discard({len}) would shrink payload below locked length ({locked})"
                            ),
                        ));
                    }
                    if len > 0 {
                        commit_shrink(file, clen, new_data_len)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Atrunc { n, data }) => {
                    if n > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: atrunc n ({n}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    let new_tail_start = data_size - n;
                    if new_tail_start < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!("process_gen: atrunc would modify locked region [0, {locked})"),
                        ));
                    }
                    if n != 0 || !data.is_empty() {
                        let file_end = HEADER_SIZE + data_size;
                        commit_tail_replace(file, clen, new_tail_start, n, data, file_end)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Splice { old, new }) => {
                    let n = old.len() as u64;
                    if n > data_size {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!(
                                "process_gen: splice n ({n}) exceeds payload size ({data_size})"
                            ),
                        ));
                    }
                    let new_tail_start = data_size - n;
                    if new_tail_start < locked {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            format!("process_gen: splice would modify locked region [0, {locked})"),
                        ));
                    }
                    if n != 0 || !new.is_empty() {
                        // Read the removed bytes before any mutation.
                        read_at(file, new_tail_start, old)?;
                        let file_end = HEADER_SIZE + data_size;
                        commit_tail_replace(file, clen, new_tail_start, n, new, file_end)?;
                    }
                    return Ok(());
                }
                Some(BStackGenOp::Len { out }) => {
                    *out = data_size;
                }
                None => return Ok(()),
            }
        }
    }

    /// Crash-atomically commit several non-overlapping in-place writes as a
    /// single unit.
    ///
    /// Takes any iterator of `(offset, data)` pairs and overwrites each
    /// `[offset, offset + data.len())` with `data`, all committing together:
    /// after a crash either every write is applied or none is, never a partial
    /// subset. Empty `data` slices are ignored. The file size is never changed —
    /// every write is an in-place overwrite of committed bytes.
    ///
    /// The writes must be **pairwise non-overlapping**; an overlapping pair is
    /// rejected as invalid input. (The generator form,
    /// [`inplace_gen`](Self::inplace_gen), instead resolves overlap in favour of
    /// the later write.)
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Durability & atomicity
    ///
    /// Crash-atomic across the whole batch via the multi-write journal (stage all
    /// blocks → arm → replay → disarm), which recovery replays or rolls back on
    /// the next [`open`](Self::open). A batch that reduces to a single non-empty
    /// write takes the ordinary single-write path (a single-block atomic write or
    /// the write-in-progress journal). The written bytes are durably synced
    /// before the call returns.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if any `offset + data.len()`
    /// overflows `u64` or exceeds the current payload size, if any write overlaps
    /// the locked region `[0, locked_len())`, or if two writes overlap.
    /// Propagates any I/O error from `write_all`, `set_len`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn set_batched<I, D>(&self, writes: I) -> io::Result<()>
    where
        I: IntoIterator<Item = (u64, D)>,
        D: AsRef<[u8]>,
    {
        // Materialise the inputs so their `AsRef` slices can be borrowed while we
        // validate, sort, and stage; drop empty writes (they touch nothing).
        let owned: Vec<(u64, D)> = writes.into_iter().collect();
        let mut blocks: Vec<(u64, &[u8])> = owned
            .iter()
            .map(|(off, d)| (*off, d.as_ref()))
            .filter(|(_, d)| !d.is_empty())
            .collect();
        if blocks.is_empty() {
            return Ok(());
        }
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        // Load `locked` under the write lock (see `set` for rationale).
        let locked = self.locked.load(Ordering::Acquire);
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        // Validate each block against the payload size and the locked prefix.
        for (off, data) in &blocks {
            let end = checked_end(
                *off,
                data.len() as u64,
                "set_batched: offset + len overflows u64",
            )?;
            if *off < locked {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "set_batched: write range [{off}, {end}) overlaps locked region [0, {locked})"
                    ),
                ));
            }
            if end > data_size {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!(
                        "set_batched: write range [{off}, {end}) exceeds payload size ({data_size})"
                    ),
                ));
            }
        }
        fault_point!(self, "set_batched");
        // A lone write cannot overlap anything and is already atomic on its own,
        // so skip the overlap scan and the multi-write journal.
        if blocks.len() == 1 {
            let (off, data) = blocks[0];
            return set_in_place(file, data_size, off, data);
        }
        // Reject overlap: sort by offset, then check that each block ends at or
        // before the next one begins.
        blocks.sort_by_key(|(off, _)| *off);
        for pair in blocks.windows(2) {
            let (a_off, a_data) = pair[0];
            let (b_off, _) = pair[1];
            let a_end = a_off + a_data.len() as u64;
            if a_end > b_off {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("set_batched: write range [{a_off}, {a_end}) overlaps [{b_off}, ...)"),
                ));
            }
        }
        journaled_multi_set(file, data_size, &blocks)
    }

    /// Run a sequence of dependent reads interleaved with multiple in-place
    /// writes, committing every write as one crash-atomic unit when the sequence
    /// ends.
    ///
    /// Like [`process_gen`](Self::process_gen), `f` is called in a loop and drives
    /// the sequence through [`BStackGenOp`], all under one held write lock — but
    /// with three differences:
    ///
    /// - **Writes accumulate; they do not end the sequence.** Each
    ///   `Some(BStackGenOp::Write { offset, data })` records a pending in-place
    ///   write and `f` is called again. Every recorded write commits together
    ///   when the sequence ends (`None`), via the multi-write journal: after a
    ///   crash either all of them are applied or none is.
    /// - **Later writes override earlier overlapping ones.** Overlap is not
    ///   rejected (unlike [`set_batched`](Self::set_batched)); the later write
    ///   wins on the overlapping bytes. For `a<b<c<d`, writing `a..c` then `b..d`
    ///   commits `a..b` from the first write and `b..d` from the second.
    /// - **Reads see the batch-so-far content.** A `Some(BStackGenOp::Read {
    ///   offset, buf })` returns the payload as it *would* look with every pending
    ///   write applied — committed bytes overlaid with the edits recorded so far —
    ///   not the on-disk committed bytes.
    ///
    /// `f` receives the [`io::Result`] of the **previous** op (the first call
    /// receives `Ok(())`): the outcome of a `Read`, or the validation result of a
    /// `Write`. An erroring op is simply not recorded — `f` can inspect the error
    /// and choose to continue, issue a different op, or end the sequence, rather
    /// than the whole batch being torn down. `Some(BStackGenOp::Len { out })`
    /// writes the current payload size into `out` (it never changes here) and
    /// continues. `None` ends the sequence and commits the accumulated writes.
    ///
    /// Only in-place operations are permitted: `Read`, `Write`, and `Len`. The
    /// size-changing ops (`Push`, `Pop`, `Discard`, `Atrunc`, `Splice`) and
    /// `Swap` are rejected with [`io::ErrorKind::InvalidInput`] reported to `f`
    /// (they are not recorded and do not end the sequence) — the multi-write
    /// journal pins `clen` and `file_size` as the staging bounds, so no
    /// size-changing operation may be compounded with it.
    ///
    /// Every slice returned by `f` — both `Write` data and any sub-slice it is
    /// derived from — must outlive the call: pending `Write` data is borrowed
    /// (`&'a [u8]`) until the final commit and consulted by later `Read`s, so a
    /// buffer handed to a `Write` must not be reused or mutated until
    /// `inplace_gen` returns.
    ///
    /// Reads of the locked region `[0, locked_len())` are permitted (those bytes
    /// are immutable); `Write` ranges that touch it are rejected, matching
    /// [`set`](Self::set).
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Per-op validation failures (overflow, out-of-range, locked-region or
    /// disallowed-op errors) are reported to `f` as the next call's argument, not
    /// returned. The call itself returns an error only if a `Read`'s I/O fails, or
    /// if staging, replaying, or disarming the final commit fails — propagating
    /// any I/O error from `read_exact`, `write_all`, `set_len`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn inplace_gen<'a, F>(&self, mut f: F) -> io::Result<()>
    where
        F: FnMut(io::Result<()>) -> Option<BStackGenOp<'a>>,
    {
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        let locked = self.locked.load(Ordering::Acquire);
        fault_point!(self, "inplace_gen");
        // Sorted, pairwise-non-overlapping set of pending in-place edits, each
        // borrowing the caller's `Write` data for the lifetime of the call.
        let mut overlay: Vec<(u64, &'a [u8])> = Vec::new();
        let mut feedback: io::Result<()> = Ok(());
        loop {
            match f(feedback) {
                Some(BStackGenOp::Read { offset, buf }) => {
                    feedback = inplace_overlay_read(file, data_size, offset, buf, &overlay);
                }
                Some(BStackGenOp::Write { offset, data }) => {
                    feedback = inplace_validate_write(offset, data, data_size, locked);
                    if feedback.is_ok() && !data.is_empty() {
                        inplace_overlay_insert(&mut overlay, offset, data);
                    }
                }
                Some(BStackGenOp::Len { out }) => {
                    *out = data_size;
                    feedback = Ok(());
                }
                Some(BStackGenOp::Swap { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Swap is not permitted (Read/Write/Len only)",
                    ));
                }
                Some(BStackGenOp::Push { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Push is not permitted (in-place writes only)",
                    ));
                }
                Some(BStackGenOp::Pop { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Pop is not permitted (in-place writes only)",
                    ));
                }
                Some(BStackGenOp::Discard { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Discard is not permitted (in-place writes only)",
                    ));
                }
                Some(BStackGenOp::Atrunc { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Atrunc is not permitted (in-place writes only)",
                    ));
                }
                Some(BStackGenOp::Splice { .. }) => {
                    feedback = Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "inplace_gen: Splice is not permitted (in-place writes only)",
                    ));
                }
                None => break,
            }
        }
        // Commit the accumulated edits. Zero → nothing to do; one → the ordinary
        // single-write path; many → the multi-write journal.
        match overlay.len() {
            0 => Ok(()),
            1 => {
                let (offset, data) = overlay[0];
                set_in_place(file, data_size, offset, data)
            }
            _ => journaled_multi_set(file, data_size, &overlay),
        }
    }

    /// Cross-Region Dependent Swap — equal condition.
    ///
    /// Reads `a_expected.len()` bytes from logical offset `a_offset` and
    /// compares them to `a_expected`.  If they are **equal**, atomically swaps
    /// region B: reads `b_buf.len()` bytes from `b_offset`, writes the current
    /// contents of `b_buf` there, and returns the old region-B bytes as
    /// `Ok(Some(Vec<u8>))`.  If the comparison fails, returns `Ok(None)`
    /// without modifying the file.
    ///
    /// The read of region A, the comparison, the read of region B, and the
    /// write to region B all happen under the same write lock, so no other
    /// thread can observe an intermediate state.  The file size is never
    /// changed.
    ///
    /// An empty `a_expected` trivially compares equal (zero bytes match zero
    /// bytes).  An empty `b_buf` skips the B swap and returns
    /// `Ok(Some(Vec::new()))` when the condition passes.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if either `a_offset + a_len` or
    /// `b_offset + b_len` overflows `u64`, exceeds the current payload size,
    /// or if region B overlaps the locked prefix.  Propagates any I/O error
    /// from `read_exact`, `write_all`, or `durable_sync`.
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn eq_crds(
        &self,
        a_offset: u64,
        a_expected: impl AsRef<[u8]>,
        b_offset: u64,
        b_buf: impl AsRef<[u8]>,
    ) -> io::Result<Option<Vec<u8>>> {
        let a_expected = a_expected.as_ref();
        let b_buf = b_buf.as_ref();
        let a_len = a_expected.len() as u64;
        let b_len = b_buf.len() as u64;
        let a_end = checked_end(a_offset, a_len, "eq_crds: a_offset + a_len overflows u64")?;
        let b_end = checked_end(b_offset, b_len, "eq_crds: b_offset + b_len overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if !b_buf.is_empty() && b_offset < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "eq_crds: B range [{b_offset}, {b_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if !a_expected.is_empty() && a_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "eq_crds: A range [{a_offset}, {a_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        if !b_buf.is_empty() && b_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "eq_crds: B range [{b_offset}, {b_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        fault_point!(self, "eq_crds");
        let mut a_current = vec![0u8; a_expected.len()];
        if !a_expected.is_empty() {
            read_at(file, a_offset, &mut a_current)?;
        }
        if a_current != a_expected {
            return Ok(None);
        }
        if b_buf.is_empty() {
            return Ok(Some(Vec::new()));
        }
        let mut old_b = vec![0u8; b_buf.len()];
        read_at(file, b_offset, &mut old_b)?;
        set_in_place(file, data_size, b_offset, b_buf)?;
        Ok(Some(old_b))
    }

    /// Cross-Region Dependent Swap — not-equal condition.
    ///
    /// Like [`eq_crds`](Self::eq_crds) but performs the region-B swap only
    /// when the `a_expected.len()` bytes at `a_offset` are **not equal** to
    /// `a_expected`.  If the bytes are not equal, atomically swaps region B:
    /// reads `b_buf.len()` bytes from `b_offset`, writes the contents of
    /// `b_buf` there, and returns the old region-B bytes as
    /// `Ok(Some(Vec<u8>))`.  Returns `Ok(None)` if the bytes compare equal
    /// (swap suppressed).
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Same conditions as [`eq_crds`](Self::eq_crds).
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn ne_crds(
        &self,
        a_offset: u64,
        a_expected: impl AsRef<[u8]>,
        b_offset: u64,
        b_buf: impl AsRef<[u8]>,
    ) -> io::Result<Option<Vec<u8>>> {
        let a_expected = a_expected.as_ref();
        let b_buf = b_buf.as_ref();
        let a_len = a_expected.len() as u64;
        let b_len = b_buf.len() as u64;
        let a_end = checked_end(a_offset, a_len, "ne_crds: a_offset + a_len overflows u64")?;
        let b_end = checked_end(b_offset, b_len, "ne_crds: b_offset + b_len overflows u64")?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if !b_buf.is_empty() && b_offset < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "ne_crds: B range [{b_offset}, {b_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if !a_expected.is_empty() && a_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "ne_crds: A range [{a_offset}, {a_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        if !b_buf.is_empty() && b_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "ne_crds: B range [{b_offset}, {b_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        fault_point!(self, "ne_crds");
        let mut a_current = vec![0u8; a_expected.len()];
        if !a_expected.is_empty() {
            read_at(file, a_offset, &mut a_current)?;
        }
        if a_current == a_expected {
            return Ok(None);
        }
        if b_buf.is_empty() {
            return Ok(Some(Vec::new()));
        }
        let mut old_b = vec![0u8; b_buf.len()];
        read_at(file, b_offset, &mut old_b)?;
        set_in_place(file, data_size, b_offset, b_buf)?;
        Ok(Some(old_b))
    }

    /// Cross-Region Dependent Swap — masked-equal condition.
    ///
    /// Like [`eq_crds`](Self::eq_crds) but the comparison applies a bitwise
    /// AND mask before comparing: for each byte `i`, the condition is
    /// `(A[i] & mask[i]) == (a_expected[i] & mask[i])`.  `mask` and
    /// `a_expected` must have the same length, which determines how many
    /// bytes are read from region A.  If the masked condition holds,
    /// atomically swaps region B: reads `b_buf.len()` bytes from `b_offset`,
    /// writes the contents of `b_buf` there, and returns the old region-B
    /// bytes as `Ok(Some(Vec<u8>))`.  Returns `Ok(None)` if the masked
    /// condition does not hold.
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `mask.len() != a_expected.len()`.
    /// Same additional conditions as [`eq_crds`](Self::eq_crds).
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn masked_eq_crds(
        &self,
        a_offset: u64,
        mask: impl AsRef<[u8]>,
        a_expected: impl AsRef<[u8]>,
        b_offset: u64,
        b_buf: impl AsRef<[u8]>,
    ) -> io::Result<Option<Vec<u8>>> {
        let mask = mask.as_ref();
        let a_expected = a_expected.as_ref();
        let b_buf = b_buf.as_ref();
        if mask.len() != a_expected.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_eq_crds: mask length ({}) != a_expected length ({})",
                    mask.len(),
                    a_expected.len()
                ),
            ));
        }
        let a_len = a_expected.len() as u64;
        let b_len = b_buf.len() as u64;
        let a_end = checked_end(
            a_offset,
            a_len,
            "masked_eq_crds: a_offset + a_len overflows u64",
        )?;
        let b_end = checked_end(
            b_offset,
            b_len,
            "masked_eq_crds: b_offset + b_len overflows u64",
        )?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if !b_buf.is_empty() && b_offset < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_eq_crds: B range [{b_offset}, {b_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if !a_expected.is_empty() && a_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_eq_crds: A range [{a_offset}, {a_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        if !b_buf.is_empty() && b_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_eq_crds: B range [{b_offset}, {b_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        fault_point!(self, "masked_eq_crds");
        let mut a_current = vec![0u8; a_expected.len()];
        if !a_expected.is_empty() {
            read_at(file, a_offset, &mut a_current)?;
        }
        let masked_match = a_current
            .iter()
            .zip(mask.iter())
            .zip(a_expected.iter())
            .all(|((&a, &m), &e)| (a & m) == (e & m));
        if !masked_match {
            return Ok(None);
        }
        if b_buf.is_empty() {
            return Ok(Some(Vec::new()));
        }
        let mut old_b = vec![0u8; b_buf.len()];
        read_at(file, b_offset, &mut old_b)?;
        set_in_place(file, data_size, b_offset, b_buf)?;
        Ok(Some(old_b))
    }

    /// Cross-Region Dependent Swap — masked-not-equal condition.
    ///
    /// Like [`masked_eq_crds`](Self::masked_eq_crds) but performs the
    /// region-B swap only when **any** masked byte differs:
    /// `(A[i] & mask[i]) != (a_expected[i] & mask[i])` for at least one `i`.
    /// If any masked byte differs, atomically swaps region B: reads
    /// `b_buf.len()` bytes from `b_offset`, writes the contents of `b_buf`
    /// there, and returns the old region-B bytes as `Ok(Some(Vec<u8>))`.
    /// Returns `Ok(None)` if all masked bytes compare equal (swap suppressed).
    ///
    /// # Feature flags
    ///
    /// Only available when both the `set` and `atomic` Cargo features are
    /// enabled.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `mask.len() != a_expected.len()`.
    /// Same additional conditions as [`eq_crds`](Self::eq_crds).
    #[cfg(all(feature = "set", feature = "atomic"))]
    pub fn masked_ne_crds(
        &self,
        a_offset: u64,
        mask: impl AsRef<[u8]>,
        a_expected: impl AsRef<[u8]>,
        b_offset: u64,
        b_buf: impl AsRef<[u8]>,
    ) -> io::Result<Option<Vec<u8>>> {
        let mask = mask.as_ref();
        let a_expected = a_expected.as_ref();
        let b_buf = b_buf.as_ref();
        if mask.len() != a_expected.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_ne_crds: mask length ({}) != a_expected length ({})",
                    mask.len(),
                    a_expected.len()
                ),
            ));
        }
        let a_len = a_expected.len() as u64;
        let b_len = b_buf.len() as u64;
        let a_end = checked_end(
            a_offset,
            a_len,
            "masked_ne_crds: a_offset + a_len overflows u64",
        )?;
        let b_end = checked_end(
            b_offset,
            b_len,
            "masked_ne_crds: b_offset + b_len overflows u64",
        )?;
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let locked = self.locked.load(Ordering::Acquire);
        if !b_buf.is_empty() && b_offset < locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_ne_crds: B range [{b_offset}, {b_end}) overlaps locked region [0, {locked})"
                ),
            ));
        }
        let data_size = file.seek(SeekFrom::End(0))?.saturating_sub(HEADER_SIZE);
        if !a_expected.is_empty() && a_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_ne_crds: A range [{a_offset}, {a_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        if !b_buf.is_empty() && b_end > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "masked_ne_crds: B range [{b_offset}, {b_end}) exceeds payload size ({data_size})"
                ),
            ));
        }
        fault_point!(self, "masked_ne_crds");
        let mut a_current = vec![0u8; a_expected.len()];
        if !a_expected.is_empty() {
            read_at(file, a_offset, &mut a_current)?;
        }
        let masked_match = a_current
            .iter()
            .zip(mask.iter())
            .zip(a_expected.iter())
            .all(|((&a, &m), &e)| (a & m) == (e & m));
        if masked_match {
            return Ok(None);
        }
        if b_buf.is_empty() {
            return Ok(Some(Vec::new()));
        }
        let mut old_b = vec![0u8; b_buf.len()];
        read_at(file, b_offset, &mut old_b)?;
        set_in_place(file, data_size, b_offset, b_buf)?;
        Ok(Some(old_b))
    }
}

// ---------------------------------------------------------------------------

impl BStack {
    /// Return the current **logical** payload size in bytes (excludes the
    /// 32-byte header).
    ///
    /// Reads the in-memory `clen` cache under the read lock, so it can run
    /// concurrently with other `len` calls but blocks while any write-lock
    /// operation is in progress. No syscall is made. The returned value
    /// always reflects a clean operation boundary.
    ///
    /// # Errors
    ///
    /// Never actually fails outside of an armed fault policy under the
    /// `fault-injection` feature; returns [`io::Result`] for source
    /// compatibility.
    pub fn len(&self) -> io::Result<u64> {
        fault_point!(self, "len");
        Ok(self.lock.read().unwrap().1)
    }

    /// Return `true` if the stack contains no payload bytes.
    ///
    /// # Errors
    ///
    /// Never actually fails outside of an armed fault policy under the
    /// `fault-injection` feature; returns [`io::Result`] for source
    /// compatibility.
    pub fn is_empty(&self) -> io::Result<bool> {
        fault_point!(self, "is_empty");
        Ok(self.lock.read().unwrap().1 == 0)
    }

    /// Returns the current locked length.  `0` means no bytes are locked.
    ///
    /// The locked region is `[0, locked_len())`.  All bytes within this range
    /// are permanently immutable: writes and shrink operations that would
    /// touch them return [`io::ErrorKind::InvalidInput`]. For
    /// [`get`](Self::get) and [`get_into`](Self::get_into), reads to ranges
    /// entirely within it skip the rwlock.
    pub fn locked_len(&self) -> u64 {
        self.locked.load(Ordering::Acquire)
    }

    /// Extend the locked region to cover `[0, n)`.
    ///
    /// `n` must be ≥ the current locked length and ≤ the current payload
    /// length. After this call, [`get`](Self::get) and
    /// [`get_into`](Self::get_into) reads to `[0, n)` skip the rwlock
    /// (lock-free on non-cached Unix/Windows stacks; cache-backed under a
    /// `Mutex` on cached stacks), and all write and shrink operations that
    /// would touch `[0, n)` return [`io::ErrorKind::InvalidInput`].
    ///
    /// Acquires the exclusive write lock to ensure all in-flight writes to
    /// `[0, n)` have completed before the region is declared immutable.
    ///
    /// # Performance
    ///
    /// On stacks opened with [`open_cached`](Self::open_cached) this call
    /// reads only the newly added portion of the locked region, that is,
    /// `n - current_locked_len` bytes, from disk into the in-memory cache
    /// before returning. In the worst case this is `n` bytes, but only when
    /// locking from `0`. This makes `lock_up_to` significantly more expensive
    /// on cached stacks than on non-cached ones.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` is less than the current
    /// locked length (partition can only grow) or if `n` exceeds the current
    /// payload length.
    pub fn lock_up_to(&self, n: u64) -> io::Result<()> {
        // Acquire the write lock to serialise against any in-flight writers.
        #[allow(unused_mut)]
        // `mut` is not needed on Unix and Windows, but other platforms may need it for the file handle.
        let mut guard = self.lock.write().unwrap();
        let file = &mut guard.0;
        let data_size = file.metadata()?.len().saturating_sub(HEADER_SIZE);
        let current_locked = self.locked.load(Ordering::Relaxed);
        if n < current_locked {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "lock_up_to: n ({n}) is less than the current locked length ({current_locked})"
                ),
            ));
        }
        if n > data_size {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("lock_up_to: n ({n}) exceeds payload size ({data_size})"),
            ));
        }
        fault_point!(self, "lock_up_to");
        // Populate or extend the in-memory cache before publishing the new
        // boundary.  `locked` is only advanced after the cache is consistent,
        // so readers always see a coherent view.
        if self.cache_enabled && n > current_locked {
            // On 32-bit targets usize < u64, so very large regions cannot be
            // cached.  Validate before casting to avoid silent truncation or a
            // panic inside next_power_of_two.
            if n > usize::MAX as u64 {
                return Err(io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "lock_up_to: locked region too large to cache on this platform",
                ));
            }
            let ol = current_locked as usize; // safe: <= n, which was just validated
            let nl = n as usize; // safe: checked above
            // isize::MAX is the maximum valid allocation size; values above it
            // would also cause next_power_of_two to overflow.
            if nl > isize::MAX as usize {
                return Err(io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "lock_up_to: locked region too large to cache on this platform",
                ));
            }
            let mut cache = self.cache.lock().unwrap();

            if nl > cache.capacity() {
                // Reallocating: build a fresh Vec with power-of-2 capacity,
                // copy the existing valid bytes, read the new portion from disk.
                // On read failure new_cache is dropped; self.locked is unchanged
                // and the old cache remains valid for [0..ol].
                let new_cap = nl.next_power_of_two();
                let mut new_cache = Vec::with_capacity(new_cap);
                new_cache.extend_from_slice(&cache[..ol]);
                new_cache.resize(nl, 0u8);
                #[cfg(unix)]
                pread_exact_raw(self.fd, HEADER_SIZE + ol as u64, &mut new_cache[ol..nl])?;
                #[cfg(windows)]
                pread_exact_raw_handle(
                    self.handle,
                    HEADER_SIZE + ol as u64,
                    &mut new_cache[ol..nl],
                )?;
                #[cfg(not(any(unix, windows)))]
                {
                    file.seek(SeekFrom::Start(HEADER_SIZE + ol as u64))?;
                    file.read_exact(&mut new_cache[ol..nl])?;
                }
                *cache = new_cache;
            } else {
                // Non-reallocating: extend the Vec in-place and read the new
                // portion.  On read failure, truncate back to the old length.
                cache.resize(nl, 0u8);
                #[cfg(unix)]
                if let Err(e) =
                    pread_exact_raw(self.fd, HEADER_SIZE + ol as u64, &mut cache[ol..nl])
                {
                    cache.truncate(ol);
                    return Err(e);
                }
                #[cfg(windows)]
                if let Err(e) =
                    pread_exact_raw_handle(self.handle, HEADER_SIZE + ol as u64, &mut cache[ol..nl])
                {
                    cache.truncate(ol);
                    return Err(e);
                }
                #[cfg(not(any(unix, windows)))]
                if let Err(e) = file
                    .seek(SeekFrom::Start(HEADER_SIZE + ol as u64))
                    .and_then(|_| file.read_exact(&mut cache[ol..nl]))
                {
                    cache.truncate(ol);
                    return Err(e);
                }
            }
        }

        // Release store: all writes completed under the write lock above are
        // visible to any thread that subsequently loads `locked` with Acquire.
        self.locked.store(n, Ordering::Release);
        drop(guard);
        Ok(())
    }

    /// Open a `BStack` and immediately lock the first `n` bytes.
    ///
    /// Equivalent to [`BStack::open`] followed by [`lock_up_to`](Self::lock_up_to),
    /// but expressed as a single call for the common pattern where the locked
    /// region is known ahead of time (e.g. a fixed-size metadata block whose
    /// size is a compile-time or configuration constant).
    ///
    /// # Errors
    ///
    /// Propagates all errors from [`open`](Self::open).  Returns
    /// [`io::ErrorKind::InvalidInput`] if `n` exceeds the payload length of
    /// the opened file.
    pub fn open_locked_up_to(path: impl AsRef<Path>, n: u64) -> io::Result<Self> {
        let stack = Self::open(path)?;
        stack.lock_up_to(n)?;
        Ok(stack)
    }

    /// Open or create a stack file at `path` with the in-memory locked-region
    /// cache enabled.
    ///
    /// Behaves identically to [`open`](Self::open) in all other respects.
    /// Once the cache is enabled, each subsequent [`lock_up_to`](Self::lock_up_to)
    /// call reads the newly locked bytes from disk into a heap buffer so that
    /// future reads whose range falls entirely within the locked region are
    /// served by copying from that buffer with no syscall.
    ///
    /// # Errors
    ///
    /// Propagates all errors from [`open`](Self::open).
    pub fn open_cached(path: impl AsRef<Path>) -> io::Result<Self> {
        let mut stack = Self::open(path)?;
        stack.cache_enabled = true;
        Ok(stack)
    }

    /// Open a cached `BStack` and immediately lock the first `n` bytes.
    ///
    /// Equivalent to [`open_cached`](Self::open_cached) followed by
    /// [`lock_up_to`](Self::lock_up_to), but expressed as a single call.
    ///
    /// # Errors
    ///
    /// Propagates all errors from [`open_cached`](Self::open_cached) and
    /// [`lock_up_to`](Self::lock_up_to).
    /// Returns [`io::ErrorKind::InvalidInput`] if `n` exceeds the payload
    /// length of the opened file.
    pub fn open_locked_up_to_cached(path: impl AsRef<Path>, n: u64) -> io::Result<Self> {
        let stack = Self::open_cached(path)?;
        stack.lock_up_to(n)?;
        Ok(stack)
    }
}

/// Deterministic I/O-fault injection controls.
///
/// These methods exist only in builds with `debug_assertions` on and the
/// `fault-injection` feature enabled (see the [`fault`] module); a normal release
/// build exposes none of them and carries no fault-injection machinery.
#[cfg(all(debug_assertions, feature = "fault-injection"))]
impl BStack {
    /// Install a [`FaultPolicy`] on this stack at construction time, consuming and
    /// returning `self` so it can be chained onto a constructor:
    ///
    /// ```ignore
    /// let stack = BStack::open(path)?.with_fault_policy(Arc::new(my_policy));
    /// ```
    ///
    /// Equivalent to [`open`](Self::open) followed by
    /// [`set_fault_policy`](Self::set_fault_policy)`(Some(policy))`; the operation
    /// sequence counter starts at 0.
    pub fn with_fault_policy(self, policy: std::sync::Arc<dyn fault::FaultPolicy>) -> Self {
        self.fault.set(Some(policy));
        self
    }

    /// Arm, re-arm, or (with `None`) disarm the fault policy on an already-open
    /// stack. Setting a policy resets the operation sequence counter to 0, so a
    /// seeded schedule replays identically each time it is armed. Because this
    /// takes `&self`, a test holding a shared reference can arm a fault, drive the
    /// operation under test, then disarm before reading results back.
    pub fn set_fault_policy(&self, policy: Option<std::sync::Arc<dyn fault::FaultPolicy>>) {
        self.fault.set(policy);
    }

    /// Return the currently armed [`FaultPolicy`], or `None` if the stack is
    /// unarmed.
    pub fn fault_policy(&self) -> Option<std::sync::Arc<dyn fault::FaultPolicy>> {
        self.fault.get()
    }
}

// ---------------------------------------------------------------------------
// io::Write

/// Appends bytes to the stack.
///
/// Each call to [`write`](io::Write::write) is equivalent to [`push`](BStack::push):
/// all bytes are written atomically and durably synced before returning.
/// Calling `write_all` or chaining multiple `write` calls therefore issues
/// one `durable_sync` per call — callers that need to batch many small writes
/// without per-write syncs should accumulate data and call `push` directly.
///
/// [`flush`](io::Write::flush) is a no-op because every `write` is already
/// durable.
impl io::Write for BStack {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.push(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Shared-reference counterpart of `impl Write for BStack`.
///
/// Because [`push`](BStack::push) takes `&self` (interior mutability via
/// `RwLock`), the `Write` implementation is also available on `&BStack`,
/// mirroring the standard library's `impl Write for &File`.
impl io::Write for &BStack {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.push(buf)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl fmt::Debug for BStack {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BStack")
            .field(
                "version",
                &format!("{}.{}.{}", MAGIC[4], MAGIC[5], MAGIC[6]),
            )
            .field("len", &self.len().ok())
            .finish_non_exhaustive()
    }
}

impl Eq for BStack {}

/// Two `BStack` instances are equal iff they are the **same instance** in memory.
///
/// Because [`BStack::open`] acquires an exclusive advisory lock, no two
/// `BStack` values within one process can refer to the same file at the same
/// time.  Pointer identity is therefore the only meaningful equality: a stack
/// is equal to itself and to nothing else.
impl PartialEq for BStack {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self, other)
    }
}

/// Hashes the instance address, consistent with the pointer-identity [`PartialEq`].
impl Hash for BStack {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (self as *const BStack).hash(state);
    }
}

/// A cursor-based reader over a [`BStack`] payload.
///
/// `BStackReader` implements [`io::Read`] and [`io::Seek`], allowing the
/// stack's payload to be consumed through any interface that expects a
/// readable, seekable byte stream.
///
/// # Construction
///
/// ```no_run
/// use bstack::BStack;
///
/// # fn main() -> std::io::Result<()> {
/// let stack = BStack::open("log.bin")?;
/// stack.push(b"hello world")?;
///
/// // Start reading from the beginning.
/// let mut reader = stack.reader();
///
/// // Or start from an arbitrary offset.
/// let mut mid = stack.reader_at(6);
/// # Ok(())
/// # }
/// ```
///
/// # Concurrency
///
/// `BStackReader` borrows the stack immutably, so multiple readers can coexist
/// and run concurrently with each other and with [`peek`](BStack::peek) /
/// [`get`](BStack::get) calls.  Concurrent [`push`](BStack::push) or
/// [`pop`](BStack::pop) operations are not blocked by an active reader, but
/// reading interleaved with writes may observe different snapshots of the
/// payload across calls — callers are responsible for synchronisation when
/// that matters.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct BStackReader<'a> {
    stack: &'a BStack,
    offset: u64,
}

impl BStack {
    /// Create a [`BStackReader`] positioned at the start of the payload.
    pub fn reader(&self) -> BStackReader<'_> {
        BStackReader {
            stack: self,
            offset: 0,
        }
    }

    /// Create a [`BStackReader`] positioned at `offset` bytes into the payload.
    ///
    /// Seeking past the current end is allowed; [`read`](io::Read::read) will
    /// return `Ok(0)` until new data is pushed past that point.
    pub fn reader_at(&self, offset: u64) -> BStackReader<'_> {
        BStackReader {
            stack: self,
            offset,
        }
    }
}

impl<'a> BStackReader<'a> {
    /// Return the current logical read offset within the payload.
    pub fn position(&self) -> u64 {
        self.offset
    }
}

impl<'a> From<&'a BStack> for BStackReader<'a> {
    fn from(stack: &'a BStack) -> Self {
        stack.reader()
    }
}

impl<'a> From<BStackReader<'a>> for &'a BStack {
    fn from(val: BStackReader<'a>) -> Self {
        val.stack
    }
}

impl<'a> PartialOrd for BStackReader<'a> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Ordered by `BStack` instance address, then by cursor `offset`.
///
/// The address component groups all readers over the same stack together,
/// and within that group the natural read order (smaller offset first) applies.
/// This ordering is consistent with the pointer-identity [`PartialEq`].
impl<'a> Ord for BStackReader<'a> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let self_ptr = self.stack as *const BStack as usize;
        let other_ptr = other.stack as *const BStack as usize;
        self_ptr
            .cmp(&other_ptr)
            .then(self.offset.cmp(&other.offset))
    }
}

impl<'a> io::Read for BStackReader<'a> {
    /// Read bytes from the current position into `buf`.
    ///
    /// Returns the number of bytes read, which may be less than `buf.len()` if
    /// the end of the payload is reached.  Returns `Ok(0)` at EOF.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let data_size = self.stack.len()?;
        if self.offset >= data_size {
            return Ok(0);
        }
        let available = (data_size - self.offset) as usize;
        let n = buf.len().min(available);
        self.stack.get_into(self.offset, &mut buf[..n])?;
        self.offset += n as u64;
        Ok(n)
    }
}

impl<'a> io::Seek for BStackReader<'a> {
    /// Move the read cursor.
    ///
    /// [`SeekFrom::Start`] and [`SeekFrom::Current`] with a non-negative delta
    /// may advance the cursor past the current end of the payload; subsequent
    /// [`read`](io::Read::read) calls will return `Ok(0)` until the payload
    /// grows past that point.  Seeking before the start of the payload returns
    /// [`io::ErrorKind::InvalidInput`].
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let data_size = self.stack.len()? as i128;
        let new_offset = match pos {
            SeekFrom::Start(n) => n as i128,
            SeekFrom::End(n) => data_size + n as i128,
            SeekFrom::Current(n) => self.offset as i128 + n as i128,
        };
        if new_offset < 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "seek before beginning of payload",
            ));
        }
        self.offset = new_offset as u64;
        Ok(self.offset)
    }
}