bitsandbytes 0.2.1

An owned, bit-aware binary codec: fast bit/byte field types and the unified #[bin] macro.
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
//! A bit-level stream codec — read/write fields at arbitrary *bit* offsets, not
//! just byte boundaries.
//!
//! A byte-oriented `Read + Seek` codec can only address byte boundaries, so a field
//! that starts mid-byte (a 108-bit DMR payload, a 48-bit sync pattern) forces
//! hand-rolled backward seeks and nibble shifts.
//! [`BitReader`]/[`BitWriter`] track a **bit** cursor over a byte buffer and
//! read/write any [`Bits`] value (`u1`..`u127`, `#[bitfield]`, `#[derive(BitEnum)]`)
//! directly — bit-aware *and* fast (shift/mask, no `bitvec`).
//!
//! The wire [`Layout`] is configurable: bit order (MSB-first default — bit 0 is the
//! high bit of byte 0, the RFC/ETSI convention — or LSB-first) and byte order (big-
//! endian default, or little-endian for byte-multiple values).
//!
//! ```
//! use bnb::{u4, u12, BitReader, BitWriter};
//!
//! // Pack a 4-bit then a 12-bit field into a 16-bit (2-byte) stream.
//! let mut w = BitWriter::new();
//! w.write(u4::new(0xA)).unwrap();
//! w.write(u12::new(0xBCD)).unwrap();
//! let bytes = w.into_bytes();
//! assert_eq!(bytes, [0xAB, 0xCD]);
//!
//! let mut r = BitReader::new(&bytes);
//! assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA));
//! assert_eq!(r.read::<u12>().unwrap(), u12::new(0xBCD));
//! ```

use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;

use crate::field::{BitOrder, Bits, ByteOrder};

/// A position-aware bit-codec error (it carries a span-like position). It records the
/// **bit offset** where decoding/encoding failed and, when the derive can supply it,
/// the **field** being processed.
///
/// # Examples
///
/// ```
/// use bnb::{bin, ErrorKind};
///
/// #[bin(big)]
/// #[derive(Debug)]
/// struct Pair { a: u16, b: u16 }
///
/// let err = Pair::decode_exact(&[0x00]).unwrap_err(); // only one byte of four
/// assert_eq!(err.at, 0);             // the bit offset where it failed
/// assert_eq!(err.field, Some("a"));  // the field being read (the span)
/// assert!(matches!(err.kind, ErrorKind::UnexpectedEof { .. }));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BitError {
    /// The cause.
    pub kind: ErrorKind,
    /// Absolute bit offset where the error occurred.
    pub at: usize,
    /// The field being decoded/encoded when it occurred, if recorded by the
    /// derive (the innermost field — the "span"). `None` for low-level reader
    /// errors with no field context.
    pub field: Option<&'static str>,
}

/// The cause of a [`BitError`]. Non-exhaustive: later phases add variants
/// (`BadMagic`, …).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Ran past the end of a finite input (a slice): `needed` bits were requested,
    /// `remaining` were left. Definitive — distinct from [`Incomplete`](ErrorKind::Incomplete).
    UnexpectedEof {
        /// Bits requested.
        needed: usize,
        /// Bits still available.
        remaining: usize,
    },
    /// A streaming source ([`StreamBitReader`]) ran out mid-message: the caller
    /// should read more bytes and retry. `needed` is a best-effort byte hint
    /// (`None` when unknown). See [`BitError::is_incomplete`].
    Incomplete {
        /// Best-effort estimate of additional bytes needed, if known.
        needed: Option<usize>,
    },
    /// `decode_exact` left whole bytes unconsumed after the message.
    TrailingBytes {
        /// Number of trailing bytes.
        remaining: usize,
    },
    /// A single field exceeded the 128-bit carrier width.
    TooWide {
        /// The offending width.
        width: usize,
    },
    /// An I/O error while encoding to a [`std::io::Write`] sink (the `std` feature).
    #[cfg(feature = "std")]
    Io(std::io::ErrorKind),
    /// A `magic` constant read off the wire did not match. Both values are the
    /// type-erased low-bit representations ([`Bits::into_bits`]).
    BadMagic {
        /// The constant the codec expected.
        expected: u128,
        /// The value actually read.
        found: u128,
    },
    /// A `try_map` conversion from the wire representation failed; `message` is the
    /// converter's `Display` output.
    Convert {
        /// The converter's error, rendered.
        message: String,
    },
    /// A position directive (`restore_position`/seek) ran on a non-seekable
    /// [`Source`] (a forward-only stream). Decode from a slice ([`BitReader`]) or a
    /// seekable source instead.
    NotSeekable,
    /// A [`BufSource`] hit its retention cap before the message finished — the
    /// framed message is larger than the configured bound (never unbounded).
    BufferFull {
        /// The cap, in bytes.
        cap: usize,
    },
}

impl BitError {
    /// Builds an error at absolute bit offset `at`, with no field recorded yet.
    #[must_use]
    pub fn new(kind: ErrorKind, at: usize) -> Self {
        Self {
            kind,
            at,
            field: None,
        }
    }

    /// Builds a [`ErrorKind::BadMagic`] error (a `magic` constant mismatched) at
    /// absolute bit offset `at`. `expected`/`found` are the type-erased low-bit
    /// values ([`Bits::into_bits`]).
    #[must_use]
    pub fn bad_magic(expected: u128, found: u128, at: usize) -> Self {
        Self::new(ErrorKind::BadMagic { expected, found }, at)
    }

    /// Builds a [`ErrorKind::Convert`] error (a `try_map` conversion failed) at
    /// absolute bit offset `at`.
    #[must_use]
    pub fn convert(message: String, at: usize) -> Self {
        Self::new(ErrorKind::Convert { message }, at)
    }

    /// Records the field being processed, **if one is not already set** — so the
    /// innermost field (set first as the error propagates up) wins. The derive
    /// calls this per field.
    #[must_use]
    pub fn in_field(mut self, field: &'static str) -> Self {
        if self.field.is_none() {
            self.field = Some(field);
        }
        self
    }

    /// Whether this is the streaming "need more bytes" signal
    /// ([`ErrorKind::Incomplete`]) — the caller should read more and retry, as
    /// opposed to a definitive parse failure.
    #[must_use]
    pub fn is_incomplete(&self) -> bool {
        matches!(self.kind, ErrorKind::Incomplete { .. })
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for BitError {
    /// Wraps a [`std::io::Error`] as [`ErrorKind::Io`] — so a `parse_with`/`write_with`
    /// using [`Source::as_read`]/[`Sink::as_write`] can `?` `std::io` results straight
    /// into a `BitError`. The bit offset is unknown at this boundary (recorded as `0`);
    /// build with [`BitError::new`] if you need the precise position.
    fn from(e: std::io::Error) -> Self {
        BitError::new(ErrorKind::Io(e.kind()), 0)
    }
}

impl fmt::Display for BitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::UnexpectedEof { needed, remaining } => write!(
                f,
                "unexpected end of input: needed {needed} bits, {remaining} remain"
            )?,
            ErrorKind::Incomplete { needed } => match needed {
                Some(n) => write!(f, "incomplete: need ~{n} more bytes")?,
                None => write!(f, "incomplete: need more bytes")?,
            },
            ErrorKind::TrailingBytes { remaining } => {
                write!(f, "{remaining} trailing bytes after the message")?;
            }
            ErrorKind::TooWide { width } => {
                write!(f, "field width {width} exceeds the 128-bit carrier")?;
            }
            #[cfg(feature = "std")]
            ErrorKind::Io(kind) => write!(f, "I/O error: {kind:?}")?,
            ErrorKind::BadMagic { expected, found } => {
                write!(f, "bad magic: expected {expected:#x}, found {found:#x}")?;
            }
            ErrorKind::Convert { message } => {
                write!(f, "conversion failed: {message}")?;
            }
            ErrorKind::NotSeekable => {
                write!(f, "a position directive ran on a non-seekable source")?;
            }
            ErrorKind::BufferFull { cap } => {
                write!(f, "buffered source exceeded its {cap}-byte cap")?;
            }
        }
        write!(f, " at bit {}", self.at)?;
        if let Some(field) = self.field {
            write!(f, " (field `{field}`)")?;
        }
        Ok(())
    }
}

impl core::error::Error for BitError {}

impl From<crate::error::Error> for BitError {
    /// Bridges a construction error (e.g. `UInt::try_new`) into a codec error, so it
    /// `?`-propagates inside a custom `parse_with`/`write_with` fn or a converter
    /// that returns [`BitError`]. The offset is unknown (`0`) — the codec's own
    /// reads/writes carry the real bit offset; this is only for borrowed construction
    /// failures with no cursor context.
    #[inline]
    fn from(e: crate::error::Error) -> Self {
        BitError::convert(e.to_string(), 0)
    }
}

/// The bit width of a [`Bits`] value's type. Generated `BIT_LEN` consts and the
/// alignment guard call this to size a `magic` constant whose type they only have
/// as an expression (the value is taken by reference purely to infer `T`).
#[doc(hidden)]
#[must_use]
pub const fn bits_of<T: Bits>(_value: &T) -> u32 {
    T::BITS
}

/// Reads a `magic` constant and verifies it equals `expected`, compared as
/// type-erased bits (so `T` needs only [`Bits`] — no `Copy`/`PartialEq`, and `T`
/// is pinned by the argument so the generated call site needs no turbofish). On
/// mismatch: [`ErrorKind::BadMagic`] at the magic's offset.
#[doc(hidden)]
pub fn verify_magic<T: Bits, S: Source>(r: &mut S, expected: T) -> Result<(), BitError> {
    let at = r.bit_pos();
    let found: T = r.read()?;
    let (e, g) = (expected.into_bits(), found.into_bits());
    if e != g {
        return Err(BitError::bad_magic(e, g, at));
    }
    Ok(())
}

/// Reads a wire value `W` (inferred from `f`'s argument type) and maps it to the
/// field type `T` — backs `#[br(map = …)]`.
///
/// # Errors
/// Propagates the read [`BitError`].
#[doc(hidden)]
pub fn read_mapped<W, T, S, F>(r: &mut S, f: F) -> Result<T, BitError>
where
    W: Bits,
    S: Source,
    F: FnOnce(W) -> T,
{
    let raw: W = r.read()?;
    Ok(f(raw))
}

/// Fallible variant — backs `#[br(try_map = …)]`. A conversion error becomes an
/// [`ErrorKind::Convert`] at the value's offset.
///
/// # Errors
/// The read [`BitError`], or the converter's failure as [`ErrorKind::Convert`].
#[doc(hidden)]
pub fn read_try_mapped<W, T, E, S, F>(r: &mut S, f: F) -> Result<T, BitError>
where
    W: Bits,
    S: Source,
    E: fmt::Display,
    F: FnOnce(W) -> Result<T, E>,
{
    let at = r.bit_pos();
    let raw: W = r.read()?;
    f(raw).map_err(|e| BitError::convert(e.to_string(), at))
}

/// Maps the field `T` to its wire value `W` and writes it — backs `#[bw(map = …)]`.
///
/// # Errors
/// Propagates the write [`BitError`].
#[doc(hidden)]
pub fn write_mapped<W, T, K, F>(w: &mut K, value: &T, f: F) -> Result<(), BitError>
where
    W: Bits,
    K: Sink,
    F: FnOnce(&T) -> W,
{
    w.write(f(value))
}

/// Decodes a whole wire **message** `W` (a `BitDecode`, inferred from `f`'s argument) and
/// maps it to the logical type — backs struct-level `#[bin(map = …)]`. The message dual of
/// [`read_mapped`] (whose `W` is a single `Bits` field).
///
/// # Errors
/// Propagates the decode [`BitError`].
#[doc(hidden)]
pub fn decode_mapped_msg<W, T, S, F>(r: &mut S, f: F) -> Result<T, BitError>
where
    W: BitDecode,
    S: Source,
    F: FnOnce(W) -> T,
{
    Ok(f(W::bit_decode(r)?))
}

/// Fallible message map — backs struct-level `#[bin(try_map = …)]`. A conversion error
/// becomes an [`ErrorKind::Convert`] at the message's start offset.
///
/// # Errors
/// The decode [`BitError`], or the converter's failure as [`ErrorKind::Convert`].
#[doc(hidden)]
pub fn decode_try_mapped_msg<W, T, E, S, F>(r: &mut S, f: F) -> Result<T, BitError>
where
    W: BitDecode,
    S: Source,
    E: fmt::Display,
    F: FnOnce(W) -> Result<T, E>,
{
    let at = r.bit_pos();
    let w = W::bit_decode(r)?;
    f(w).map_err(|e| BitError::convert(e.to_string(), at))
}

/// Maps the logical type to its wire **message** `W` (a `BitEncode`) and encodes it —
/// backs struct-level `#[bin(bw_map = …)]`. The message dual of [`write_mapped`].
///
/// # Errors
/// Propagates the encode [`BitError`].
#[doc(hidden)]
pub fn encode_mapped_msg<W, T, K, F>(w: &mut K, value: &T, f: F) -> Result<(), BitError>
where
    W: BitEncode,
    K: Sink,
    F: FnOnce(&T) -> W,
{
    f(value).bit_encode(w)
}

/// A typed bit/byte amount for positioning directives — `4.bits()`, `3.bytes()` —
/// resolving to a bit count. Bring it in with `use bnb::prelude::*`.
///
/// # Examples
///
/// ```
/// use bnb::prelude::*;
/// assert_eq!(4u32.bits(), 4);
/// assert_eq!(3u32.bytes(), 24);
/// ```
///
/// Used by the positioning directives, e.g. `#[br(pad_before = 2u32.bytes())]` — see
/// [`guide::directives`](crate::guide::directives).
pub trait BitAmount: Copy {
    /// This many **bits**.
    fn bits(self) -> u32;
    /// This many **bytes** (× 8 bits).
    fn bytes(self) -> u32;
}

macro_rules! impl_bit_amount {
    ($($t:ty),*) => {$(
        impl BitAmount for $t {
            fn bits(self) -> u32 { self as u32 }
            fn bytes(self) -> u32 { (self as u32) * 8 }
        }
    )*};
}
impl_bit_amount!(u8, u16, u32, u64, usize, i16, i32, i64, isize);

/// Skips `bits` forward (consuming and discarding) — backs `#[br(pad_before/after)]`.
///
/// # Errors
/// Propagates the source's [`BitError`].
#[doc(hidden)]
pub fn skip_read<S: Source>(r: &mut S, bits: u32) -> Result<(), BitError> {
    let mut left = bits;
    while left > 0 {
        let n = left.min(128);
        r.read_bits(n)?;
        left -= n;
    }
    Ok(())
}

/// Writes `bits` zero bits forward — the write dual of [`skip_read`].
///
/// # Errors
/// Propagates the sink's [`BitError`].
#[doc(hidden)]
pub fn skip_write<K: Sink>(w: &mut K, bits: u32) -> Result<(), BitError> {
    let mut left = bits;
    while left > 0 {
        let n = left.min(128);
        w.write_bits(0, n)?;
        left -= n;
    }
    Ok(())
}

/// Skips forward to the next byte boundary — backs `#[br(align_before/after)]`.
///
/// # Errors
/// Propagates the source's [`BitError`].
#[doc(hidden)]
pub fn align_read<S: Source>(r: &mut S) -> Result<(), BitError> {
    let pad = (8 - (r.bit_pos() % 8)) % 8;
    skip_read(r, pad as u32)
}

/// Pads with zero bits to the next byte boundary — the write dual of [`align_read`].
///
/// # Errors
/// Propagates the sink's [`BitError`].
#[doc(hidden)]
pub fn align_write<K: Sink>(w: &mut K) -> Result<(), BitError> {
    let pad = (8 - (w.bit_pos() % 8)) % 8;
    skip_write(w, pad as u32)
}

/// The wire layout: bit packing order **and** byte order, threaded through the
/// cursors and entry points. `#[bin(big|little)]` and `#[bin(bit_order = msb|lsb)]`
/// set it; the default is MSB-first, big-endian (RFC/network order).
///
/// # Examples
///
/// ```
/// use bnb::{BitReader, BitOrder, ByteOrder, Layout};
///
/// // Read a 16-bit value little-endian instead of the default big-endian.
/// let layout = Layout { bit: BitOrder::Msb, byte: ByteOrder::Little };
/// let mut r = BitReader::with_layout(&[0x34, 0x12], layout);
/// assert_eq!(r.read::<u16>().unwrap(), 0x1234);
/// assert_eq!(Layout::default(), Layout { bit: BitOrder::Msb, byte: ByteOrder::Big });
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Layout {
    /// Bit packing order — does the first bit land in the high or low bit.
    pub bit: BitOrder,
    /// Byte order, applied to byte-multiple values.
    pub byte: ByteOrder,
}

/// Reverses the low `bits / 8` bytes of `raw` when the declared byte order differs from the
/// bit order's **natural** layout, and the width is a whole number of bytes (byte order
/// applies only to byte-multiple values); a no-op otherwise. It is its own inverse, so read
/// and write share it.
///
/// The natural layout is what the bit cursor produces with no transform: MSB-first emits a
/// value's high bits first, so its bytes land **big-endian**; LSB-first emits low bits first,
/// so its bytes land **little-endian** (bit *k* of the value goes to stream bit *k* — exactly
/// the DBC/"Intel" layout `raw |= v << start; frame = raw.to_le_bytes()`). So the transform
/// swaps only for `Msb`+`Little` and `Lsb`+`Big`; `Msb`+`Big` (network order) and
/// `Lsb`+`Little` (DBC Intel, SMB) are identities. See `DESIGN.md` § byte order × bit order.
#[inline]
fn apply_byte_order(raw: u128, bits: u32, bit: BitOrder, byte: ByteOrder) -> u128 {
    let natural = match bit {
        BitOrder::Msb => ByteOrder::Big,
        BitOrder::Lsb => ByteOrder::Little,
    };
    if byte == natural || bits % 8 != 0 {
        return raw;
    }
    let n = (bits / 8) as usize;
    let le = raw.to_le_bytes();
    let mut out = 0u128;
    let mut i = 0;
    while i < n {
        out |= (le[i] as u128) << (8 * (n - 1 - i));
        i += 1;
    }
    out
}

/// Extracts `n` (`<= 128`) bits starting at absolute bit offset `pos` from `buf`, in
/// `order`, returned right-aligned in a `u128` (byte order is applied separately by
/// `read`). The single bit-extraction routine behind every slice-backed [`Source`]
/// ([`BitReader`], [`BufSource`], [`SeekReader`]). The caller must have bounds-checked
/// `pos + n <= buf.len() * 8` and `n <= 128`.
///
/// **Fast path:** when the read is byte-aligned (`pos % 8 == 0` and `n % 8 == 0`) the
/// bytes are accumulated whole — one iteration per byte, not per bit (≈8× fewer).
#[inline]
fn extract_bits(buf: &[u8], pos: usize, n: usize, order: BitOrder) -> u128 {
    if pos % 8 == 0 && n % 8 == 0 {
        let start = pos / 8;
        let nbytes = n / 8;
        let mut acc = 0u128;
        match order {
            // MSB-first byte-aligned == big-endian byte concatenation.
            BitOrder::Msb => {
                for j in 0..nbytes {
                    acc = (acc << 8) | u128::from(buf[start + j]);
                }
            }
            // LSB-first byte-aligned == little-endian byte concatenation.
            BitOrder::Lsb => {
                for j in 0..nbytes {
                    acc |= u128::from(buf[start + j]) << (8 * j);
                }
            }
        }
        return acc;
    }
    // General path: one bit at a time (handles sub-byte offsets/widths).
    let mut acc = 0u128;
    match order {
        BitOrder::Msb => {
            for k in 0..n {
                let p = pos + k;
                acc = (acc << 1) | u128::from((buf[p >> 3] >> (7 - (p & 7))) & 1);
            }
        }
        BitOrder::Lsb => {
            for k in 0..n {
                let p = pos + k;
                acc |= u128::from((buf[p >> 3] >> (p & 7)) & 1) << k;
            }
        }
    }
    acc
}

/// Appends the low `n` (`<= 128`) bits of `value` to `out` at absolute bit offset
/// `bit_pos`, in `order` — the write dual of [`extract_bits`], used by [`BitWriter`].
///
/// **Fast path:** when appending byte-aligned at the end (`bit_pos % 8 == 0`,
/// `n % 8 == 0`, cursor at `out.len()`) the bytes are pushed whole, one per byte.
#[inline]
fn emit_bits(out: &mut Vec<u8>, bit_pos: usize, value: u128, n: usize, order: BitOrder) {
    if n % 8 == 0 && bit_pos % 8 == 0 && bit_pos / 8 == out.len() {
        let nbytes = n / 8;
        match order {
            BitOrder::Msb => {
                for j in 0..nbytes {
                    out.push((value >> (8 * (nbytes - 1 - j))) as u8);
                }
            }
            BitOrder::Lsb => {
                for j in 0..nbytes {
                    out.push((value >> (8 * j)) as u8);
                }
            }
        }
        return;
    }
    for k in 0..n {
        let p = bit_pos + k;
        // MSB-first emits the field's high bit first (i = n-1-k); LSB-first emits its
        // low bit first (i = k) into the byte's low bit.
        let (i, shift) = match order {
            BitOrder::Msb => (n - 1 - k, 7 - (p & 7)),
            BitOrder::Lsb => (k, p & 7),
        };
        let byte_idx = p >> 3;
        if byte_idx == out.len() {
            out.push(0);
        }
        if (value >> i) & 1 != 0 {
            out[byte_idx] |= 1 << shift;
        }
    }
}

/// A cursor that reads values at arbitrary bit offsets from a byte slice, in a
/// chosen [`BitOrder`] (MSB-first by default — `bit 0` is the high bit of byte 0,
/// the RFC/ETSI ASCII-art convention; LSB-first for serial/PHY layers).
///
/// # Examples
///
/// ```
/// use bnb::{BitReader, u4, u12};
///
/// let mut r = BitReader::new(&[0xAB, 0xCD]);
/// assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA)); // 4 bits
/// assert_eq!(r.read::<u12>().unwrap(), u12::new(0xBCD)); // the next 12, straddling a byte
/// assert_eq!(r.remaining_bits(), 0);
/// ```
#[derive(Clone, Debug)]
pub struct BitReader<'a> {
    bytes: &'a [u8],
    bit_pos: usize,
    order: BitOrder,
    byte: ByteOrder,
}

impl<'a> BitReader<'a> {
    /// Wraps `bytes`, positioned at bit 0, **MSB-first**, big-endian.
    #[must_use]
    pub fn new(bytes: &'a [u8]) -> Self {
        Self::with_order(bytes, BitOrder::Msb)
    }

    /// Wraps `bytes`, positioned at bit 0, in the given bit order (big-endian).
    #[must_use]
    pub fn with_order(bytes: &'a [u8], order: BitOrder) -> Self {
        Self::with_layout(
            bytes,
            Layout {
                bit: order,
                byte: ByteOrder::Big,
            },
        )
    }

    /// Wraps `bytes`, positioned at bit 0, in the given [`Layout`] (bit + byte order).
    #[must_use]
    pub fn with_layout(bytes: &'a [u8], layout: Layout) -> Self {
        Self {
            bytes,
            bit_pos: 0,
            order: layout.bit,
            byte: layout.byte,
        }
    }

    /// The current absolute bit offset.
    #[must_use]
    pub fn bit_pos(&self) -> usize {
        self.bit_pos
    }

    /// Bits not yet consumed.
    #[must_use]
    pub fn remaining_bits(&self) -> usize {
        self.bytes.len() * 8 - self.bit_pos
    }

    /// Reads `n` (`<= 128`) bits into the low bits of a `u128`, in the reader's
    /// bit order (MSB-first by default).
    ///
    /// # Errors
    /// [`ErrorKind::TooWide`] if `n > 128`; [`ErrorKind::UnexpectedEof`] if fewer
    /// than `n` bits remain. Either carries the current bit offset.
    #[inline]
    pub fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        let n = n as usize;
        if n > 128 {
            return Err(BitError::new(ErrorKind::TooWide { width: n }, self.bit_pos));
        }
        if n > self.remaining_bits() {
            return Err(BitError::new(
                ErrorKind::UnexpectedEof {
                    needed: n,
                    remaining: self.remaining_bits(),
                },
                self.bit_pos,
            ));
        }
        let acc = extract_bits(self.bytes, self.bit_pos, n, self.order);
        self.bit_pos += n;
        Ok(acc)
    }

    /// Reads one [`Bits`] value of its declared width, applying the byte order to a
    /// byte-multiple value.
    ///
    /// # Errors
    /// As [`read_bits`](Self::read_bits).
    #[inline]
    pub fn read<T: Bits>(&mut self) -> Result<T, BitError> {
        let raw = self.read_bits(T::BITS)?;
        Ok(T::from_bits(apply_byte_order(
            raw,
            T::BITS,
            self.order,
            self.byte,
        )))
    }

    /// Moves the cursor to absolute bit `pos`. This needs no `Seek` trait — the whole
    /// buffer is in hand, so a seek is just cursor arithmetic. (Enables e.g. DNS
    /// name-compression pointers.)
    ///
    /// # Errors
    /// [`ErrorKind::UnexpectedEof`] if `pos` is past the end of the buffer.
    pub fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
        let end = self.bytes.len() * 8;
        if pos > end {
            return Err(BitError::new(
                ErrorKind::UnexpectedEof {
                    needed: pos,
                    remaining: end,
                },
                self.bit_pos,
            ));
        }
        self.bit_pos = pos;
        Ok(())
    }

    /// Advances the cursor to the next byte boundary (a no-op if already aligned).
    pub fn align_to_byte(&mut self) {
        self.bit_pos = (self.bit_pos + 7) & !7;
    }
}

/// A sink that appends values at arbitrary bit offsets in a chosen [`BitOrder`]
/// (MSB-first by default), growing a byte buffer (the final partial byte is
/// zero-padded).
///
/// # Examples
///
/// ```
/// use bnb::{BitWriter, u4, u12};
///
/// let mut w = BitWriter::new();
/// w.write(u4::new(0xA)).unwrap();
/// w.write(u12::new(0xBCD)).unwrap();
/// assert_eq!(w.bit_len(), 16);
/// assert_eq!(w.into_bytes(), [0xAB, 0xCD]);
/// ```
#[derive(Default)]
pub struct BitWriter {
    bytes: Vec<u8>,
    bit_pos: usize,
    order: BitOrder,
    byte: ByteOrder,
    /// Optional per-encode scratch (see [`Sink::scratch`]); not part of the written bytes.
    scratch: Option<Box<dyn Any>>,
}

// Hand-written so the public `Clone`/`Debug` API survives the (un-`Clone`, un-`Debug`)
// `scratch` slot. Cloning starts a fresh encode session, so the scratch is **not**
// carried (a clone gets `None`); `Debug` reports only its presence.
impl Clone for BitWriter {
    fn clone(&self) -> Self {
        Self {
            bytes: self.bytes.clone(),
            bit_pos: self.bit_pos,
            order: self.order,
            byte: self.byte,
            scratch: None,
        }
    }
}

impl fmt::Debug for BitWriter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BitWriter")
            .field("bytes", &self.bytes)
            .field("bit_pos", &self.bit_pos)
            .field("order", &self.order)
            .field("byte", &self.byte)
            .field("scratch", &self.scratch.is_some())
            .finish()
    }
}

impl BitWriter {
    /// An empty **MSB-first**, big-endian writer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// An empty writer in the given bit order (big-endian).
    #[must_use]
    pub fn with_order(order: BitOrder) -> Self {
        Self::with_layout(Layout {
            bit: order,
            byte: ByteOrder::Big,
        })
    }

    /// An empty writer in the given [`Layout`] (bit + byte order).
    #[must_use]
    pub fn with_layout(layout: Layout) -> Self {
        Self {
            bytes: Vec::new(),
            bit_pos: 0,
            order: layout.bit,
            byte: layout.byte,
            scratch: None,
        }
    }

    /// Attach a type-erased **scratch** value, reachable from any codec during the encode
    /// via [`Sink::scratch`] and recovered by [`downcast_mut`](Any::downcast_mut).
    ///
    /// The escape hatch for codecs that need mutable state shared across a whole message's
    /// fields — a back-reference / compression dictionary (e.g. DNS name compression). The
    /// scratch lives for the encode and is dropped by [`into_bytes`](Self::into_bytes); it
    /// is never written to the output and is not carried by [`Clone`].
    ///
    /// ```
    /// use bnb::{BitWriter, Sink};
    ///
    /// let mut w = BitWriter::new().with_scratch(Box::new(0u32));
    /// if let Some(n) = w.scratch().and_then(|s| s.downcast_mut::<u32>()) {
    ///     *n += 1;
    /// }
    /// assert_eq!(w.scratch().and_then(|s| s.downcast_ref::<u32>()), Some(&1));
    /// ```
    #[must_use]
    pub fn with_scratch(mut self, scratch: Box<dyn Any>) -> Self {
        self.scratch = Some(scratch);
        self
    }

    /// Bits written so far.
    #[must_use]
    pub fn bit_len(&self) -> usize {
        self.bit_pos
    }

    /// Appends the low `n` (`<= 128`) bits of `value`, in the writer's bit order.
    ///
    /// # Errors
    /// [`ErrorKind::TooWide`] if `n > 128`.
    #[inline]
    pub fn write_bits(&mut self, value: u128, n: u32) -> Result<(), BitError> {
        let n = n as usize;
        if n > 128 {
            return Err(BitError::new(ErrorKind::TooWide { width: n }, self.bit_pos));
        }
        emit_bits(&mut self.bytes, self.bit_pos, value, n, self.order);
        self.bit_pos += n;
        Ok(())
    }

    /// Appends one [`Bits`] value of its declared width, applying the byte order to
    /// a byte-multiple value.
    ///
    /// # Errors
    /// As [`write_bits`](Self::write_bits).
    #[inline]
    pub fn write<T: Bits>(&mut self, value: T) -> Result<(), BitError> {
        let raw = apply_byte_order(value.into_bits(), T::BITS, self.order, self.byte);
        self.write_bits(raw, T::BITS)
    }

    /// Consumes the writer, returning the packed bytes.
    #[must_use]
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

/// A bit-level **input** the codec recurses over. Implemented by [`BitReader`]
/// (in-memory slice), [`StreamBitReader`] (forward `Read`), [`BufSource`] (a
/// retain-and-seek socket adapter), and [`SeekReader`] (`Read + Seek`); the codec is
/// generic over `Source`, so one decoder runs over any of them — see
/// [`guide::io`](crate::guide::io).
///
/// # Examples
///
/// ```
/// use bnb::{BitReader, Source, u4};
///
/// // A reader generic over any `Source`.
/// fn first_nibble<S: Source>(s: &mut S) -> u4 { s.read().unwrap() }
///
/// let mut r = BitReader::new(&[0xA5]);
/// assert_eq!(first_nibble(&mut r), u4::new(0xA));
/// ```
pub trait Source {
    /// Reads `n` (`<= 128`) bits into the low bits of a `u128`, in the source's
    /// bit order (MSB-first by default).
    ///
    /// # Errors
    /// Propagates the reader's [`BitError`].
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError>;

    /// The current absolute bit offset (for position-aware errors).
    fn bit_pos(&self) -> usize;

    /// The byte order applied to a byte-multiple value (default big-endian).
    fn byte_order(&self) -> ByteOrder {
        ByteOrder::Big
    }

    /// The bit order this source reads in (default MSB-first). Paired with
    /// [`byte_order`](Source::byte_order) to decide whether a byte-multiple value needs its
    /// bytes swapped — each bit order has a *natural* byte layout (big-endian under MSB,
    /// little-endian under LSB), and only the opposite declaration swaps.
    fn bit_order(&self) -> BitOrder {
        BitOrder::Msb
    }

    /// Moves the cursor to absolute bit `pos`. The default — for a forward-only
    /// source — fails with [`ErrorKind::NotSeekable`]; seekable sources (the slice
    /// [`BitReader`]) override it. A [`SeekSource`] guarantees this works.
    ///
    /// # Errors
    /// [`ErrorKind::NotSeekable`] unless the source is seekable.
    fn seek_to_bit(&mut self, _pos: usize) -> Result<(), BitError> {
        Err(BitError::new(ErrorKind::NotSeekable, self.bit_pos()))
    }

    /// Reads one [`Bits`] value of its declared width, applying the byte order.
    ///
    /// # Errors
    /// As [`read_bits`](Source::read_bits).
    #[inline]
    fn read<T: Bits>(&mut self) -> Result<T, BitError> {
        let raw = self.read_bits(T::BITS)?;
        Ok(T::from_bits(apply_byte_order(
            raw,
            T::BITS,
            self.bit_order(),
            self.byte_order(),
        )))
    }

    /// Reads `n` bytes into a fresh `Vec` (at any bit offset — the bytes need not be
    /// aligned). The bulk form of the per-byte `read::<u8>()` loop, for blob/payload
    /// reads in custom codecs and container formats.
    ///
    /// `n` is often attacker-controlled, so **nothing is pre-allocated from it**: bytes
    /// are pushed as they are read, bounded by the input — a hostile huge `n` against a
    /// short source is a fast [`UnexpectedEof`](ErrorKind::UnexpectedEof), not an
    /// allocation. (An implementation may override with a byte-aligned fast path; the
    /// default is the correct-first per-byte loop.)
    ///
    /// # Errors
    /// As [`read_bits`](Source::read_bits).
    fn read_bytes(&mut self, n: usize) -> Result<alloc::vec::Vec<u8>, BitError> {
        let mut v = alloc::vec::Vec::new();
        for _ in 0..n {
            v.push(self.read::<u8>()?);
        }
        Ok(v)
    }

    /// Fills `buf` with bytes from the source — the no-alloc dual of
    /// [`read_bytes`](Source::read_bytes), for fixed scratch buffers and tight
    /// `no_std` paths.
    ///
    /// # Errors
    /// As [`read_bits`](Source::read_bits).
    fn read_into(&mut self, buf: &mut [u8]) -> Result<(), BitError> {
        for slot in buf.iter_mut() {
            *slot = self.read::<u8>()?;
        }
        Ok(())
    }

    /// Borrows this source as a [`std::io::Read`] over its bytes — for handing the
    /// cursor to `std::io`-based code from a `#[br(parse_with = …)]` (e.g. a decoder, or
    /// a `Read`-based parser). Reads 8 bits per byte; see [`SourceReader`]. Only with
    /// the `std` feature.
    #[cfg(feature = "std")]
    fn as_read(&mut self) -> SourceReader<'_, Self>
    where
        Self: Sized,
    {
        SourceReader(self)
    }
}

/// A [`std::io::Read`] view over a [`Source`], from [`Source::as_read`]. Each `read`
/// pulls 8 bits per byte through [`Source::read_bits`], so it works at any bit
/// alignment (you will normally be byte-aligned). A read failure surfaces as an
/// `io::Error` when no bytes were produced, or ends the read short once some were — the
/// `std::io` convention. This is the outbound dual of [`BufSource`]/[`SeekReader`] (which
/// adapt a `std::io::Read` *into* a `Source`).
#[cfg(feature = "std")]
pub struct SourceReader<'a, S: Source>(&'a mut S);

#[cfg(feature = "std")]
impl<S: Source> std::io::Read for SourceReader<'_, S> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        for (i, slot) in buf.iter_mut().enumerate() {
            match self.0.read_bits(8) {
                Ok(b) => *slot = b as u8,
                Err(e) if i == 0 => {
                    // Map the actual failure — only a genuine end-of-input is `UnexpectedEof`;
                    // a non-EOF error (e.g. `NotSeekable`, `Convert`) must not masquerade as one.
                    let kind = match e.kind {
                        ErrorKind::UnexpectedEof { .. } | ErrorKind::Incomplete { .. } => {
                            std::io::ErrorKind::UnexpectedEof
                        }
                        _ => std::io::ErrorKind::InvalidData,
                    };
                    return Err(std::io::Error::new(kind, e.to_string()));
                }
                Err(_) => return Ok(i),
            }
        }
        Ok(buf.len())
    }
}

/// A [`Source`] that can seek (its [`seek_to_bit`](Source::seek_to_bit) is real, not
/// the failing default). A `#[bin]` message that uses `restore_position` bounds its
/// generated `decode` on this trait, so a forward-only stream is rejected at
/// compile time. Implemented by [`BitReader`], [`BufSource`], and [`SeekReader`]
/// (and, with the `bytes` feature, `BytesReader`).
pub trait SeekSource: Source {}

impl SeekSource for BitReader<'_> {}

/// A bit-level **output** the codec writes to — the in-memory [`BitWriter`]
/// (and, under the `bytes` feature, `BytesWriter`). Encode to any
/// [`std::io::Write`] via a message's generated `encode` method.
///
/// # Examples
///
/// ```
/// use bnb::{BitWriter, Sink, u4};
///
/// // A writer generic over any `Sink`.
/// fn put_nibble<K: Sink>(k: &mut K, v: u4) { k.write(v).unwrap(); }
///
/// let mut w = BitWriter::new();
/// put_nibble(&mut w, u4::new(0xA));
/// put_nibble(&mut w, u4::new(0x5));
/// assert_eq!(w.into_bytes(), [0xA5]);
/// ```
pub trait Sink {
    /// Appends the low `n` (`<= 128`) bits of `value`, in the sink's bit order
    /// (MSB-first by default).
    ///
    /// # Errors
    /// Propagates the writer's [`BitError`].
    fn write_bits(&mut self, value: u128, n: u32) -> Result<(), BitError>;

    /// The number of bits written so far.
    fn bit_pos(&self) -> usize;

    /// The byte order applied to a byte-multiple value (default big-endian).
    fn byte_order(&self) -> ByteOrder {
        ByteOrder::Big
    }

    /// The bit order this sink writes in (default MSB-first). Paired with
    /// [`byte_order`](Sink::byte_order) exactly as on [`Source`]: each bit order has a
    /// *natural* byte layout (big-endian under MSB, little-endian under LSB), and only the
    /// opposite declaration swaps a byte-multiple value.
    fn bit_order(&self) -> BitOrder {
        BitOrder::Msb
    }

    /// A type-erased, **encode-scoped scratch** value for codecs that need mutable state
    /// shared across a whole message's fields — a back-reference / compression dictionary
    /// (e.g. DNS name compression). Recover the concrete type with
    /// [`downcast_mut`](Any::downcast_mut).
    ///
    /// Returns `None` unless the sink was built carrying one (see
    /// [`BitWriter::with_scratch`]); the default sink has none. The scratch is the shared
    /// thread the `Sink` already provides — since one sink is passed by `&mut` through
    /// every field's encode, a value stored here is visible to them all.
    fn scratch(&mut self) -> Option<&mut dyn Any> {
        None
    }

    /// Appends one [`Bits`] value of its declared width, applying the byte order.
    ///
    /// # Errors
    /// As [`write_bits`](Sink::write_bits).
    #[inline]
    fn write<T: Bits>(&mut self, value: T) -> Result<(), BitError> {
        let raw = apply_byte_order(
            value.into_bits(),
            T::BITS,
            self.bit_order(),
            self.byte_order(),
        );
        self.write_bits(raw, T::BITS)
    }

    /// Appends a run of bytes — the bulk dual of [`Source::read_bytes`], replacing the
    /// per-byte `write(b)?` loop in custom codecs. Works at any bit offset.
    ///
    /// # Errors
    /// As [`write_bits`](Sink::write_bits).
    fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), BitError> {
        for &b in bytes {
            self.write(b)?;
        }
        Ok(())
    }

    /// Borrows this sink as a [`std::io::Write`] — the dual of [`Source::as_read`], for
    /// handing the cursor to `std::io`-based code from a `#[bw(write_with = …)]`. Writes 8
    /// bits per byte; see [`SinkWriter`]. Only with the `std` feature.
    #[cfg(feature = "std")]
    fn as_write(&mut self) -> SinkWriter<'_, Self>
    where
        Self: Sized,
    {
        SinkWriter(self)
    }
}

/// A [`std::io::Write`] view over a [`Sink`], from [`Sink::as_write`]. Each `write`
/// pushes 8 bits per byte through [`Sink::write_bits`]. The outbound dual of
/// [`SourceReader`]; `flush` is a no-op (the sink owns its buffer).
#[cfg(feature = "std")]
pub struct SinkWriter<'a, K: Sink>(&'a mut K);

#[cfg(feature = "std")]
impl<K: Sink> std::io::Write for SinkWriter<'_, K> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        for &b in buf {
            self.0
                .write_bits(u128::from(b), 8)
                .map_err(|e| std::io::Error::other(e.to_string()))?;
        }
        Ok(buf.len())
    }

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

impl Source for BitReader<'_> {
    #[inline]
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        BitReader::read_bits(self, n)
    }
    #[inline]
    fn bit_pos(&self) -> usize {
        self.bit_pos
    }
    #[inline]
    fn byte_order(&self) -> ByteOrder {
        self.byte
    }
    #[inline]
    fn bit_order(&self) -> BitOrder {
        self.order
    }
    #[inline]
    fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
        BitReader::seek_to_bit(self, pos)
    }
}

impl Sink for BitWriter {
    #[inline]
    fn write_bits(&mut self, value: u128, n: u32) -> Result<(), BitError> {
        BitWriter::write_bits(self, value, n)
    }
    #[inline]
    fn bit_pos(&self) -> usize {
        self.bit_pos
    }
    #[inline]
    fn byte_order(&self) -> ByteOrder {
        self.byte
    }
    #[inline]
    fn bit_order(&self) -> BitOrder {
        self.order
    }
    #[inline]
    fn scratch(&mut self) -> Option<&mut dyn Any> {
        self.scratch.as_deref_mut()
    }
}

/// A message decoded from a bit stream — the recursion point a
/// `#[derive(BitDecode)]` struct implements (reading each field in declaration
/// order). Leaf fields are any [`Bits`] type; nested messages recurse. Fixed- or
/// variable-length; a fixed-length message *also* implements [`FixedBitLen`].
///
/// Most users reach for [`#[bin]`](macro@crate::bin) (which derives this plus
/// [`BitEncode`] and a builder); the bare derives are the codec on its own, for fields
/// that straddle byte boundaries.
///
/// # Examples
///
/// ```
/// use bnb::{BitDecode, BitEncode, u4, u12};
///
/// // A 4-bit tag + a 12-bit length, straddling the byte boundary.
/// #[derive(BitDecode, BitEncode, Debug, PartialEq)]
/// struct Frame { tag: u4, len: u12 }
///
/// let f = Frame::decode_exact(&[0xAB, 0xCD]).unwrap();
/// assert_eq!(f, Frame { tag: u4::new(0xA), len: u12::new(0xBCD) });
/// assert_eq!(f.to_bytes().unwrap(), [0xAB, 0xCD]); // round-trips
/// ```
pub trait BitDecode: Sized {
    /// Decodes `Self` from any [`Source`], advancing its cursor.
    ///
    /// # Errors
    /// Propagates the source's [`BitError`].
    fn bit_decode<S: Source>(r: &mut S) -> Result<Self, BitError>;
}

/// A message whose encoded length is a **compile-time constant** — i.e. it has no
/// variable-length (`count`-driven `Vec`) field. The derive implements this only
/// for fixed messages; it sizes a fixed byte region when the message is embedded
/// as a field in another message (its contribution to the parent's width). A
/// `count`-bearing message implements [`BitDecode`]/[`BitEncode`] but **not** this.
/// `Bits` leaves also implement it (their `BIT_LEN` is `Bits::BITS`), so a field's
/// width is computed uniformly whether it's a leaf or a nested message.
pub trait FixedBitLen {
    /// Total encoded width of the message in bits — the sum of its fields' widths.
    const BIT_LEN: u32;
}

/// Which form [`EncodeExt::encode`] writes. On a `#[bin]` message that has a `reserved` or
/// `calc` field, this is a settable in-memory property (`encode_mode()`/`set_encode_mode()`,
/// or the builder's `.encode_mode(…)`) that `encode` consults — never written to the wire.
/// `to_bytes`/`to_canonical_bytes` ignore it and always encode verbatim/canonical respectively.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum EncodeMode {
    /// **Verbatim** *(default)* — write exactly what's stored (retained `reserved` bits, the
    /// stored value of a `calc` field). Never silently rewrites the caller's data, and is the
    /// faithful dual of `decode` (so a decoded value re-encodes byte-for-byte).
    #[default]
    Verbatim,
    /// **Canonical** — `reserved` fields written as their spec value and `calc` fields
    /// recomputed, so the result is always spec-compliant.
    Canonical,
}

/// A message encoded to a bit stream — the dual of [`BitDecode`].
///
/// Encoding has two forms (see [`EncodeMode`]): the required [`bit_encode`](Self::bit_encode)
/// is **verbatim** (exactly what's stored), and [`canonical_bit_encode`](Self::canonical_bit_encode)
/// is **canonical** (`reserved` → spec value, `calc` → recomputed). The default canonical
/// impl just calls `bit_encode`, so the two are identical unless a `#[bin]` message has a
/// `reserved` or non-`temp` `calc` field — in which case the derive overrides it.
pub trait BitEncode {
    /// The message's bit/byte order, used to size a fresh [`BitWriter`] when
    /// encoding to a `Vec`/writer. The derive sets it from the struct's declared
    /// `bit_order`/`bytes`; a hand-written impl that only ever encodes into a
    /// caller-supplied [`Sink`] can leave the default.
    const LAYOUT: Layout = Layout {
        bit: BitOrder::Msb,
        byte: ByteOrder::Big,
    };

    /// Encodes `self` **verbatim** into any [`Sink`], advancing its cursor.
    ///
    /// # Errors
    /// Propagates the sink's [`BitError`].
    fn bit_encode<K: Sink>(&self, w: &mut K) -> Result<(), BitError>;

    /// Encodes `self`'s **canonical** form into any [`Sink`]: `reserved` fields as their
    /// spec value, `calc` fields recomputed. Defaults to [`bit_encode`](Self::bit_encode)
    /// (verbatim == canonical) for messages with no `reserved`/`calc` field.
    ///
    /// # Errors
    /// Propagates the sink's [`BitError`].
    fn canonical_bit_encode<K: Sink>(&self, w: &mut K) -> Result<(), BitError> {
        self.bit_encode(w)
    }

    /// The form [`EncodeExt::encode`] writes for this value. Defaults to
    /// [`EncodeMode::Verbatim`]; a `#[bin]` message with a `reserved`/`calc` field carries a
    /// settable `encode_mode` and overrides this to return it.
    fn encode_mode(&self) -> EncodeMode {
        EncodeMode::Verbatim
    }
}

// A `Bits` leaf (a `uN`, a `#[bitfield]`, a `BitEnum`/`#[bitflags]`) is *also* field-codable:
// it decodes by reading its `BITS` bits and encodes by writing them. This lets `#[bin]` treat
// **every** field uniformly through `bit_decode`/`bit_encode`, so it needs no `#[nested]` marker
// to choose between "read bits" and "recurse into a message". (The `Bits` packing role — the
// reason these types exist — is untouched; this only *adds* the stream-codec impls.) No blanket
// `impl<T: Bits>` is possible (it would collide with the per-message derives under coherence),
// so the leaves are covered concretely here and the macros emit one for each user `Bits` type.
macro_rules! bits_leaf_codec {
    ($($t:ty),* $(,)?) => {$(
        impl BitDecode for $t {
            #[inline]
            fn bit_decode<S: Source>(r: &mut S) -> Result<Self, BitError> {
                r.read::<$t>()
            }
        }
        impl BitEncode for $t {
            #[inline]
            fn bit_encode<K: Sink>(&self, w: &mut K) -> Result<(), BitError> {
                w.write(*self)
            }
        }
        // A leaf's fixed width is its `Bits::BITS`, so `#[bin]` can size it the same way it
        // sizes a fixed nested message — uniformly via `FixedBitLen`.
        impl FixedBitLen for $t {
            const BIT_LEN: u32 = <$t as Bits>::BITS;
        }
    )*};
}
bits_leaf_codec!(u8, u16, u32, u64, u128, bool);

// `std::net` address types as `#[bin]` fields — the network-codec convenience the protocols
// dogfooding surfaced (IPv4 headers otherwise model addresses as a raw `u32`). An address
// serializes as its `to_bits`/`from_bits` integer, so it follows the struct's byte order like
// any other integer field: in a `#[bin(big)]` message that's the octets in network order
// (`192.168.1.1` → `C0 A8 01 01`), which is what every real protocol wants. `std` only, since
// the types are `std::net`.
macro_rules! ip_addr_codec {
    ($($t:ty => $int:ty, $bits:expr);* $(;)?) => {$(
        #[cfg(feature = "std")]
        impl BitDecode for $t {
            #[inline]
            fn bit_decode<S: Source>(r: &mut S) -> Result<Self, BitError> {
                Ok(<$t>::from_bits(r.read::<$int>()?))
            }
        }
        #[cfg(feature = "std")]
        impl BitEncode for $t {
            #[inline]
            fn bit_encode<K: Sink>(&self, w: &mut K) -> Result<(), BitError> {
                w.write(self.to_bits())
            }
        }
        #[cfg(feature = "std")]
        impl FixedBitLen for $t {
            const BIT_LEN: u32 = $bits;
        }
    )*};
}
ip_addr_codec!(
    std::net::Ipv4Addr => u32, 32;
    std::net::Ipv6Addr => u128, 128;
);

impl<T, const N: usize> BitDecode for crate::int::UInt<T, N>
where
    crate::int::UInt<T, N>: Bits,
{
    #[inline]
    fn bit_decode<S: Source>(r: &mut S) -> Result<Self, BitError> {
        r.read::<Self>()
    }
}

impl<T, const N: usize> BitEncode for crate::int::UInt<T, N>
where
    crate::int::UInt<T, N>: Bits,
{
    #[inline]
    fn bit_encode<K: Sink>(&self, w: &mut K) -> Result<(), BitError> {
        w.write(*self)
    }
}

impl<T, const N: usize> FixedBitLen for crate::int::UInt<T, N>
where
    crate::int::UInt<T, N>: Bits,
{
    const BIT_LEN: u32 = <Self as Bits>::BITS;
}

/// Seals [`CountPrefix`] and [`codecs::leb128::Varint`](crate::codecs::leb128::Varint):
/// the impl set is crate-owned (all wire-integer widths are already covered), so growing
/// it later is non-breaking while a downstream impl can never observe a bound change.
pub(crate) mod sealed {
    /// The sealing supertrait — unnameable downstream, so the traits above cannot be
    /// implemented outside this crate.
    pub trait Sealed {}
}

/// Checked length ⇄ wire-prefix conversions: the types usable as a length/count prefix —
/// by the [`#[brw(count_prefix = <Ty>)]`](macro@crate::bin) directive and by the
/// [`codecs::prefixed`](crate::codecs::prefixed) string codec.
///
/// The prefix is computed from `len()` on encode and turned back into an element count on
/// decode. `try_from_len` is **checked and never truncates**: the length is widened (never
/// narrowed) before the range compare, so 300 elements against a `u8` prefix is
/// [`Error::ValueTooLarge`] — not a silently wrapped `44`.
///
/// [`Error::ValueTooLarge`]: crate::Error::ValueTooLarge
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be a `count_prefix` type",
    note = "supported prefix types: u8, u16, u32, u64, u128 and the arbitrary-width `uN` aliases (e.g. `u12`)",
    note = "this trait is sealed — the supported prefix types are built in"
)]
pub trait CountPrefix: Bits + sealed::Sealed {
    /// The prefix for a collection of `len` elements, or [`Error::ValueTooLarge`] when
    /// `len` exceeds the prefix's range.
    fn try_from_len(len: usize) -> crate::error::Result<Self>
    where
        Self: Sized;

    /// The prefix as an element count.
    ///
    /// For a `u64`/`u128` prefix on a 32-bit target this is a wrapping narrow — the same
    /// `n as usize` the hand-written triad performs; harmless under the codec's
    /// push-based count loop (no pre-allocation, bounded by the input).
    fn to_count(self) -> usize;
}

macro_rules! count_prefix_prim {
    ($($t:ty),* $(,)?) => {$(
        impl sealed::Sealed for $t {}

        impl CountPrefix for $t {
            #[inline]
            fn try_from_len(len: usize) -> crate::error::Result<Self> {
                <$t>::try_from(len).map_err(|_| crate::error::Error::ValueTooLarge {
                    value: len as u128,
                    bits: <$t>::BITS,
                })
            }

            #[inline]
            fn to_count(self) -> usize {
                self as usize
            }
        }
    )*};
}
count_prefix_prim!(u8, u16, u32, u64, u128);

macro_rules! count_prefix_uint {
    ($($t:ty),* $(,)?) => {$(
        impl<const N: usize> sealed::Sealed for crate::int::UInt<$t, N> {}

        impl<const N: usize> CountPrefix for crate::int::UInt<$t, N> {
            #[inline]
            fn try_from_len(len: usize) -> crate::error::Result<Self> {
                // Widen-then-compare: narrowing first (`len as $t`) would truncate
                // *before* the range check and let an oversized length slip through.
                let wide = len as u128;
                if wide > Self::MASK as u128 {
                    return Err(crate::error::Error::ValueTooLarge {
                        value: wide,
                        bits: N as u32,
                    });
                }
                Ok(Self::from_raw(len as $t))
            }

            #[inline]
            fn to_count(self) -> usize {
                self.value() as usize
            }
        }
    )*};
}
count_prefix_uint!(u8, u16, u32, u64, u128);

/// `encode(writer)` for any [`BitEncode`] message — encodes to a `Vec` (using the type's
/// [`LAYOUT`](BitEncode::LAYOUT)) in `self`'s [`encode_mode`](BitEncode::encode_mode) and
/// writes it to a [`std::io::Write`] sink. A blanket-implemented extension trait, so bring it
/// into scope (`use bnb::prelude::*` or `use bnb::EncodeExt`) to call `.encode(&mut w)`. Only
/// with the `std` feature; in `no_std` use the generated `to_bytes`/`to_canonical_bytes`, or
/// [`bit_encode`](BitEncode::bit_encode)/[`canonical_bit_encode`](BitEncode::canonical_bit_encode)
/// over a [`Sink`].
#[cfg(feature = "std")]
pub trait EncodeExt: BitEncode {
    /// Encodes `self` to any [`std::io::Write`] (socket, file, `Vec`) in the value's
    /// [`encode_mode`](BitEncode::encode_mode) — verbatim unless its mode is set to
    /// [`Canonical`](EncodeMode::Canonical). For an unconditional choice, use the inherent
    /// `to_bytes` (verbatim) / `to_canonical_bytes` (canonical) instead.
    ///
    /// # Errors
    /// [`ErrorKind::Io`] on a write failure, else the encode error.
    fn encode<W: std::io::Write>(&self, w: &mut W) -> Result<(), BitError>
    where
        Self: Sized,
    {
        match self.encode_mode() {
            EncodeMode::Verbatim => {
                encode_to_writer_with(w, Self::LAYOUT, |bw| self.bit_encode(bw))
            }
            EncodeMode::Canonical => {
                encode_to_writer_with(w, Self::LAYOUT, |bw| self.canonical_bit_encode(bw))
            }
        }
    }
}

#[cfg(feature = "std")]
impl<T: BitEncode> EncodeExt for T {}

/// Polymorphic decode **with context** `A` — the companion to a `#[bin(ctx(...))]`
/// type's inherent `decode_with`, for hand-written generic combinators and
/// trait-object parsing (ctx Layer 2). Every [`BitDecode`] type is `DecodeWith<()>`
/// (blanket), and a ctx type is `DecodeWith<…Ctx>`, so one bound `T: DecodeWith<A>`
/// spans both context-free and context-taking messages. Inherent `Type::decode_with`
/// call sites are unaffected.
pub trait DecodeWith<A>: Sized {
    /// Decodes `Self` from a [`Source`] given `args`.
    ///
    /// # Errors
    /// Propagates the decode [`BitError`].
    fn decode_with<S: Source>(r: &mut S, args: A) -> Result<Self, BitError>;
}

/// The dual of [`DecodeWith`] — polymorphic encode with context `A`.
pub trait EncodeWith<A> {
    /// Encodes `self` into a [`Sink`] given `args`.
    ///
    /// # Errors
    /// Propagates the encode [`BitError`].
    fn encode_with<K: Sink>(&self, w: &mut K, args: A) -> Result<(), BitError>;
}

impl<T: BitDecode> DecodeWith<()> for T {
    fn decode_with<S: Source>(r: &mut S, _args: ()) -> Result<Self, BitError> {
        T::bit_decode(r)
    }
}

impl<T: BitEncode> EncodeWith<()> for T {
    fn encode_with<K: Sink>(&self, w: &mut K, _args: ()) -> Result<(), BitError> {
        self.bit_encode(w)
    }
}

// ---------------------------------------------------------------------------
// Entry-point helpers — the logic behind the `#[derive]`-generated inherent
// methods (`Type::decode`/`peek`/`decode_exact`/`encode`/`to_bytes`). Kept here
// so the logic lives in one place rather than monomorphized inline per type;
// doc-hidden because the public surface is the generated methods.
// ---------------------------------------------------------------------------

/// Decode every message from `bytes` into a `Vec`, with the message's own byte/bit order baked
/// in — bit-aware, so messages that don't end on byte boundaries reassemble correctly. Backs
/// `Type::decode_all`. The buffer must hold whole messages (a partial tail is an error).
///
/// # Errors
/// The first decode [`BitError`] (e.g. a truncated trailing message).
#[doc(hidden)]
pub fn decode_all<T: BitDecode>(bytes: &[u8], layout: Layout) -> Result<Vec<T>, BitError> {
    let mut r = BitReader::with_layout(bytes, layout);
    let mut out = Vec::new();
    while r.remaining_bits() > 0 {
        let before = r.bit_pos();
        let item = T::bit_decode(&mut r)?;
        if r.bit_pos() == before {
            break; // a zero-width `T` makes no progress — stop without pushing a spurious
            // element (and without spinning forever).
        }
        out.push(item);
    }
    Ok(out)
}

/// A lazy iterator decoding successive `T` from `bytes` (layout baked in) until the buffer is
/// drained, ending after the first error if one occurs. Backs `Type::decode_iter`.
#[doc(hidden)]
pub fn decode_iter<T: BitDecode>(
    bytes: &[u8],
    layout: Layout,
) -> impl Iterator<Item = Result<T, BitError>> + '_ {
    let mut r = BitReader::with_layout(bytes, layout);
    let mut stopped = false;
    core::iter::from_fn(move || {
        if stopped || r.remaining_bits() == 0 {
            return None;
        }
        let before = r.bit_pos();
        match T::bit_decode(&mut r) {
            Ok(v) => {
                stopped = r.bit_pos() == before; // stop if a zero-width message made no progress
                Some(Ok(v))
            }
            Err(e) => {
                stopped = true;
                Some(Err(e))
            }
        }
    })
}

/// Decodes one message from `bytes` without consuming the caller's buffer
/// (tail-tolerant). Backs `Type::peek`.
///
/// # Errors
/// Propagates the decode [`BitError`].
#[doc(hidden)]
pub fn decode_peek<T: BitDecode>(bytes: &[u8], layout: Layout) -> Result<T, BitError> {
    T::bit_decode(&mut BitReader::with_layout(bytes, layout))
}

/// `decode_peek` over a caller-supplied closure (no consumption requirement) — backs a
/// `#[bin]` enum's `peek_variant`, which runs only the dispatch decision over `bytes`.
///
/// # Errors
/// Propagates the closure's [`BitError`].
#[doc(hidden)]
pub fn decode_peek_with<T, F>(bytes: &[u8], layout: Layout, f: F) -> Result<T, BitError>
where
    F: FnOnce(&mut BitReader) -> Result<T, BitError>,
{
    f(&mut BitReader::with_layout(bytes, layout))
}

/// `decode_exact` over a caller-supplied decode closure rather than the
/// [`BitDecode`] trait — backs the `ctx`-parameterized `Type::decode_with_exact`
/// (a `ctx` type takes a context argument, so it has no plain `bit_decode`).
///
/// # Errors
/// [`ErrorKind::TrailingBytes`] if whole bytes remain, else the closure's error.
#[doc(hidden)]
pub fn decode_exact_with<T, F>(bytes: &[u8], layout: Layout, f: F) -> Result<T, BitError>
where
    F: FnOnce(&mut BitReader) -> Result<T, BitError>,
{
    let mut r = BitReader::with_layout(bytes, layout);
    let v = f(&mut r)?;
    let consumed = r.bit_pos().div_ceil(8);
    if consumed < bytes.len() {
        return Err(BitError::new(
            ErrorKind::TrailingBytes {
                remaining: bytes.len() - consumed,
            },
            r.bit_pos(),
        ));
    }
    Ok(v)
}

/// `to_bytes` over a caller-supplied encode closure — backs the `ctx`-parameterized
/// `Type::to_bytes_with`.
///
/// # Errors
/// Propagates the closure's [`BitError`].
#[doc(hidden)]
pub fn encode_to_vec_with<F>(layout: Layout, f: F) -> Result<Vec<u8>, BitError>
where
    F: FnOnce(&mut BitWriter) -> Result<(), BitError>,
{
    let mut w = BitWriter::with_layout(layout);
    f(&mut w)?;
    Ok(w.into_bytes())
}

/// Decodes and requires every **whole byte** consumed; a sub-byte tail in the
/// final byte is treated as padding. Backs `Type::decode_exact`.
///
/// # Errors
/// [`ErrorKind::TrailingBytes`] if whole bytes remain, else the decode error.
#[doc(hidden)]
pub fn decode_exact<T: BitDecode>(bytes: &[u8], layout: Layout) -> Result<T, BitError> {
    let mut r = BitReader::with_layout(bytes, layout);
    let v = T::bit_decode(&mut r)?;
    let consumed = r.bit_pos().div_ceil(8);
    if consumed < bytes.len() {
        return Err(BitError::new(
            ErrorKind::TrailingBytes {
                remaining: bytes.len() - consumed,
            },
            r.bit_pos(),
        ));
    }
    Ok(v)
}

/// Encodes `value` to a `Vec<u8>`. Backs `Type::to_bytes`.
///
/// # Errors
/// Propagates the encode [`BitError`].
#[doc(hidden)]
pub fn encode_to_vec<T: BitEncode>(value: &T, layout: Layout) -> Result<Vec<u8>, BitError> {
    let mut w = BitWriter::with_layout(layout);
    value.bit_encode(&mut w)?;
    Ok(w.into_bytes())
}

/// Encodes `value` to any [`std::io::Write`]. Backs [`EncodeExt::encode`].
///
/// # Errors
/// [`ErrorKind::Io`] on a write failure, else the encode error.
/// Encode to a [`std::io::Write`] over a caller-supplied encode closure — backs
/// [`EncodeExt::encode`] in either [`EncodeMode`] (the closure picks `bit_encode` vs
/// `canonical_bit_encode`).
///
/// # Errors
/// [`ErrorKind::Io`] on a write failure, else the closure's error.
#[cfg(feature = "std")]
#[doc(hidden)]
pub fn encode_to_writer_with<W, F>(w: &mut W, layout: Layout, f: F) -> Result<(), BitError>
where
    W: std::io::Write,
    F: FnOnce(&mut BitWriter) -> Result<(), BitError>,
{
    let mut bw = BitWriter::with_layout(layout);
    f(&mut bw)?;
    let at = bw.bit_len();
    w.write_all(&bw.into_bytes())
        .map_err(|e| BitError::new(ErrorKind::Io(e.kind()), at))
}

/// Reads a fixed `[u8; N]` byte array (`N * 8` bits) from the cursor. Backs a
/// `[u8; N]` payload field; `N` is inferred from the field type. Variable-length
/// payloads (`Vec` + `#[br(count = …)]`) take a separate push-based path that
/// grows by element, so an attacker-controlled count can't over-allocate.
///
/// # Errors
/// Propagates the source's [`BitError`].
#[doc(hidden)]
pub fn read_byte_array<const N: usize, S: Source>(r: &mut S) -> Result<[u8; N], BitError> {
    let mut arr = [0u8; N];
    for b in &mut arr {
        *b = r.read_bits(8)? as u8;
    }
    Ok(arr)
}

/// Peeks up to `max` bytes without consuming them — reads them, then rewinds. Returns
/// however many are available (fewer than `max` at end-of-input). Backs variable-width
/// `#[bin]` enum magic dispatch (peek the longest magic, match a prefix, then seek past
/// the matched one). Like other seeking directives it bounds the generated `decode`
/// on [`SeekSource`]; a forward-only source fails at runtime with
/// [`ErrorKind::NotSeekable`].
///
/// # Errors
/// [`ErrorKind::NotSeekable`] if the source can't rewind.
#[doc(hidden)]
pub fn peek_bytes<S: Source>(r: &mut S, max: usize) -> Result<Vec<u8>, BitError> {
    let start = r.bit_pos();
    let mut out = Vec::with_capacity(max);
    for _ in 0..max {
        match r.read_bits(8) {
            Ok(b) => out.push(b as u8),
            Err(_) => break, // end of input — a shorter magic may still match
        }
    }
    r.seek_to_bit(start)?;
    Ok(out)
}

/// Writes a fixed `[u8; N]` byte array. Backs a `[u8; N]` payload field.
///
/// # Errors
/// Propagates the sink's [`BitError`].
#[doc(hidden)]
pub fn write_byte_array<const N: usize, K: Sink>(arr: &[u8; N], w: &mut K) -> Result<(), BitError> {
    for &b in arr {
        w.write_bits(u128::from(b), 8)?;
    }
    Ok(())
}

/// A *forward-only* bit reader over any [`std::io::Read`] — the streaming counterpart
/// to the in-memory [`BitReader`], for a stream you read once and don't seek.
///
/// It is bounded on `Read` **only, not `Seek`**, so it works over inputs that can't
/// seek (a socket, or a `&[u8]`, which is `Read` but not `Seek`). A message that needs
/// to seek (`#[br(restore_position)]`) won't decode through it — use a [`BufSource`] or
/// [`SeekReader`] for that. Reads up to 128 bits per call (the [`Source`] width
/// ceiling); running out mid-message yields [`ErrorKind::Incomplete`] ("read more and
/// retry").
///
/// # Examples
///
/// ```
/// use bnb::{bin, StreamBitReader};
///
/// #[bin(big)]
/// #[derive(Debug, PartialEq)]
/// struct Word { value: u32 }
///
/// // `&[u8]` is `Read` but not `Seek` — exactly the forward-only case.
/// let data: &[u8] = &[0x12, 0x34, 0x56, 0x78];
/// let mut s = StreamBitReader::new(data);
/// assert_eq!(Word::decode(&mut s).unwrap(), Word { value: 0x1234_5678 });
/// ```
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct StreamBitReader<R> {
    inner: R,
    /// Leftover bits from the last partially-consumed byte, right-aligned in the low
    /// `lead_bits` bits (MSB-first, so they are the *high* bits of the next read).
    /// Always fewer than 8.
    lead: u32,
    lead_bits: u32,
    /// Total bits consumed so far (for position-aware errors).
    pos: usize,
    /// The bit/byte order this source reports (raw `read_bits` is always MSB-first; the
    /// layout is applied to multi-byte values by `Source::read`).
    layout: Layout,
}

#[cfg(feature = "std")]
impl<R: std::io::Read> StreamBitReader<R> {
    /// Wraps a byte source, decoding in the default **MSB-first, big-endian** order. For a
    /// `#[bin(little)]`/`bit_order = lsb` message, use [`with_layout`](Self::with_layout) with
    /// that type's [`LAYOUT`](BitEncode::LAYOUT), or the decode reads the wrong order.
    pub fn new(inner: R) -> Self {
        Self::with_layout(inner, Layout::default())
    }

    /// Wraps a byte source, decoding in the given [`Layout`] (bit + byte order) — pass a
    /// message's `LAYOUT` so a non-default-order `#[bin]` type round-trips over a stream.
    pub fn with_layout(inner: R, layout: Layout) -> Self {
        Self {
            inner,
            lead: 0,
            lead_bits: 0,
            pos: 0,
            layout,
        }
    }

    /// The total number of bits consumed so far.
    #[must_use]
    pub fn bit_pos(&self) -> usize {
        self.pos
    }

    /// Reads `n` (`<= 128`) bits MSB-first, pulling bytes from the source as needed.
    ///
    /// # Errors
    /// [`ErrorKind::TooWide`] if `n > 128`; [`ErrorKind::Incomplete`] if the
    /// source runs out mid-field (read more and retry). Either carries the bit
    /// offset.
    pub fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        if n > 128 {
            return Err(BitError::new(
                ErrorKind::TooWide { width: n as usize },
                self.pos,
            ));
        }
        let at = self.pos;
        // Build the result MSB-first, consuming the leftover bits then whole bytes.
        // The accumulator never holds more than `n` (<= 128) bits, so it can't
        // overflow — unlike a "shift bytes in, mask out" buffer, which is why the old
        // byte-accumulator capped at 64 and this caps at the full 128.
        let mut result: u128 = 0;
        let mut need = n;
        while need > 0 {
            if self.lead_bits == 0 {
                let mut b = [0u8; 1];
                if self.inner.read_exact(&mut b).is_err() {
                    // Ran out mid-field: "need more bytes" (buffer and retry), not a
                    // definitive end-of-input.
                    return Err(BitError::new(ErrorKind::Incomplete { needed: None }, at));
                }
                self.lead = u32::from(b[0]);
                self.lead_bits = 8;
            }
            let take = need.min(self.lead_bits);
            // The top `take` of the `lead_bits` leftover bits (MSB-first).
            let shift = self.lead_bits - take;
            let chunk = (self.lead >> shift) & ((1u32 << take) - 1);
            result = (result << take) | u128::from(chunk);
            self.lead_bits -= take;
            self.lead &= (1u32 << self.lead_bits) - 1; // keep the unconsumed low bits
            need -= take;
        }
        self.pos += n as usize;
        Ok(result)
    }

    /// Reads one [`Bits`] value (width `<= 128`) of its declared width.
    ///
    /// # Errors
    /// As [`read_bits`](Self::read_bits).
    pub fn read<T: Bits>(&mut self) -> Result<T, BitError> {
        Ok(T::from_bits(self.read_bits(T::BITS)?))
    }
}

#[cfg(feature = "std")]
impl<R: std::io::Read> Source for StreamBitReader<R> {
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        StreamBitReader::read_bits(self, n)
    }
    fn bit_pos(&self) -> usize {
        self.pos
    }
    fn byte_order(&self) -> ByteOrder {
        self.layout.byte
    }
    fn bit_order(&self) -> BitOrder {
        self.layout.bit
    }
}

/// A **seekable** [`Source`] over a forward `Read` (a socket): it *retains* the bytes
/// it has read, so a seek-using message (`restore_position`) works over a non-seekable
/// stream by seeking within the retained buffer, reading more on demand. It is
/// **bounded** — a retention `cap` (default 64 KiB) past which it errors
/// [`ErrorKind::BufferFull`] rather than buffering unboundedly. The
/// "continuously-receiving peer that also needs to seek" case.
///
/// # Examples
///
/// ```
/// use bnb::{bin, BufSource};
///
/// #[bin(big)]
/// #[derive(Debug, PartialEq)]
/// struct Word { value: u32 }
///
/// let mut src = BufSource::new(&[0x12, 0x34, 0x56, 0x78][..]); // any `Read`
/// assert_eq!(Word::decode(&mut src).unwrap(), Word { value: 0x1234_5678 });
/// ```
#[cfg(feature = "std")]
#[derive(Clone, Debug)]
pub struct BufSource<R> {
    inner: R,
    buf: Vec<u8>,
    bit_pos: usize,
    cap: usize,
    layout: Layout,
    eof: bool,
}

#[cfg(feature = "std")]
impl<R: std::io::Read> BufSource<R> {
    /// Wraps `inner` with the default 64 KiB retention cap, MSB-first big-endian.
    #[must_use]
    pub fn new(inner: R) -> Self {
        Self::with_cap(inner, 64 * 1024)
    }

    /// Wraps `inner` with a retention `cap` (bytes), MSB-first big-endian.
    #[must_use]
    pub fn with_cap(inner: R, cap: usize) -> Self {
        Self::with_cap_and_layout(inner, cap, Layout::default())
    }

    /// Wraps `inner` with a retention `cap` (bytes) and [`Layout`].
    #[must_use]
    pub fn with_cap_and_layout(inner: R, cap: usize, layout: Layout) -> Self {
        Self {
            inner,
            buf: Vec::new(),
            bit_pos: 0,
            cap,
            layout,
            eof: false,
        }
    }

    /// Reads from `inner` until `buf` holds at least `byte_end` bytes (or EOF/cap).
    fn fill_to(&mut self, byte_end: usize) -> Result<(), BitError> {
        while self.buf.len() < byte_end && !self.eof {
            if self.buf.len() >= self.cap {
                return Err(BitError::new(
                    ErrorKind::BufferFull { cap: self.cap },
                    self.bit_pos,
                ));
            }
            let want = (byte_end - self.buf.len()).min(self.cap - self.buf.len());
            let start = self.buf.len();
            self.buf.resize(start + want, 0);
            match self.inner.read(&mut self.buf[start..]) {
                Ok(0) => {
                    self.buf.truncate(start);
                    self.eof = true;
                }
                Ok(got) => self.buf.truncate(start + got),
                Err(e) => {
                    self.buf.truncate(start);
                    return Err(BitError::new(ErrorKind::Io(e.kind()), self.bit_pos));
                }
            }
        }
        Ok(())
    }
}

#[cfg(feature = "std")]
impl<R: std::io::Read> Source for BufSource<R> {
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        if n > 128 {
            return Err(BitError::new(
                ErrorKind::TooWide { width: n as usize },
                self.bit_pos,
            ));
        }
        let byte_end = (self.bit_pos + n as usize).div_ceil(8);
        self.fill_to(byte_end)?;
        if self.buf.len() < byte_end {
            return Err(BitError::new(
                ErrorKind::Incomplete {
                    needed: Some(byte_end - self.buf.len()),
                },
                self.bit_pos,
            ));
        }
        let acc = extract_bits(&self.buf, self.bit_pos, n as usize, self.layout.bit);
        self.bit_pos += n as usize;
        Ok(acc)
    }
    fn bit_pos(&self) -> usize {
        self.bit_pos
    }
    fn byte_order(&self) -> ByteOrder {
        self.layout.byte
    }
    fn bit_order(&self) -> BitOrder {
        self.layout.bit
    }
    fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
        // Seek within the retained buffer; a later read fills more on demand.
        // Backward seeks (`restore_position`) hit already-retained bytes.
        self.bit_pos = pos;
        Ok(())
    }
}

#[cfg(feature = "std")]
impl<R: std::io::Read> SeekSource for BufSource<R> {}

/// A **push/pull, bit-aware** decode buffer for incremental framing.
///
/// Feed bytes with [`push`](Self::push) as they arrive — from a socket, a channel, a callback,
/// anything that delivers bytes — and take whole messages off the front with [`pull`](Self::pull),
/// which returns `Ok(None)` when it needs more bytes (push more and call again).
///
/// Unlike a byte cursor (`bytes::BytesMut::advance`), `BitBuf` tracks a **bit** position, so a
/// stream of messages that *don't* end on byte boundaries (bit-packed frames) reassembles cleanly:
/// `pull` advances past the consumed whole bytes and retains any partial trailing byte for the
/// next message. It's the *pushable*, in-memory counterpart to [`BufSource`] (which pulls from a
/// `Read`). `no_std`-compatible (`alloc` only).
///
/// **Reclaim is deferred and in place.** `pull` doesn't drain consumed bytes — the next
/// [`push`](Self::push)/[`try_push`](Self::try_push) reclaims them in place (one memmove, only when
/// it avoids a reallocation), so a steady push/pull loop reuses the same allocation without
/// per-message churn. For a guaranteed-fixed footprint (real-time / `no_std`), construct a
/// [`bounded`](Self::bounded) buffer: it allocates once, [`try_push`](Self::try_push) refuses bytes
/// past the cap instead of growing, and [`grow`](Self::grow) is the only thing that reallocates.
///
/// `BitBuf` is also a [`SeekSource`], so it reads through the same [`decode`](crate::BitDecode)
/// entry points as every other cursor: `Type::decode(&mut bitbuf)` advances its cursor (then call
/// [`compact`](Self::compact) to reclaim). For streaming, prefer [`pull`](Self::pull) — it bakes
/// the message's own [`LAYOUT`](BitEncode::LAYOUT) (so `little`/`lsb` messages are always correct),
/// decodes **and** reclaims, and reports "need more bytes" as `Ok(None)`. The bare `Source` path
/// instead uses the buffer's own [`with_layout`](Self::with_layout) order (default msb/big).
///
/// ```
/// use bnb::{bin, BitBuf};
/// #[bin(big)]
/// #[derive(Debug, PartialEq, Eq)]
/// struct Ping { seq: u16 }
///
/// let mut bb = BitBuf::new();
/// bb.push(&[0x00]);                                  // only half of the first message
/// assert_eq!(bb.pull::<Ping>().unwrap(), None);      // not a whole message yet
/// bb.push(&[0x01, 0x00, 0x02]);                      // rest of msg 1 + all of msg 2
/// assert_eq!(bb.pull::<Ping>().unwrap(), Some(Ping { seq: 1 }));
/// assert_eq!(bb.pull::<Ping>().unwrap(), Some(Ping { seq: 2 }));
/// assert_eq!(bb.pull::<Ping>().unwrap(), None);      // drained
/// ```
///
#[derive(Debug, Default, Clone)]
pub struct BitBuf {
    /// Buffered bytes. The bytes before `cursor`'s byte are **consumed** (dead) — physically
    /// reclaimed lazily (on a [`push`](Self::push) that would otherwise grow, or [`compact`](Self::compact)),
    /// not on every [`pull`](Self::pull), so a push/pull loop doesn't churn memory.
    buf: Vec<u8>,
    /// Live read position, in bits, into `buf` (`0..=buf.len() * 8`).
    cursor: usize,
    /// `Some(cap)` for a **bounded** buffer (alloc-once: [`try_push`](Self::try_push) never grows
    /// past `cap`, [`grow`](Self::grow) raises it explicitly); `None` for an auto-growing buffer.
    cap: Option<usize>,
    /// Byte/bit order for the [`Source`] impl (the `decode(&mut bitbuf)` path); default msb/big.
    layout: Layout,
}

impl BitBuf {
    /// An empty auto-growing buffer (msb/big order for the [`Source`] path).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// An empty auto-growing buffer with room for `cap` bytes before reallocating. Like
    /// [`new`](Self::new) but pre-reserved; it still grows past `cap` on demand (use
    /// [`bounded`](Self::bounded) for a hard cap).
    #[must_use]
    pub fn with_capacity(cap: usize) -> Self {
        Self {
            buf: Vec::with_capacity(cap),
            cursor: 0,
            cap: None,
            layout: Layout::default(),
        }
    }

    /// An empty **bounded** buffer: it allocates `cap` bytes once and never reallocates on its own.
    /// [`try_push`](Self::try_push) refuses bytes that would exceed `cap` (reclaiming consumed
    /// bytes first), and [`grow`](Self::grow) is the only thing that allocates again — so a
    /// real-time / `no_std` caller can guarantee a fixed footprint.
    #[must_use]
    pub fn bounded(cap: usize) -> Self {
        Self {
            buf: Vec::with_capacity(cap),
            cursor: 0,
            cap: Some(cap),
            layout: Layout::default(),
        }
    }

    /// Set the byte/bit order used by the [`Source`] impl (the `decode(&mut bitbuf)` path).
    /// [`pull`](Self::pull) ignores this — it always bakes the message's own `LAYOUT`.
    #[must_use]
    pub fn with_layout(mut self, layout: Layout) -> Self {
        self.layout = layout;
        self
    }

    /// The buffer's hard capacity in bytes for a [`bounded`](Self::bounded) buffer, or `None` if
    /// it auto-grows.
    #[must_use]
    pub fn capacity(&self) -> Option<usize> {
        self.cap
    }

    /// Reclaim consumed whole bytes (drain everything before the cursor's byte) when doing so
    /// avoids a reallocation or the dead prefix has grown to dominate the live bytes. Keeps the
    /// footprint near the working set without compacting on every push.
    fn make_room(&mut self, additional: usize) {
        let dead = self.cursor / 8;
        if dead == 0 {
            return;
        }
        let live = self.buf.len() - dead;
        let would_grow = self.buf.len() + additional > self.buf.capacity();
        if would_grow || dead >= live {
            self.buf.drain(..dead);
            self.cursor -= dead * 8;
        }
    }

    /// Append freshly-received bytes to the back of the buffer, growing (reallocating) if needed.
    /// Consumed bytes are reclaimed in place first when that avoids a reallocation. For a hard,
    /// alloc-free cap, use [`bounded`](Self::bounded) + [`try_push`](Self::try_push).
    pub fn push(&mut self, bytes: &[u8]) {
        self.make_room(bytes.len());
        self.buf.extend_from_slice(bytes);
    }

    /// Append bytes **without reallocating**, reclaiming consumed bytes in place to make room.
    ///
    /// # Errors
    /// [`CapacityError`] if the bytes don't fit a [`bounded`](Self::bounded) buffer's capacity
    /// (the live bytes plus the new bytes exceed `cap`). On an unbounded buffer it always
    /// succeeds (growing if needed), so prefer [`push`](Self::push) there.
    pub fn try_push(&mut self, bytes: &[u8]) -> Result<(), CapacityError> {
        let live = self.buf.len() - self.cursor / 8;
        if let Some(cap) = self.cap {
            if live + bytes.len() > cap {
                return Err(CapacityError {
                    cap,
                    requested: live + bytes.len(),
                });
            }
        }
        self.make_room(bytes.len());
        self.buf.extend_from_slice(bytes);
        Ok(())
    }

    /// Grow a [`bounded`](Self::bounded) buffer's capacity by `additional` bytes (raising the cap
    /// and reserving the space — the one operation that reallocates a bounded buffer). On an
    /// unbounded buffer it just reserves.
    pub fn grow(&mut self, additional: usize) {
        if let Some(cap) = &mut self.cap {
            *cap += additional;
        }
        self.buf.reserve(additional);
    }

    /// The number of unconsumed bits currently buffered.
    #[must_use]
    pub fn bit_len(&self) -> usize {
        self.buf.len() * 8 - self.cursor
    }

    /// Whether no unconsumed bits remain.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.bit_len() == 0
    }

    /// Drop all buffered bytes and reset the cursor (keeps the allocation and any bound).
    pub fn clear(&mut self) {
        self.buf.clear();
        self.cursor = 0;
    }

    /// Physically reclaim the fully-consumed whole bytes now (drop everything before the cursor's
    /// byte), keeping any partial trailing byte. [`pull`](Self::pull) defers this; call it
    /// yourself when consuming via the [`Source`] path (`decode(&mut bitbuf)`) to bound the buffer.
    pub fn compact(&mut self) {
        let whole = self.cursor / 8;
        self.buf.drain(..whole);
        self.cursor -= whole * 8;
    }

    /// Decode the next complete message off the front, advancing past the bytes it consumed.
    ///
    /// Returns `Ok(None)` when the buffer doesn't yet hold a whole message — push more bytes and
    /// call again; the cursor is left untouched, so the retry is free. A malformed message is an
    /// `Err`. The byte/bit order is taken from `T`'s [`LAYOUT`](BitEncode::LAYOUT), so it decodes
    /// `little`/`lsb` messages correctly regardless of [`with_layout`](Self::with_layout).
    ///
    /// Consumed bytes are **not** drained here — they are reclaimed in place by the next
    /// [`push`](Self::push)/[`try_push`](Self::try_push) (or an explicit [`compact`](Self::compact)),
    /// so a steady push/pull loop reuses the same allocation without per-message memmoves.
    ///
    /// # Errors
    /// A codec [`BitError`] for a malformed message.
    pub fn pull<T: BitDecode + BitEncode>(&mut self) -> Result<Option<T>, BitError> {
        if self.cursor >= self.buf.len() * 8 {
            return Ok(None);
        }
        let mut r = BitReader::with_layout(&self.buf, <T as BitEncode>::LAYOUT);
        r.seek_to_bit(self.cursor)?;
        match T::bit_decode(&mut r) {
            Ok(msg) => {
                self.cursor = r.bit_pos(); // advance past the message; reclaim is deferred
                Ok(Some(msg))
            }
            // Only a partial message is buffered — wait for more (cursor untouched, retry-safe).
            Err(e)
                if matches!(
                    e.kind,
                    ErrorKind::UnexpectedEof { .. } | ErrorKind::Incomplete { .. }
                ) =>
            {
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }
}

/// The error [`BitBuf::try_push`] returns when bytes won't fit a [`bounded`](BitBuf::bounded)
/// buffer — the live (unconsumed) bytes plus the new bytes exceed its fixed `cap`. Grow it with
/// [`BitBuf::grow`], or drain messages with [`pull`](BitBuf::pull) before pushing more.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CapacityError {
    /// The buffer's fixed capacity, in bytes.
    pub cap: usize,
    /// The bytes that were needed (live bytes + the rejected push).
    pub requested: usize,
}

impl fmt::Display for CapacityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "bitbuf is full: {} bytes needed exceeds the {}-byte capacity",
            self.requested, self.cap
        )
    }
}

impl core::error::Error for CapacityError {}

impl Source for BitBuf {
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        let mut r = BitReader::with_layout(&self.buf, self.layout);
        r.seek_to_bit(self.cursor)?;
        let v = r.read_bits(n)?;
        self.cursor = r.bit_pos();
        Ok(v)
    }

    fn bit_pos(&self) -> usize {
        self.cursor
    }

    fn byte_order(&self) -> ByteOrder {
        self.layout.byte
    }
    fn bit_order(&self) -> BitOrder {
        self.layout.bit
    }

    fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
        // Validate against the buffered bits (mirrors BitReader's bounds), then move the cursor.
        let mut probe = BitReader::with_layout(&self.buf, self.layout);
        probe.seek_to_bit(pos)?;
        self.cursor = pos;
        Ok(())
    }
}

impl SeekSource for BitBuf {}

/// A [`SeekSource`] over a seekable reader (`Read + Seek`, e.g. a `File`): it seeks
/// via [`std::io::Seek`] to the byte holding the bit cursor, **without buffering** —
/// the large-file / container-format case. For a *non*-seekable stream that still
/// needs to seek, use [`BufSource`].
///
/// # Examples
///
/// ```
/// use bnb::{bin, SeekReader};
/// use std::io::Cursor;
///
/// #[bin(big)]
/// #[derive(Debug, PartialEq)]
/// struct Word { value: u32 }
///
/// let mut f = SeekReader::new(Cursor::new(vec![0x12u8, 0x34, 0x56, 0x78]));
/// assert_eq!(Word::decode(&mut f).unwrap(), Word { value: 0x1234_5678 });
/// ```
#[cfg(feature = "std")]
#[derive(Clone, Debug)]
pub struct SeekReader<R> {
    inner: R,
    bit_pos: usize,
    layout: Layout,
}

#[cfg(feature = "std")]
impl<R: std::io::Read + std::io::Seek> SeekReader<R> {
    /// Wraps `inner` at bit 0, MSB-first big-endian.
    #[must_use]
    pub fn new(inner: R) -> Self {
        Self::with_layout(inner, Layout::default())
    }

    /// Wraps `inner` at bit 0 with the given [`Layout`].
    #[must_use]
    pub fn with_layout(inner: R, layout: Layout) -> Self {
        Self {
            inner,
            bit_pos: 0,
            layout,
        }
    }
}

#[cfg(feature = "std")]
impl<R: std::io::Read + std::io::Seek> Source for SeekReader<R> {
    fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
        if n > 128 {
            return Err(BitError::new(
                ErrorKind::TooWide { width: n as usize },
                self.bit_pos,
            ));
        }
        let bit_off = self.bit_pos % 8;
        let byte_start = (self.bit_pos / 8) as u64;
        let nbytes = (bit_off + n as usize).div_ceil(8);
        self.inner
            .seek(std::io::SeekFrom::Start(byte_start))
            .map_err(|e| BitError::new(ErrorKind::Io(e.kind()), self.bit_pos))?;
        let mut buf = vec![0u8; nbytes];
        self.inner.read_exact(&mut buf).map_err(|e| {
            let kind = if e.kind() == std::io::ErrorKind::UnexpectedEof {
                ErrorKind::UnexpectedEof {
                    needed: n as usize,
                    remaining: 0,
                }
            } else {
                ErrorKind::Io(e.kind())
            };
            BitError::new(kind, self.bit_pos)
        })?;
        let acc = extract_bits(&buf, bit_off, n as usize, self.layout.bit);
        self.bit_pos += n as usize;
        Ok(acc)
    }
    fn bit_pos(&self) -> usize {
        self.bit_pos
    }
    fn byte_order(&self) -> ByteOrder {
        self.layout.byte
    }
    fn bit_order(&self) -> BitOrder {
        self.layout.bit
    }
    fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
        self.bit_pos = pos; // the actual `io::Seek` happens on the next read
        Ok(())
    }
}

#[cfg(feature = "std")]
impl<R: std::io::Read + std::io::Seek> SeekSource for SeekReader<R> {}

/// Zero-copy `bytes`-crate adapters (the `bytes` feature): own a `Bytes` frame to
/// decode, encode into a `BytesMut` you `freeze()` to a `Bytes` — the async/tokio
/// framing case. Off by default so the core stays dependency-light.
#[cfg(feature = "bytes")]
mod bytes_io {
    use super::{
        BitError, BitOrder, BitReader, BitWriter, ByteOrder, Layout, SeekSource, Sink, Source,
    };

    /// A [`SeekSource`](super::SeekSource) that **owns** a `bytes::Bytes` frame (no
    /// borrow), decoding bits from it. Constructing it from a `Bytes` is a refcount
    /// bump (zero copy).
    #[derive(Clone, Debug)]
    pub struct BytesReader {
        data: bytes::Bytes,
        bit_pos: usize,
        layout: Layout,
    }

    impl BytesReader {
        /// Owns `data`, positioned at bit 0, MSB-first big-endian.
        #[must_use]
        pub fn new(data: bytes::Bytes) -> Self {
            Self::with_layout(data, Layout::default())
        }

        /// Owns `data` with the given [`Layout`](super::Layout).
        #[must_use]
        pub fn with_layout(data: bytes::Bytes, layout: Layout) -> Self {
            Self {
                data,
                bit_pos: 0,
                layout,
            }
        }
    }

    impl Source for BytesReader {
        fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
            let mut br = BitReader::with_layout(&self.data, self.layout);
            br.seek_to_bit(self.bit_pos)?;
            let v = br.read_bits(n)?;
            self.bit_pos = Source::bit_pos(&br);
            Ok(v)
        }
        fn bit_pos(&self) -> usize {
            self.bit_pos
        }
        fn byte_order(&self) -> ByteOrder {
            self.layout.byte
        }
        fn bit_order(&self) -> BitOrder {
            self.layout.bit
        }
        fn seek_to_bit(&mut self, pos: usize) -> Result<(), BitError> {
            self.bit_pos = pos;
            Ok(())
        }
    }

    impl SeekSource for BytesReader {}

    /// A [`Sink`](super::Sink) that encodes into a `bytes::BytesMut`; [`freeze`]
    /// hands off a zero-copy `Bytes`.
    ///
    /// [`freeze`]: BytesWriter::freeze
    #[derive(Clone, Debug, Default)]
    pub struct BytesWriter {
        inner: BitWriter,
    }

    impl BytesWriter {
        /// An empty MSB-first, big-endian writer.
        #[must_use]
        pub fn new() -> Self {
            Self::default()
        }

        /// An empty writer in the given [`Layout`](super::Layout).
        #[must_use]
        pub fn with_layout(layout: Layout) -> Self {
            Self {
                inner: BitWriter::with_layout(layout),
            }
        }

        /// The encoded bytes as a zero-copy `Bytes` (the final partial byte is
        /// zero-padded).
        #[must_use]
        pub fn freeze(self) -> bytes::Bytes {
            bytes::Bytes::from(self.inner.into_bytes())
        }
    }

    impl Sink for BytesWriter {
        fn write_bits(&mut self, value: u128, n: u32) -> Result<(), BitError> {
            self.inner.write_bits(value, n)
        }
        fn bit_pos(&self) -> usize {
            Sink::bit_pos(&self.inner)
        }
        fn byte_order(&self) -> ByteOrder {
            Sink::byte_order(&self.inner)
        }
        fn bit_order(&self) -> BitOrder {
            Sink::bit_order(&self.inner)
        }
    }
}

#[cfg(feature = "bytes")]
pub use bytes_io::{BytesReader, BytesWriter};

#[cfg(test)]
mod unit {
    use super::*;
    use crate::{u4, u12};

    #[test]
    fn unaligned_round_trip() {
        let mut w = BitWriter::new();
        w.write(u4::new(0xA)).unwrap();
        w.write(u12::new(0xBCD)).unwrap();
        assert_eq!(w.bit_len(), 16);
        let bytes = w.into_bytes();
        assert_eq!(bytes, [0xAB, 0xCD]);

        let mut r = BitReader::new(&bytes);
        assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA));
        assert_eq!(r.read::<u12>().unwrap(), u12::new(0xBCD));
        assert_eq!(r.remaining_bits(), 0);
    }

    #[test]
    fn eof_is_an_error_not_a_panic() {
        let mut r = BitReader::new(&[0xFF]);
        assert_eq!(r.read::<u4>().unwrap(), u4::new(0xF));
        let err = r.read_bits(8).unwrap_err();
        assert_eq!(
            err.kind,
            ErrorKind::UnexpectedEof {
                needed: 8,
                remaining: 4
            }
        );
        assert_eq!(err.at, 4, "error records the bit offset");
        assert!(err.field.is_none(), "no field context at the reader level");
    }

    #[test]
    fn too_wide_is_rejected() {
        let mut r = BitReader::new(&[0u8; 32]);
        let err = r.read_bits(129).unwrap_err();
        assert_eq!(err.kind, ErrorKind::TooWide { width: 129 });
    }

    #[test]
    fn stream_reader_matches_slice_up_to_128_bits() {
        // The `Source` contract allows reads up to 128 bits; the forward streaming
        // reader must agree with the slice reader across the whole range, including
        // wide (> 64-bit) and byte-straddling reads.
        let bytes: Vec<u8> = (0u8..16).collect(); // 0x00 01 02 … 0F

        // A single 128-bit read.
        let mut s = StreamBitReader::new(&bytes[..]);
        let mut r = BitReader::new(&bytes);
        assert_eq!(s.read_bits(128).unwrap(), r.read_bits(128).unwrap());

        // A 100-bit then 28-bit split (each crosses byte boundaries and the second
        // starts mid-byte, exercising the leftover-bits path).
        let mut s = StreamBitReader::new(&bytes[..]);
        let mut r = BitReader::new(&bytes);
        assert_eq!(s.read_bits(100).unwrap(), r.read_bits(100).unwrap());
        assert_eq!(s.read_bits(28).unwrap(), r.read_bits(28).unwrap());

        // Over-wide is rejected at 128 now, not 64.
        let mut s = StreamBitReader::new(&bytes[..]);
        assert_eq!(
            s.read_bits(65).unwrap(),
            BitReader::new(&bytes).read_bits(65).unwrap(),
            "a 65-bit read used to be rejected"
        );
        let mut s = StreamBitReader::new(&bytes[..]);
        assert_eq!(
            s.read_bits(129).unwrap_err().kind,
            ErrorKind::TooWide { width: 129 }
        );
    }

    // --- BitError: Display for every ErrorKind, and the offset/field suffix --------

    use alloc::string::{String, ToString};

    #[test]
    fn display_unexpected_eof() {
        let e = BitError::new(
            ErrorKind::UnexpectedEof {
                needed: 16,
                remaining: 8,
            },
            0,
        );
        assert_eq!(
            e.to_string(),
            "unexpected end of input: needed 16 bits, 8 remain at bit 0"
        );
    }

    #[test]
    fn display_incomplete_with_and_without_hint() {
        assert_eq!(
            BitError::new(ErrorKind::Incomplete { needed: Some(3) }, 8).to_string(),
            "incomplete: need ~3 more bytes at bit 8",
        );
        assert_eq!(
            BitError::new(ErrorKind::Incomplete { needed: None }, 8).to_string(),
            "incomplete: need more bytes at bit 8",
        );
    }

    #[test]
    fn display_trailing_too_wide_not_seekable_buffer_full() {
        assert_eq!(
            BitError::new(ErrorKind::TrailingBytes { remaining: 2 }, 16).to_string(),
            "2 trailing bytes after the message at bit 16",
        );
        assert_eq!(
            BitError::new(ErrorKind::TooWide { width: 129 }, 0).to_string(),
            "field width 129 exceeds the 128-bit carrier at bit 0",
        );
        assert_eq!(
            BitError::new(ErrorKind::NotSeekable, 4).to_string(),
            "a position directive ran on a non-seekable source at bit 4",
        );
        assert_eq!(
            BitError::new(ErrorKind::BufferFull { cap: 64 }, 0).to_string(),
            "buffered source exceeded its 64-byte cap at bit 0",
        );
    }

    #[test]
    fn display_bad_magic_and_convert() {
        assert_eq!(
            BitError::bad_magic(0xCAFE, 0x0000, 0).to_string(),
            "bad magic: expected 0xcafe, found 0x0 at bit 0",
        );
        assert_eq!(
            BitError::convert(String::from("nope"), 8).to_string(),
            "conversion failed: nope at bit 8",
        );
    }

    #[test]
    fn display_appends_field_span_when_set() {
        let e = BitError::new(ErrorKind::TooWide { width: 200 }, 12).in_field("payload");
        assert_eq!(
            e.to_string(),
            "field width 200 exceeds the 128-bit carrier at bit 12 (field `payload`)"
        );
    }

    #[test]
    fn display_io_kind() {
        let e = BitError::new(ErrorKind::Io(std::io::ErrorKind::BrokenPipe), 0);
        assert!(e.to_string().starts_with("I/O error:"));
    }

    // --- BitError constructors and the two From bridges ----------------------------

    #[test]
    fn in_field_records_only_the_innermost() {
        let e = BitError::new(ErrorKind::NotSeekable, 0)
            .in_field("inner")
            .in_field("outer"); // ignored — inner already set
        assert_eq!(e.field, Some("inner"));
    }

    #[test]
    fn is_incomplete_is_true_only_for_incomplete() {
        assert!(BitError::new(ErrorKind::Incomplete { needed: None }, 0).is_incomplete());
        assert!(!BitError::new(ErrorKind::NotSeekable, 0).is_incomplete());
    }

    #[test]
    fn construction_error_bridges_to_a_convert_error() {
        let e: BitError = crate::error::Error::ValueTooLarge { value: 99, bits: 4 }.into();
        assert!(matches!(e.kind, ErrorKind::Convert { .. }));
        assert_eq!(e.at, 0);
        assert!(e.to_string().contains("does not fit in 4 bits"));
    }

    #[test]
    fn io_error_bridges_to_an_io_kind() {
        let e: BitError = std::io::Error::new(std::io::ErrorKind::TimedOut, "x").into();
        assert_eq!(e.kind, ErrorKind::Io(std::io::ErrorKind::TimedOut));
        assert_eq!(e.at, 0);
    }

    // --- BitWriter: the LSB-order constructor and the over-wide guard ---------------

    #[test]
    fn writer_with_order_lsb_packs_first_field_in_the_low_bits() {
        let mut w = BitWriter::with_order(BitOrder::Lsb);
        w.write(u4::new(0xA)).unwrap(); // -> low nibble
        w.write(u4::new(0xB)).unwrap(); // -> high nibble
        assert_eq!(w.into_bytes(), [0xBA]);
    }

    #[test]
    fn cursor_layout_matrix_bit_and_byte_order_are_independent() {
        // The two axes — `bit` (how a sub-byte field packs) and `byte` (how a byte-multiple
        // value serializes) — must compose independently at the cursor level (`extract_bits`/
        // `emit_bits`/`apply_byte_order`). Write a nibble pair (bit-order sensitive) then a u16
        // word (byte-order sensitive) under each of the four layouts.
        let combos = [
            (BitOrder::Msb, ByteOrder::Big),
            (BitOrder::Msb, ByteOrder::Little),
            (BitOrder::Lsb, ByteOrder::Big),
            (BitOrder::Lsb, ByteOrder::Little),
        ];
        let mut encs = Vec::new();
        for (bit, byte) in combos {
            let layout = Layout { bit, byte };
            let mut w = BitWriter::with_layout(layout);
            w.write(u4::new(0xA)).unwrap();
            w.write(u4::new(0xB)).unwrap();
            w.write(0x1234u16).unwrap();
            let bytes = w.into_bytes();
            // Every layout round-trips through a reader with the same layout.
            let mut r = BitReader::with_layout(&bytes, layout);
            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA));
            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xB));
            assert_eq!(r.read::<u16>().unwrap(), 0x1234);
            encs.push(bytes);
        }
        // All four corners are golden under the natural-layout rule (`apply_byte_order`):
        // each bit order has a natural byte layout — big-endian under MSB, little-endian
        // under LSB (the DBC-Intel layout) — and the byte-order knob swaps a byte-multiple
        // value only when it differs from that natural layout.
        assert_eq!(encs[0], [0xAB, 0x12, 0x34]); // msb / big    (natural — no swap)
        assert_eq!(encs[1], [0xAB, 0x34, 0x12]); // msb / little (differs — word swaps)
        assert_eq!(encs[2], [0xBA, 0x12, 0x34]); // lsb / big    (differs — word swaps)
        assert_eq!(encs[3], [0xBA, 0x34, 0x12]); // lsb / little (natural — no swap)
        // Flipping byte order changes only the word's bytes, never the nibble byte.
        assert_eq!(encs[0][0], encs[1][0]);
        assert_ne!(encs[0][1..], encs[1][1..]);
        assert_eq!(encs[2][0], encs[3][0]);
        assert_ne!(encs[2][1..], encs[3][1..]);
        // All four corners are pairwise distinct — neither axis aliases the other.
        for i in 0..encs.len() {
            for j in (i + 1)..encs.len() {
                assert_ne!(encs[i], encs[j], "layout corners {i} and {j} alias");
            }
        }
    }

    #[test]
    fn write_bits_rejects_over_128() {
        let mut w = BitWriter::new();
        assert_eq!(
            w.write_bits(0, 129).unwrap_err().kind,
            ErrorKind::TooWide { width: 129 }
        );
    }

    // --- Source/Sink trait DEFAULT methods, via minimal in-test impls --------------

    /// A forward-only `Source` that overrides only the two required methods, so calling
    /// the rest exercises the trait's default `byte_order`/`seek_to_bit`/`read`.
    struct TinySource<'a> {
        bytes: &'a [u8],
        pos: usize,
    }
    impl Source for TinySource<'_> {
        fn read_bits(&mut self, n: u32) -> Result<u128, BitError> {
            let n = n as usize;
            let total = self.bytes.len() * 8;
            if self.pos + n > total {
                return Err(BitError::new(
                    ErrorKind::UnexpectedEof {
                        needed: n,
                        remaining: total - self.pos,
                    },
                    self.pos,
                ));
            }
            let mut acc = 0u128;
            for k in 0..n {
                let p = self.pos + k;
                acc = (acc << 1) | u128::from((self.bytes[p >> 3] >> (7 - (p & 7))) & 1);
            }
            self.pos += n;
            Ok(acc)
        }
        fn bit_pos(&self) -> usize {
            self.pos
        }
    }

    #[test]
    fn source_default_byte_order_is_big() {
        let s = TinySource {
            bytes: &[0],
            pos: 0,
        };
        assert_eq!(s.byte_order(), ByteOrder::Big);
    }

    #[test]
    fn source_default_seek_is_not_seekable() {
        let mut s = TinySource {
            bytes: &[0, 0],
            pos: 0,
        };
        assert_eq!(s.seek_to_bit(8).unwrap_err().kind, ErrorKind::NotSeekable);
    }

    #[test]
    fn source_default_read_dispatches_through_read_bits() {
        let mut s = TinySource {
            bytes: &[0xAB, 0xCD],
            pos: 0,
        };
        assert_eq!(s.read::<u8>().unwrap(), 0xAB);
        assert_eq!(s.read::<u8>().unwrap(), 0xCD);
    }

    /// A `Sink` that overrides only the required methods, exercising the default
    /// `byte_order`/`write`.
    struct TinySink {
        out: Vec<u8>,
        bit: usize,
    }
    impl Sink for TinySink {
        fn write_bits(&mut self, value: u128, n: u32) -> Result<(), BitError> {
            let n = n as usize;
            for k in 0..n {
                let p = self.bit + k;
                if p >> 3 == self.out.len() {
                    self.out.push(0);
                }
                if (value >> (n - 1 - k)) & 1 != 0 {
                    self.out[p >> 3] |= 1 << (7 - (p & 7));
                }
            }
            self.bit += n;
            Ok(())
        }
        fn bit_pos(&self) -> usize {
            self.bit
        }
    }

    #[test]
    fn sink_default_byte_order_is_big() {
        let s = TinySink {
            out: Vec::new(),
            bit: 0,
        };
        assert_eq!(s.byte_order(), ByteOrder::Big);
    }

    #[test]
    fn sink_default_write_dispatches_through_write_bits() {
        let mut s = TinySink {
            out: Vec::new(),
            bit: 0,
        };
        s.write(0xABu8).unwrap();
        s.write(0xCDu8).unwrap();
        assert_eq!(s.out, [0xAB, 0xCD]);
    }

    // --- BitEncode/DecodeWith defaults for a leaf type -----------------------------

    #[test]
    fn leaf_canonical_encode_defaults_to_verbatim() {
        let mut a = BitWriter::new();
        let mut b = BitWriter::new();
        BitEncode::bit_encode(&0xABCDu16, &mut a).unwrap();
        BitEncode::canonical_bit_encode(&0xABCDu16, &mut b).unwrap();
        assert_eq!(a.into_bytes(), b.into_bytes());
    }

    #[test]
    fn leaf_encode_mode_default_is_verbatim() {
        assert_eq!(BitEncode::encode_mode(&0u16), EncodeMode::Verbatim);
    }

    #[test]
    fn leaf_decode_with_and_encode_with_unit_args() {
        let mut r = BitReader::new(&[0xAB, 0xCD]);
        assert_eq!(
            <u16 as DecodeWith<()>>::decode_with(&mut r, ()).unwrap(),
            0xABCD
        );
        let mut w = BitWriter::new();
        EncodeWith::encode_with(&0xABCDu16, &mut w, ()).unwrap();
        assert_eq!(w.into_bytes(), [0xAB, 0xCD]);
    }

    #[test]
    fn bitbuf_bounded_reports_its_capacity() {
        assert_eq!(BitBuf::bounded(64).capacity(), Some(64));
        assert_eq!(BitBuf::new().capacity(), None);
        assert_eq!(BitBuf::with_capacity(64).capacity(), None); // pre-reserved, not a hard cap
    }

    #[test]
    fn capacity_error_display() {
        let e = CapacityError {
            cap: 4,
            requested: 5,
        };
        assert_eq!(
            e.to_string(),
            "bitbuf is full: 5 bytes needed exceeds the 4-byte capacity"
        );
    }

    #[test]
    fn count_prefix_primitive_boundaries() {
        // In-range: exact fit at the top of the range.
        assert_eq!(u8::try_from_len(255).unwrap(), 255u8);
        // Out of range: checked, not wrapped.
        assert_eq!(
            u8::try_from_len(256).unwrap_err(),
            crate::error::Error::ValueTooLarge {
                value: 256,
                bits: 8
            }
        );
        assert_eq!(u16::try_from_len(65_535).unwrap(), 65_535u16);
        assert_eq!(u8::to_count(200), 200);
        assert_eq!(u32::to_count(70_000), 70_000);
    }

    #[test]
    fn count_prefix_uint_boundaries() {
        // u12: 4095 fits, 4096 does not.
        assert_eq!(u12::try_from_len(4095).unwrap(), u12::new(4095));
        assert_eq!(
            u12::try_from_len(4096).unwrap_err(),
            crate::error::Error::ValueTooLarge {
                value: 4096,
                bits: 12
            }
        );
        assert_eq!(u12::new(4095).to_count(), 4095);
    }

    #[test]
    fn count_prefix_uint_never_truncates_before_the_check() {
        // 300 as u8 would wrap to 44 — a masked `from_raw`/`try_new(len as u8)` path
        // would then accept it. The widen-then-compare must reject instead.
        assert_eq!(
            u4::try_from_len(300).unwrap_err(),
            crate::error::Error::ValueTooLarge {
                value: 300,
                bits: 4
            }
        );
    }

    #[test]
    fn count_prefix_round_trips() {
        for len in [0usize, 1, 15, 255, 4095] {
            assert_eq!(u16::try_from_len(len).unwrap().to_count(), len);
            assert_eq!(u12::try_from_len(len).unwrap().to_count(), len);
        }
    }

    #[test]
    fn bulk_bytes_round_trip() {
        let mut w = BitWriter::new();
        w.write_bytes(&[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
        let bytes = w.into_bytes();
        assert_eq!(bytes, [0xDE, 0xAD, 0xBE, 0xEF]);
        let mut r = BitReader::new(&bytes);
        assert_eq!(r.read_bytes(4).unwrap(), [0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(r.remaining_bits(), 0);
    }

    #[test]
    fn bulk_bytes_work_at_a_bit_offset() {
        // Bytes need not be aligned: write a nibble, then bytes straddling.
        let mut w = BitWriter::new();
        w.write(u4::new(0xF)).unwrap();
        w.write_bytes(&[0xAB, 0xCD]).unwrap();
        let bytes = w.into_bytes();
        assert_eq!(bytes, [0xFA, 0xBC, 0xD0]);
        let mut r = BitReader::new(&bytes);
        assert_eq!(r.read::<u4>().unwrap(), u4::new(0xF));
        assert_eq!(r.read_bytes(2).unwrap(), [0xAB, 0xCD]);
    }

    #[test]
    fn read_bytes_hostile_length_is_eof_not_alloc() {
        // A huge n against a 2-byte source: push-per-byte means a fast EOF, no
        // pre-allocation from the untrusted length.
        let mut r = BitReader::new(&[0x01, 0x02]);
        let err = r.read_bytes(usize::MAX).unwrap_err();
        assert!(matches!(err.kind, ErrorKind::UnexpectedEof { .. }));
    }

    #[test]
    fn read_into_fills_and_errors_short() {
        let mut r = BitReader::new(&[0x0A, 0x0B, 0x0C]);
        let mut buf = [0u8; 3];
        r.read_into(&mut buf).unwrap();
        assert_eq!(buf, [0x0A, 0x0B, 0x0C]);

        let mut r = BitReader::new(&[0x0A]);
        let mut buf = [0u8; 3];
        let err = r.read_into(&mut buf).unwrap_err();
        assert!(matches!(err.kind, ErrorKind::UnexpectedEof { .. }));
    }
}

#[cfg(test)]
mod component {
    //! Component tests: one runtime adapter in isolation (the I/O ladder over the
    //! bit cursors). `cargo test component` runs these alongside the other layers.
    /// `bitstream_source.rs` — Generic recursion over `Source` (ROADMAP Phase 1, chunk B1): one derived
    mod source {

        use bnb::{BitDecode, BitEncode, BitReader, BitWriter, StreamBitReader, u4, u12};

        #[derive(BitDecode, BitEncode, Debug, PartialEq, Eq)]
        struct Word {
            a: u4,
            b: u12, // 16 bits; all <= 64 so the streaming reader handles it too
        }

        #[test]
        fn decodes_over_slice_and_stream_identically() {
            let word = Word {
                a: u4::new(0xA),
                b: u12::new(0xBCD),
            };
            let mut w = BitWriter::new();
            word.bit_encode(&mut w).unwrap();
            let bytes = w.into_bytes();
            assert_eq!(bytes, [0xAB, 0xCD]);

            // Source 1 — in-memory slice cursor (random-access, full power).
            let mut slice = BitReader::new(&bytes);
            assert_eq!(Word::bit_decode(&mut slice).unwrap(), word);

            // Source 2 — a forward `Read` (`&[u8]` is `Read` but NOT `Seek`); same code,
            // no rewrite, no Seek requirement.
            let mut stream = StreamBitReader::new(&bytes[..]);
            assert_eq!(Word::bit_decode(&mut stream).unwrap(), word);
        }

        #[test]
        fn stream_reader_honors_a_little_endian_layout() {
            use bnb::{Layout, bin};
            #[bin(little)]
            #[derive(Debug, PartialEq)]
            struct Le {
                v: u32,
            }
            let bytes = Le { v: 0x1122_3344 }.to_bytes().unwrap();
            assert_eq!(bytes, [0x44, 0x33, 0x22, 0x11]); // little-endian on the wire

            // A default stream reader would misread it big-endian; with the type's layout
            // it decodes correctly over a forward `Read`.
            let mut stream = StreamBitReader::with_layout(&bytes[..], <Le as BitEncode>::LAYOUT);
            assert_eq!(Le::bit_decode(&mut stream).unwrap(), Le { v: 0x1122_3344 });
            // (The default `new` reader, big-endian, would read the bytes reversed.)
            let mut msb = StreamBitReader::with_layout(&bytes[..], Layout::default());
            assert_ne!(Le::bit_decode(&mut msb).unwrap().v, 0x1122_3344);
        }
    }

    /// `bitstream_seek.rs` — Spike (DESIGN §11): seeking is free on the in-memory cursor, and a
    mod seek {

        use bnb::{BitReader, StreamBitReader, u4};

        #[test]
        fn seek_and_align_need_no_seek_trait() {
            // 3 bytes: 0xAB, 0xCD, 0xEF.
            let bytes = [0xABu8, 0xCD, 0xEF];
            let mut r = BitReader::new(&bytes);

            // Read a nibble, jump to an absolute bit offset, read, then jump back —
            // exactly the move DNS name-compression needs, with no Seek machinery.
            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA));
            r.seek_to_bit(16).unwrap(); // -> third byte
            assert_eq!(r.read_bits(8).unwrap(), 0xEF);
            r.seek_to_bit(4).unwrap(); // back to the low nibble of byte 0
            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xB));

            // align_to_byte snaps the cursor forward to the next byte boundary.
            r.seek_to_bit(9).unwrap();
            r.align_to_byte();
            assert_eq!(r.bit_pos(), 16);

            // Seeking past the end is a clean error, not a panic.
            assert!(r.seek_to_bit(999).is_err());
        }

        #[test]
        fn forward_only_stream_reader_requires_only_read() {
            // `&[u8]` implements `std::io::Read` but NOT `std::io::Seek`. That this
            // compiles and runs is the whole point: forward bit parsing drops the Seek
            // requirement binrw imposes uniformly.
            let data = [0xABu8, 0xCD];
            let src: &[u8] = &data;
            let mut r = StreamBitReader::new(src);

            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xA));
            assert_eq!(r.read::<u4>().unwrap(), u4::new(0xB));
            assert_eq!(r.read_bits(8).unwrap(), 0xCD);
            // Past the end -> error, not panic.
            assert!(r.read_bits(1).is_err());
        }
    }

    /// `bitstream_entry.rs` — Entry points (ROADMAP Phase 1, chunk B2): `decode`/`peek`/`decode_exact`/
    mod entry {

        use bnb::{
            BitDecode, BitEncode, BitReader, EncodeExt, ErrorKind, StreamBitReader, u4, u12,
        };
        use std::io::Cursor;

        #[derive(BitDecode, BitEncode, Debug, PartialEq, Eq, Clone, Copy)]
        struct Word {
            a: u4,
            b: u12,
        }

        fn sample() -> (Word, [u8; 2]) {
            (
                Word {
                    a: u4::new(0xA),
                    b: u12::new(0xBCD),
                },
                [0xAB, 0xCD],
            )
        }

        #[test]
        fn to_bytes_peek_and_tail_tolerance() {
            let (w, bytes) = sample();
            assert_eq!(w.to_bytes().unwrap(), bytes);
            assert_eq!(Word::peek(&bytes).unwrap(), w);

            // peek is tail-tolerant: a trailing byte is ignored.
            let mut padded = bytes.to_vec();
            padded.push(0xFF);
            assert_eq!(Word::peek(&padded).unwrap(), w);
        }

        #[test]
        fn decode_advances_a_cursor() {
            let (w, bytes) = sample();
            let mut both = bytes.to_vec();
            both.extend_from_slice(&bytes); // two messages back to back

            let mut cur = BitReader::new(&both);
            assert_eq!(Word::decode(&mut cur).unwrap(), w);
            assert_eq!(cur.bit_pos(), 16, "advanced past the first message");
            assert_eq!(Word::decode(&mut cur).unwrap(), w);
            assert_eq!(cur.bit_pos(), both.len() * 8, "consumed both");
        }

        #[test]
        fn decode_all_and_iter_collect_back_to_back() {
            let (w, bytes) = sample();
            let mut both = bytes.to_vec();
            both.extend_from_slice(&bytes);

            // decode_all — eager; decode_iter — lazy. Both layout-baked and bit-aware.
            assert_eq!(Word::decode_all(&both).unwrap(), vec![w, w]);
            let collected: Result<Vec<_>, _> = Word::decode_iter(&both).collect();
            assert_eq!(collected.unwrap(), vec![w, w]);
        }

        #[test]
        fn decode_all_of_a_zero_width_type_yields_nothing() {
            use bnb::{BitDecode, BitError, Layout, Source};
            #[derive(Debug, PartialEq)]
            struct Zero;
            impl BitDecode for Zero {
                fn bit_decode<S: Source>(_r: &mut S) -> Result<Self, BitError> {
                    Ok(Zero)
                }
            }
            // A zero-width type makes no progress; over a non-empty buffer `decode_all` must
            // yield an empty `Vec` (not one spurious element) and not spin.
            let out: Vec<Zero> =
                bnb::__private::decode_all(&[0xFF, 0xFF], Layout::default()).unwrap();
            assert!(out.is_empty());
        }

        #[test]
        fn decode_errors_on_short_cursor() {
            let short = [0xABu8]; // one byte; Word needs two
            let mut cur = BitReader::new(&short);
            let err = Word::decode(&mut cur).unwrap_err();
            assert!(matches!(err.kind, ErrorKind::UnexpectedEof { .. }));
        }

        #[test]
        fn decode_exact_rejects_trailing_bytes() {
            let (w, bytes) = sample();
            assert_eq!(Word::decode_exact(&bytes).unwrap(), w);

            let mut padded = bytes.to_vec();
            padded.push(0xFF);
            let err = Word::decode_exact(&padded).unwrap_err();
            assert_eq!(err.kind, ErrorKind::TrailingBytes { remaining: 1 });
        }

        #[test]
        fn encode_to_any_write() {
            let (w, bytes) = sample();
            let mut sink = Cursor::new(Vec::new());
            w.encode(&mut sink).unwrap();
            assert_eq!(sink.into_inner(), bytes);
        }

        #[test]
        fn encode_io_error_is_reported() {
            struct Full;
            impl std::io::Write for Full {
                fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                    Err(std::io::Error::new(std::io::ErrorKind::WriteZero, "full"))
                }
                fn flush(&mut self) -> std::io::Result<()> {
                    Ok(())
                }
            }
            let (w, _) = sample();
            let err = w.encode(&mut Full).unwrap_err();
            assert_eq!(err.kind, ErrorKind::Io(std::io::ErrorKind::WriteZero));
        }

        #[test]
        fn decode_explicit_cursor() {
            let (w, bytes) = sample();
            let mut r = BitReader::new(&bytes);
            assert_eq!(Word::decode(&mut r).unwrap(), w);
        }

        #[test]
        fn streaming_shortfall_is_incomplete_not_eof() {
            let (_, bytes) = sample();
            // Only the first byte available over a stream: the shortfall is the retry
            // signal, not a definitive EOF.
            let mut stream = StreamBitReader::new(&bytes[..1]);
            let err = Word::decode(&mut stream).unwrap_err();
            assert!(err.is_incomplete(), "stream shortfall is incomplete: {err}");
            assert!(matches!(err.kind, ErrorKind::Incomplete { .. }));
            assert_eq!(err.field, Some("b"), "still records the field span");
        }
    }

    /// `bitstream_errors.rs` — Position-aware errors (ROADMAP Phase 1): a decode/encode failure reports the
    mod errors {

        use bnb::{BitDecode, BitEncode, BitError, BitReader, BitWriter, ErrorKind, u4, u12};

        #[derive(BitDecode, BitEncode, Debug, PartialEq, Eq)]
        struct Header {
            a: u4,
            b: u12, // a + b = 16 bits
        }

        #[test]
        fn round_trips() {
            let h = Header {
                a: u4::new(0xA),
                b: u12::new(0xBCD),
            };
            let mut w = BitWriter::new();
            h.bit_encode(&mut w).unwrap();
            let bytes = w.into_bytes();
            assert_eq!(bytes, [0xAB, 0xCD]);

            let mut r = BitReader::new(&bytes);
            assert_eq!(Header::bit_decode(&mut r).unwrap(), h);
        }

        #[test]
        fn decode_eof_reports_offset_and_field() {
            // One byte: `a` (4 bits) decodes; `b` (12 bits) runs off the end at bit 4.
            let bytes = [0xAB];
            let mut r = BitReader::new(&bytes);
            let err: BitError = Header::bit_decode(&mut r).unwrap_err();

            assert_eq!(err.field, Some("b"), "names the field that failed");
            assert_eq!(err.at, 4, "records the bit offset where decoding stopped");
            assert_eq!(
                err.kind,
                ErrorKind::UnexpectedEof {
                    needed: 12,
                    remaining: 4
                }
            );

            let msg = err.to_string();
            assert!(msg.contains("field `b`"), "message names the field: {msg}");
            assert!(msg.contains("at bit 4"), "message names the offset: {msg}");
        }

        #[test]
        fn innermost_field_wins_the_span() {
            // The error originates in `b`'s read; the outer struct must not overwrite it.
            let mut r = BitReader::new(&[0xAB]);
            let err = Header::bit_decode(&mut r).unwrap_err();
            assert_eq!(err.field, Some("b"));
        }
    }

    /// `bin_io_adapter.rs` — `Source::as_read` / `Sink::as_write`: hand a bnb cursor to `std::io`-based code
    mod io_adapter {

        use bnb::{BitError, Sink, Source, bin};
        use std::io::{Read, Write};

        // A length-prefixed blob, read and written through std::io::Read/Write *views* over the
        // bnb cursor — exactly how you'd drop in a `Read`/`Write`-based parser or a stream
        // wrapper (decompressor, checksummer, …) from a custom codec.
        fn read_blob<S: Source>(r: &mut S) -> Result<Vec<u8>, BitError> {
            let len: u8 = r.read()?;
            let mut buf = vec![0u8; len as usize];
            r.as_read().read_exact(&mut buf)?; // io::Error -> BitError via `?`
            Ok(buf)
        }

        fn write_blob<K: Sink>(blob: &[u8], w: &mut K) -> Result<(), BitError> {
            w.write(u8::try_from(blob.len()).unwrap())?;
            w.as_write().write_all(blob)?;
            Ok(())
        }

        #[bin(big)]
        #[derive(Debug, PartialEq)]
        struct Msg {
            #[br(parse_with = read_blob)]
            #[bw(write_with = write_blob)]
            data: Vec<u8>,
        }

        #[test]
        fn as_read_as_write_roundtrip_through_std_io() {
            let m = Msg {
                data: vec![0xDE, 0xAD, 0xBE, 0xEF],
            };
            let bytes = m.to_bytes().unwrap();
            assert_eq!(bytes, [0x04, 0xDE, 0xAD, 0xBE, 0xEF]);
            assert_eq!(Msg::decode_exact(&bytes).unwrap(), m);
        }

        #[test]
        fn as_read_short_read_reports_eof() {
            use bnb::BitReader;
            // Only 2 bytes available but the length prefix claims 4 -> read_exact hits EOF,
            // which surfaces as a BitError (not a panic).
            let mut r = BitReader::new(&[0x04, 0xAA, 0xBB]);
            assert!(read_blob(&mut r).is_err());
        }
    }

    /// `bin_buf_source.rs` — `BufSource` (ROADMAP Phase 3): a seekable `Source` over a forward `Read`. It
    mod buf_source {

        use bnb::{BufSource, ErrorKind, Source, bin, u4};

        // A forward-only reader (a socket-like stream) yielding one byte per `read`.
        struct Chunked {
            data: Vec<u8>,
            pos: usize,
        }
        impl std::io::Read for Chunked {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.pos >= self.data.len() || buf.is_empty() {
                    return Ok(0);
                }
                buf[0] = self.data[self.pos];
                self.pos += 1;
                Ok(1)
            }
        }

        #[bin]
        #[derive(Debug, PartialEq, Eq, Clone)]
        struct Frame {
            flags: u4,
            #[br(restore_position)]
            peek: u8,
            value: u16,
        }

        #[test]
        fn seek_using_message_over_a_nonseekable_stream() {
            // Wire bytes from the restore_position round-trip: flags=5, value=0xABCD.
            let wire = vec![0x5A, 0xBC, 0xD0];
            let mut src = BufSource::new(Chunked { data: wire, pos: 0 });
            let f = Frame::decode(&mut src).unwrap();
            assert_eq!(f.value, 0xABCD);
            assert_eq!(f.peek, 0xAB, "the rewind re-read retained bytes");
        }

        #[test]
        fn retention_cap_bounds_the_buffer() {
            // A 1-byte cap; reading a 16-bit value needs 2 bytes -> BufferFull.
            let mut src = BufSource::with_cap(
                Chunked {
                    data: vec![0xFF; 8],
                    pos: 0,
                },
                1,
            );
            let err = src.read_bits(16).unwrap_err();
            assert!(matches!(err.kind, ErrorKind::BufferFull { cap: 1 }));
        }

        #[test]
        fn over_wide_read_is_rejected() {
            let mut src = BufSource::new(Chunked {
                data: vec![0u8; 32],
                pos: 0,
            });
            assert!(matches!(
                src.read_bits(129).unwrap_err().kind,
                ErrorKind::TooWide { width: 129 }
            ));
        }

        #[test]
        fn running_out_mid_field_is_incomplete() {
            // Only one byte is available, but a 16-bit read needs two — the stream ends (EOF)
            // partway through, which is the streaming "need more" signal, not a definitive EOF.
            let mut src = BufSource::new(Chunked {
                data: vec![0xAB],
                pos: 0,
            });
            assert!(matches!(
                src.read_bits(16).unwrap_err().kind,
                ErrorKind::Incomplete { .. }
            ));
        }

        #[test]
        fn an_io_error_from_the_reader_propagates() {
            struct Failing;
            impl std::io::Read for Failing {
                fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::ConnectionReset,
                        "boom",
                    ))
                }
            }
            let mut src = BufSource::new(Failing);
            assert!(matches!(
                src.read_bits(8).unwrap_err().kind,
                ErrorKind::Io(_)
            ));
        }
    }

    /// `bin_seek_reader.rs` — `SeekReader` (ROADMAP Phase 3b): a `SeekSource` over a `Read + Seek` (a file-like)
    mod seek_reader {

        use bnb::{SeekReader, bin, u4};
        use std::io::Cursor;

        #[bin]
        #[derive(Debug, PartialEq, Eq, Clone)]
        struct Frame {
            flags: u4,
            #[br(restore_position)]
            peek: u8,
            value: u16,
        }

        #[test]
        fn seek_reader_over_a_file_like_source() {
            let wire = vec![0x5A, 0xBC, 0xD0]; // flags=5, value=0xABCD (restore_position layout)
            let mut src = SeekReader::new(Cursor::new(wire));
            let f = Frame::decode(&mut src).unwrap();
            assert_eq!(f.value, 0xABCD);
            assert_eq!(f.peek, 0xAB, "rewound and re-read via io::Seek");
        }

        #[test]
        fn over_wide_read_is_rejected() {
            use bnb::{ErrorKind, Source};
            let mut src = SeekReader::new(Cursor::new(vec![0u8; 32]));
            assert!(matches!(
                src.read_bits(129).unwrap_err().kind,
                ErrorKind::TooWide { width: 129 }
            ));
        }

        #[test]
        fn reading_past_the_end_is_unexpected_eof() {
            use bnb::ErrorKind;
            #[bin(big)]
            #[derive(Debug)]
            struct Quad {
                v: u32,
            }
            // Only two of the four needed bytes are present.
            let mut src = SeekReader::new(Cursor::new(vec![0x12, 0x34]));
            assert!(matches!(
                Quad::decode(&mut src).unwrap_err().kind,
                ErrorKind::UnexpectedEof { .. }
            ));
        }

        #[test]
        fn little_endian_layout_is_honored() {
            #[bin(little)]
            #[derive(Debug, PartialEq)]
            struct Le {
                v: u32,
            }
            // `with_layout` carries the message's little-endian order onto the reader.
            let mut src = SeekReader::with_layout(
                Cursor::new(vec![0x78, 0x56, 0x34, 0x12]),
                <Le as bnb::BitEncode>::LAYOUT,
            );
            assert_eq!(Le::decode(&mut src).unwrap(), Le { v: 0x1234_5678 });
        }
    }

    /// `bitbuf.rs` — `BitBuf` — a push/pull, bit-aware incremental decode buffer.
    mod bitbuf {

        use bnb::{BitBuf, BitDecode, BitEncode, BitWriter, bin, u4};

        #[bin(big)]
        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
        struct Frame {
            tag: u4,
            val: u8,
        } // 12 bits — a non-byte-aligned boundary

        #[bin(little)]
        #[derive(Debug, PartialEq, Eq, Clone, Copy)]
        struct LeMsg {
            a: u16,
            b: u32,
        } // little-endian, byte-aligned (6 bytes)

        #[test]
        fn pull_is_none_until_a_whole_message_arrives_then_reclaims() {
            let m = LeMsg {
                a: 0x1234,
                b: 0xDEAD_BEEF,
            };
            let bytes = m.to_bytes().unwrap();

            let mut bb = BitBuf::new();
            bb.push(&bytes[..3]); // only part of the message
            assert_eq!(bb.pull::<LeMsg>().unwrap(), None); // wait for more — buffer untouched
            assert_eq!(bb.bit_len(), 24);

            bb.push(&bytes[3..]); // the rest
            assert_eq!(bb.pull::<LeMsg>().unwrap(), Some(m)); // decodes (little-endian honored via LAYOUT)
            assert!(bb.is_empty()); // consumed bytes reclaimed
            assert_eq!(bb.pull::<LeMsg>().unwrap(), None);
        }

        #[test]
        fn reassembles_sub_byte_boundary_messages_across_pushes() {
            let f1 = Frame {
                tag: u4::new(0xA),
                val: 0x12,
            };
            let f2 = Frame {
                tag: u4::new(0xB),
                val: 0x34,
            };
            // Pack contiguously: 24 bits / 3 bytes, with f2 starting at bit 12 (mid-byte).
            let mut w = BitWriter::new();
            f1.bit_encode(&mut w).unwrap();
            f2.bit_encode(&mut w).unwrap();
            let wire = w.into_bytes();

            let mut bb = BitBuf::new();
            let mut out = Vec::new();
            // f1 spans the chunk boundary; the bit cursor keeps f2's sub-byte alignment.
            for chunk in [&wire[0..1], &wire[1..3]] {
                bb.push(chunk);
                while let Some(f) = bb.pull::<Frame>().unwrap() {
                    out.push(f);
                }
            }
            assert_eq!(out, vec![f1, f2]);
            assert!(bb.is_empty());
        }

        #[test]
        fn clear_and_capacity() {
            let mut bb = BitBuf::with_capacity(64);
            bb.push(&[1, 2, 3]);
            assert_eq!(bb.bit_len(), 24);
            bb.clear();
            assert!(bb.is_empty());
        }

        // BitBuf is a Source: it reads through the same `bit_decode` entry the renamed `decode` uses.
        // The default-order buffer reads a big message; `with_layout` reads a little one (this also
        // proves byte order is applied exactly once — no double-ordering in the Source delegation).
        #[test]
        fn reads_as_a_source_respecting_layout() {
            // big message via a default (msb/big) BitBuf
            let f = Frame {
                tag: u4::new(0xC),
                val: 0x9A,
            };
            let mut bb = BitBuf::new();
            bb.push(&f.to_bytes().unwrap());
            assert_eq!(<Frame as BitDecode>::bit_decode(&mut bb).unwrap(), f);

            // little message via a layout-configured BitBuf (byte-aligned, so compact fully drains)
            let m = LeMsg {
                a: 0x1234,
                b: 0xDEAD_BEEF,
            };
            let mut bb = BitBuf::new().with_layout(<LeMsg as BitEncode>::LAYOUT);
            bb.push(&m.to_bytes().unwrap());
            let got = <LeMsg as BitDecode>::bit_decode(&mut bb).unwrap();
            assert_eq!(got, m); // would be byte-swapped if ordering double-applied
            bb.compact(); // Source path doesn't auto-reclaim
            assert!(bb.is_empty());
        }

        // BitBuf is a `SeekSource`, so a `restore_position` message decodes over it through the
        // `decode` cursor path — exercising BitBuf's `seek_to_bit` (the rewind).
        #[test]
        fn as_a_seek_source_a_restore_position_message_decodes() {
            #[bin(big)]
            #[derive(Debug, PartialEq, Eq)]
            struct Peeked {
                #[br(restore_position)]
                tag: u8,
                full: u16,
            }
            let mut bb = BitBuf::new();
            bb.push(&[0xAB, 0xCD]);
            let p = Peeked::decode(&mut bb).unwrap();
            assert_eq!((p.tag, p.full), (0xAB, 0xABCD));
        }

        // --- bounded (alloc-once) mode -----------------------------------------------------

        #[bin(big)]
        #[derive(Debug, PartialEq, Eq)]
        struct Two {
            v: u16,
        }

        #[test]
        fn bounded_try_push_respects_capacity_then_reclaims_in_place() {
            use bnb::CapacityError;
            let mut bb = BitBuf::bounded(4);
            assert_eq!(bb.capacity(), Some(4));
            bb.try_push(&[0x00, 0x01]).unwrap(); // 2 bytes
            bb.try_push(&[0x00, 0x02]).unwrap(); // 4 bytes — full
            // a 5th byte can't fit until something is drained
            assert!(matches!(
                bb.try_push(&[0xFF]),
                Err(CapacityError { cap: 4, .. })
            ));
            // drain one message → 2 live bytes; the dead prefix is reclaimed in place to fit more
            assert_eq!(bb.pull::<Two>().unwrap(), Some(Two { v: 1 }));
            bb.try_push(&[0x00, 0x03]).unwrap();
            assert_eq!(bb.pull::<Two>().unwrap(), Some(Two { v: 2 }));
            assert_eq!(bb.pull::<Two>().unwrap(), Some(Two { v: 3 }));
            assert!(bb.is_empty());
        }

        #[test]
        fn grow_raises_a_bounded_capacity() {
            let mut bb = BitBuf::bounded(2);
            bb.try_push(&[0x00, 0x01]).unwrap();
            assert!(bb.try_push(&[0x02]).is_err()); // full at 2
            bb.grow(2); // the one explicit allocation
            assert_eq!(bb.capacity(), Some(4));
            bb.try_push(&[0x02, 0x03]).unwrap();
            assert_eq!(bb.bit_len(), 32);
        }

        #[test]
        fn unbounded_try_push_never_fails() {
            let mut bb = BitBuf::new();
            assert_eq!(bb.capacity(), None);
            bb.try_push(&[1, 2, 3]).unwrap(); // no cap → grows, never errors
            assert_eq!(bb.bit_len(), 24);
        }

        #[test]
        fn a_streaming_push_pull_loop_stays_within_a_tiny_cap() {
            // Pushed one message at a time and drained immediately, a bounded buffer reuses the same
            // allocation forever: each try_push fits because the prior message was reclaimed in place.
            let mut bb = BitBuf::bounded(2);
            for i in 0..100u16 {
                bb.try_push(&i.to_be_bytes()).unwrap();
                assert_eq!(bb.pull::<Two>().unwrap(), Some(Two { v: i }));
            }
            assert!(bb.is_empty());
        }
    }

    #[cfg(feature = "bytes")]
    /// `bin_bytes.rs` — `bytes` integration (ROADMAP Phase 3, the `bytes` feature): zero-copy
    mod bytes_adapters {

        use bnb::{BitEncode, BytesReader, BytesWriter, bin, u4, u12};

        #[bin]
        #[derive(Debug, PartialEq, Eq, Clone)]
        struct Frame {
            a: u4,
            b: u12,
        }

        #[test]
        fn round_trip_through_bytes() {
            let f = Frame {
                a: u4::new(0xA),
                b: u12::new(0x123),
            };

            // Encode into a BytesWriter, then freeze to a zero-copy Bytes.
            let mut w = BytesWriter::new();
            f.bit_encode(&mut w).unwrap();
            let frozen = w.freeze();
            assert_eq!(&frozen[..], &[0xA1, 0x23]);

            // Decode from an owned Bytes via BytesReader.
            let mut r = BytesReader::new(frozen.clone());
            let decoded = Frame::decode(&mut r).unwrap();
            assert_eq!(decoded, f);
        }

        // A `restore_position` message decodes over `BytesReader` (a `SeekSource`), exercising its
        // `bit_pos`/`seek_to_bit`. The frame is produced via `BytesWriter::freeze` (no `bytes::` name).
        #[test]
        fn bytes_reader_seek_and_bit_pos() {
            use bnb::{Sink, Source};
            #[bin(big)]
            #[derive(Debug, PartialEq, Eq)]
            struct Peeked {
                #[br(restore_position)]
                tag: u8,
                full: u16,
            }
            let mut w = BytesWriter::new();
            w.write(0xABu8).unwrap();
            w.write(0xCDu8).unwrap();
            let mut r = BytesReader::new(w.freeze());
            assert_eq!(r.bit_pos(), 0);
            let p = Peeked::decode(&mut r).unwrap();
            assert_eq!((p.tag, p.full), (0xAB, 0xABCD));
        }

        #[test]
        fn bytes_writer_with_layout_and_bit_pos() {
            use bnb::{BitOrder, ByteOrder, Layout, Sink};
            let mut w = BytesWriter::with_layout(Layout {
                bit: BitOrder::Lsb,
                byte: ByteOrder::Big,
            });
            assert_eq!(w.bit_pos(), 0);
            w.write(u4::new(0xA)).unwrap();
            assert_eq!(w.bit_pos(), 4);
        }
    }
}