binrw 0.15.1

A Rust crate for helping read structs from binary data using ✨macro magic✨
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
Glossary of directives in binrw attributes (`#[br]`, `#[bw]`, `#[brw]`).

<style>
    .show-rw {
        background: var(--main-background-color, #fff);
        border: thin solid #ddd;
        box-shadow: -0.25rem 0.25rem 0 var(--main-background-color, #fff);
        display: flex;
        list-style: none;
        margin: 0 0 -2.25rem auto;
        gap: 0.5rem;
        padding: 0.25rem 1rem 0.75rem;
        position: sticky;
        top: 2rem;
        width: fit-content;
        z-index: 1;
    }
    .show-rw > legend {
        background: var(--main-background-color, #fff);
        padding: 0 0.15rem;
    }
    .show-rw [for]::before {
        background-clip: content-box;
        border: thin solid var(--main-color, #000);
        border-radius: 0.5em;
        content: '';
        display: inline-block;
        height: 0.5em;
        margin-right: 0.3em;
        padding: 1px;
        width: 0.5em;
    }
    #show_write:checked ~ .br:not(.bw),
    #show_write:checked ~ * .br:not(.bw),
    #show_read:checked ~ .bw:not(.br),
    #show_read:checked ~ * .bw:not(.br),
    #show_both:not(:checked) ~ .brw,
    #show_both:not(:checked) ~ * .brw {
        display: none;
    }
    #show_read:checked ~ .show-rw [for=show_read]::before,
    #show_write:checked ~ .show-rw [for=show_write]::before,
    #show_both:checked ~ .show-rw [for=show_both]::before {
        background-color: var(--main-color, #000);
    }
    .br, .bw, .brw {
        display: contents;
    }
    /* undoing rustdoc style that does not behave appropriately when wrapped */
    .br .example-wrap:last-child,
    .bw .example-wrap:last-child,
    .brw .example-wrap:last-child {
        margin-bottom: 10px;
    }
    .br > p:last-child,
    .bw > p:last-child,
    .brw > p:last-child,
    .br .warning,
    .bw .warning,
    .brw .warning {
        margin-bottom: .75em;
    }
    .docblock hr {
        margin: 1em auto;
        border: 0 solid;
        border-top-width: thin;
    }
    #show_both:checked ~ span.brw + span.br,
    #show_both:checked ~ span.brw + span.br + span.bw,
    #show_both:checked ~ * span.brw + span.br,
    #show_both:checked ~ * span.brw + span.br + span.bw {
        display: none;
    }
    #show_both:checked ~ span.br + span.bw::before,
    #show_both:checked ~ * span.br + span.bw::before {
        content: '/';
    }
</style>
<input name="show_rw" id="show_read" type="radio" hidden>
<input name="show_rw" id="show_write" type="radio" hidden>
<input name="show_rw" id="show_both" type="radio" hidden checked>
<fieldset class="show-rw">
  <legend>View for:</legend>
  <label for="show_read"><code>#[br]</code></label>
  <label for="show_write"><code>#[bw]</code></label>
  <label for="show_both">Both</label>
</fieldset>

# List of directives

| r/w | Directive | Supports[*] | Description
|-----|-----------|----------|------------
| rw  | [`align_after`]#padding-and-alignment | field | Aligns the <span class="br">reader</span><span class="bw">writer</span> to the Nth byte after a field.
| rw  | [`align_before`]#padding-and-alignment | field | Aligns the <span class="br">reader</span><span class="bw">writer</span> to the Nth byte before a field.
| rw  | [`args`]#arguments | field | Passes arguments to another binrw object.
| rw  | [`args_raw`]#arguments | field | Like `args`, but specifies a single variable containing the arguments.
| rw  | [`assert`]#assert | struct, field, non-unit enum, data variant | Asserts that a condition is true. Can be used multiple times.
| rw  | [`big`]#byte-order | all except unit variant | Sets the byte order to big-endian.
| rw  | [`calc`]#calculations | field | Computes the value of a field instead of <span class="br">reading data</span><span class="bw">using a field</span>.
| r   | [`count`]#count | field | Sets the length of a vector.
| r   | [`dbg`]#debug | field | Prints the value and offset of a field to `stderr`.
| r   | [`default`]#ignore | field | An alias for `ignore`.
| r   | [`err_context`]#backtrace | field | Adds additional context to errors.
| rw  | [`if`]#conditional-values | field | <span class="brw">Reads or writes</span><span class="br">Reads</span><span class="bw">Writes</span> data only if a condition is true.
| rw  | [`ignore`]#ignore | field | <span class="brw">For `BinRead`, uses the [`default`]core::default::Default value for a field instead of reading data. For `BinWrite`, skips writing the field.</span><span class="br">Uses the [`default`]core::default::Default value for a field instead of reading data.</span><span class="bw">Skips writing the field.</span>
| rw  | [`import`]#arguments | struct, non-unit enum, unit-like enum | Defines extra arguments for a struct or enum.
| rw  | [`import_raw`]#arguments | struct, non-unit enum, unit-like enum | Like `import`, but receives the arguments as a single variable.
| rw  | [`is_big`]#byte-order | field | Conditionally sets the byte order to big-endian.
| rw  | [`is_little`]#byte-order | field | Conditionally set the byte order to little-endian.
| rw  | [`little`]#byte-order | all except unit variant | Sets the byte order to little-endian.
| rw  | [`magic`]#magic | all | <span class="br">Matches</span><span class="bw">Writes</span> a magic number.
| rw  | [`map`]#map | all except unit variant | Maps an object or value to a new value.
| rw  | [`map_stream`]#stream-access-and-manipulation | all except unit variant | Maps the <span class="br">read</span><span class="bw">write</span> stream to a new stream.
| r   | [`offset`]#offset | field | Modifies the offset used by a [`FilePtr`]crate::FilePtr while parsing.
| rw  | [`pad_after`]#padding-and-alignment | field | Skips N bytes after <span class="br">reading</span><span class="bw">writing</span> a field.
| rw  | [`pad_before`]#padding-and-alignment | field | Skips N bytes before <span class="br">reading</span><span class="bw">writing</span> a field.
| rw  | [`pad_size_to`]#padding-and-alignment | field | Ensures the <span class="br">reader</span><span class="bw">writer</span> is always advanced at least N bytes.
| r   | [`parse_with`]#custom-parserswriters | field | Specifies a custom function for reading a field.
| r   | [`pre_assert`]#pre-assert | struct, non-unit enum, unit variant | Like `assert`, but checks the condition before parsing.
| rw  | [`repr`]#repr | unit-like enum | Specifies the underlying type for a unit-like (C-style) enum.
| rw  | [`restore_position`]#restore-position | field | Restores the <span class="br">reader’s</span><span class="bw">writer’s</span> position after <span class="br">reading</span><span class="bw">writing</span> a field.
| r   | [`return_all_errors`]#enum-errors | non-unit enum | Returns a [`Vec`] containing the error which occurred on each variant of an enum on failure. This is the default.
| r   | [`return_unexpected_error`]#enum-errors | non-unit enum | Returns a single generic error on failure.
| rw  | [`seek_before`]#padding-and-alignment | field | Moves the <span class="br">reader</span><span class="bw">writer</span> to a specific position before <span class="br">reading</span><span class="bw">writing</span> data.
| rw  | [`stream`]#stream-access-and-manipulation | struct, non-unit enum, unit-like enum | Exposes the underlying <span class="br">read</span><span class="bw">write</span> stream.
| r   | [`temp`]#temp | field | Uses a field as a temporary variable. Only usable with the [`binread`]macro@crate::binread attribute macro.
| r   | [`try`]#try | field | Tries to parse and stores the [`default`]core::default::Default value for the type if parsing fails instead of returning an error.
| rw  | [`try_calc`]#calculations | field | Like `calc`, but returns a [`Result`].
| rw  | [`try_map`]#map | all except unit variant | Like `map`, but returns a [`Result`].
|  w  | [`write_with`]#custom-parserswriters | field | Specifies a custom function for writing a field.

[*]: #terminology

# Terminology

Each binrw attribute contains a comma-separated list of directives. The
following terms are used when describing where particular directives are
supported:

```text
#[brw(…)]               // ← struct
struct NamedStruct {
    #[brw(…)]           // ← field
    field: Type
}

#[brw(…)]               // ← struct
struct TupleStruct(
    #[brw(…)]           // ← field
    Type,
);

#[brw(…)]               // ← struct
struct UnitStruct;

#[brw(…)]               // ← non-unit enum
enum NonUnitEnum {
    #[brw(…)]           // ← data variant
    StructDataVariant {
        #[brw(…)]       // ← field
        field: Type
    },

    #[brw(…)]           // ← data variant
    TupleDataVariant(
        #[brw(…)]       // ← field
        Type
    ),

    #[brw(…)]           // ← unit variant
    UnitVariant
}

#[brw(…)]               // ← unit-like enum
enum UnitLikeEnum {
    #[brw(…)]           // ← unit variant
    UnitVariantA,
    #[brw(…)]           // ← unit variant
    UnitVariantN
}
```

# Arguments

Arguments provide extra data necessary for
<span class="br">reading</span><span class="bw">writing</span> an
object.

The `import` and `args` directives define the type of
<span class="br">[`BinRead::Args`](crate::BinRead::Args)</span>
<span class="bw">[`BinWrite::Args`](crate::BinWrite::Args)</span>
and the values passed in the `args`
argument of a
<span class="br">[`BinRead::read_options`](crate::BinRead::read_options)</span>
<span class="bw">[`BinWrite::write_options`](crate::BinWrite::write_options)</span>
call, respectively.

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be referenced in `args`.

## Ways to pass and receive arguments

There are 3 ways arguments can be passed and received:

* Tuple-style arguments (or “ordered arguments”): arguments passed as a tuple
* Named arguments: arguments passed as an object
* Raw arguments: arguments passed as a type of your choice

### Tuple-style arguments

Tuple-style arguments (or “ordered arguments”) are passed via `args()` and
received via `import()`:

<div class="br">

```text
#[br(import($($ident:ident : $ty:ty),* $(,)?))]
#[br(args($($value:expr),* $(,)?))]
```
</div>
<div class="bw">

```text
#[bw(import($($ident:ident : $ty:ty),* $(,)?))]
#[bw(args($($value:expr),* $(,)?))]
```
</div>

This is the most common form of argument passing because it works mostly
like a normal function call:

<div class="br">

```
# use binrw::prelude::*;
#[derive(BinRead)]
#[br(import(val1: u32, val2: &str))]
struct Child {
    // ...
}

#[derive(BinRead)]
struct Parent {
    val: u32,
    #[br(args(val + 3, "test"))]
    test: Child
}
```
</div>
<div class="bw">

```
# use binrw::prelude::*;
#[derive(BinWrite)]
#[bw(import(val1: u32, val2: &str))]
struct Child {
    // ...
}

#[derive(BinWrite)]
struct Parent {
    val: u32,
    #[bw(args(val + 3, "test"))]
    test: Child
}
```
</div>

### Named arguments

Named arguments are passed via `args {}` and received via `import {}`
(note the curly braces), similar to a struct literal:

<div class="br">

```text
#[br(import { $($ident:ident : $ty:ty $(= $default:expr)?),* $(,)? })]
#[br(args { $($name:ident $(: $value:expr)?),* $(,)? } )]
```
</div>
<div class="bw">

```text
#[bw(import { $($ident:ident : $ty:ty $(= $default:expr)?),* $(,)? })]
#[bw(args { $($name:ident $(: $value:expr)?),* $(,)? } )]
```
</div>

[Field init shorthand](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#using-the-field-init-shorthand)
and optional arguments are both supported.

Named arguments are particularly useful for container objects like [`Vec`],
but they can be used by any <span class="br">parser</span><span class="bw">serialiser</span>
that would benefit from labelled, optional, or unordered arguments:

<div class="br">

```
# use binrw::prelude::*;
#[derive(BinRead)]
#[br(import {
    count: u32,
    other: u16 = 0 // ← optional argument
})]
struct Child {
    // ...
}

#[derive(BinRead)]
struct Parent {
    count: u32,

    #[br(args {
        count, // ← field init shorthand
        other: 5
    })]
    test: Child,

    #[br(args { count: 3 })]
    test2: Child,
}
```
</div>
<div class="bw">

```
# use binrw::prelude::*;
#[derive(BinWrite)]
#[bw(import {
    count: u32,
    other: u16 = 0 // ← optional argument
})]
struct Child {
    // ...
}

#[derive(BinWrite)]
struct Parent {
    count: u32,

    #[bw(args {
        count: *count,
        other: 5
    })]
    test: Child,

    #[bw(args { count: 3 })]
    test2: Child,
}
```
</div>

When nesting named arguments, you can use the [`binrw::args!`] macro to
construct the nested object:

<div class="br">

```
# use binrw::prelude::*;
#[derive(BinRead)]
#[br(import {
    more_extra_stuff: u32
})]
struct Inner {
    // ...
}

#[derive(BinRead)]
#[br(import {
    extra_stuff: u32,
    inner_stuff: <Inner as BinRead>::Args<'_>
})]
struct Middle {
    #[br(args_raw = inner_stuff)]
    inner: Inner
}

#[derive(BinRead)]
struct Outer {
    extra_stuff: u32,
    inner_extra_stuff: u32,

    #[br(args { // ← Middle::Args<'_>
        extra_stuff,
        inner_stuff: binrw::args! { // ← Inner::Args<'_>
            more_extra_stuff: inner_extra_stuff
        }
    })]
    middle: Middle,
}
```
</div>
<div class="bw">

```
# use binrw::prelude::*;
#[derive(BinWrite)]
#[bw(import {
    more_extra_stuff: u32
})]
struct Inner {
    // ...
}

#[derive(BinWrite)]
#[bw(import {
    extra_stuff: u32,
    inner_stuff: <Inner as BinWrite>::Args<'_>
})]
struct Middle {
    #[bw(args_raw = inner_stuff)]
    inner: Inner
}

#[derive(BinWrite)]
struct Outer {
    extra_stuff: u32,
    inner_extra_stuff: u32,

    #[bw(args { // ← Middle::Args<'_>
        extra_stuff: *extra_stuff,
        inner_stuff: binrw::args! { // ← Inner::Args<'_>
            more_extra_stuff: *inner_extra_stuff
        }
    })]
    middle: Middle,
}
```
</div>

Named arguments can also be used with types that manually implement
<span class="br">`BinRead`</span><span class="bw">`BinWrite`</span> by creating
a separate type for its arguments that implements [`binrw::NamedArgs`].

The [`count`](#count) and [`offset`](#offset) directives are sugar for setting
the `count` and `offset` arguments on any named arguments object; see those
directives’ documentation for more information.

### Raw arguments

Raw arguments allow the
<span class="br">[`BinRead::Args`](crate::BinRead::Args)</span>
<span class="bw">[`BinWrite::Args`](crate::BinWrite::Args)</span>
type to be specified explicitly and to receive all arguments into a single
variable:

<div class="br">

```text
#[br(import_raw($binding:ident : $ty:ty))]
#[br(args_raw($value:expr))] or #[br(args_raw = $value:expr)]
```
</div>
<div class="bw">

```text
#[bw(import_raw($binding:ident : $ty:ty))]
#[bw(args_raw($value:expr))] or #[bw(args_raw = $value:expr)]
```
</div>

They are most useful for argument forwarding:

<div class="br">

```
# use binrw::prelude::*;
type Args = (u32, u16);

#[derive(BinRead)]
#[br(import_raw(args: Args))]
struct Child {
    // ...
}

#[derive(BinRead)]
#[br(import_raw(args: Args))]
struct Middle {
    #[br(args_raw = args)]
    test: Child,
}

#[derive(BinRead)]
struct Parent {
    count: u32,

    #[br(args(1, 2))]
    mid: Middle,

    // identical to `mid`
    #[br(args_raw = (1, 2))]
    mid2: Middle,
}
```
</div>
<div class="bw">

```
# use binrw::prelude::*;
type Args = (u32, u16);

#[derive(BinWrite)]
#[bw(import_raw(args: Args))]
struct Child {
    // ...
}

#[derive(BinWrite)]
#[bw(import_raw(args: Args))]
struct Middle {
    #[bw(args_raw = args)]
    test: Child,
}

#[derive(BinWrite)]
struct Parent {
    count: u32,

    #[bw(args(1, 2))]
    mid: Middle,

    // identical to `mid`
    #[bw(args_raw = (1, 2))]
    mid2: Middle,
}
```
</div>

# Assert

The `assert` directive validates objects and fields
<span class="brw">after they are read or before they are written,</span>
<span class="br">after they are read,</span>
<span class="bw">before they are written,</span>
returning an error if the assertion condition evaluates to `false`:

<div class="br">

```text
#[br(assert($cond:expr $(,)?))]
#[br(assert($cond:expr, $msg:literal $(,)?)]
#[br(assert($cond:expr, $fmt:literal, $($arg:expr),* $(,)?))]
#[br(assert($cond:expr, $err:expr $(,)?)]
```
</div>
<div class="bw">

```text
#[bw(assert($cond:expr $(,)?))]
#[bw(assert($cond:expr, $msg:literal $(,)?)]
#[bw(assert($cond:expr, $fmt:literal, $($arg:expr),* $(,)?))]
#[bw(assert($cond:expr, $err:expr $(,)?)]
```
</div>

Multiple assertion directives can be used; they will be combined and
executed in order.

Assertions added to the top of an enum will be checked against every variant
in the enum.

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be referenced by expressions
in the directive. <span class="brw">When reading, an</span><span class="br">An</span>
`assert` directive on a struct, non-unit enum, or data variant can access the
constructed object using the `self` keyword.

## Examples

### Formatted error

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug)]
#[br(assert(some_val > some_smaller_val, "oops! {} <= {}", some_val, some_smaller_val))]
struct Test {
    some_val: u32,
    some_smaller_val: u32
}

let error = Cursor::new(b"\0\0\0\x01\0\0\0\xFF").read_be::<Test>();
assert!(error.is_err());
let error = error.unwrap_err();
let expected = "oops! 1 <= 255".to_string();
assert!(matches!(error, binrw::Error::AssertFail { message: expected, .. }));
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
# #[derive(Debug)]
#[bw(assert(some_val > some_smaller_val, "oops! {} <= {}", some_val, some_smaller_val))]
struct Test {
    some_val: u32,
    some_smaller_val: u32
}

let object = Test { some_val: 1, some_smaller_val: 255 };
let error = object.write_le(&mut Cursor::new(vec![]));
assert!(error.is_err());
let error = error.unwrap_err();
let expected = "oops! 1 <= 255".to_string();
assert!(matches!(error, binrw::Error::AssertFail { message: expected, .. }));
```
</div>

### Custom error

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(Debug, PartialEq)]
struct NotSmallerError(u32, u32);
impl core::fmt::Display for NotSmallerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{} <= {}", self.0, self.1)
    }
}

#[derive(BinRead, Debug)]
#[br(assert(some_val > some_smaller_val, NotSmallerError(some_val, some_smaller_val)))]
struct Test {
    some_val: u32,
    some_smaller_val: u32
}

let error = Cursor::new(b"\0\0\0\x01\0\0\0\xFF").read_be::<Test>();
assert!(error.is_err());
let error = error.unwrap_err();
assert_eq!(error.custom_err(), Some(&NotSmallerError(0x1, 0xFF)));
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(Debug, PartialEq)]
struct NotSmallerError(u32, u32);
impl core::fmt::Display for NotSmallerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{} <= {}", self.0, self.1)
    }
}

#[derive(BinWrite, Debug)]
#[bw(assert(some_val > some_smaller_val, NotSmallerError(*some_val, *some_smaller_val)))]
struct Test {
    some_val: u32,
    some_smaller_val: u32
}

let object = Test { some_val: 1, some_smaller_val: 255 };
let error = object.write_le(&mut Cursor::new(vec![]));
assert!(error.is_err());
let error = error.unwrap_err();
assert_eq!(error.custom_err(), Some(&NotSmallerError(0x1, 0xFF)));
```
</div>

<div class="br">

### In combination with `map` or `try_map`

```
# use binrw::{prelude::*, io::Cursor};
use modular_bitfield::prelude::*;

#[bitfield]
#[derive(BinRead)]
#[br(assert(self.is_fast()), map = Self::from_bytes)]
pub struct PackedData {
    status: B4,
    is_fast: bool,
    is_static: bool,
    is_alive: bool,
    is_good: bool,
}

let data = Cursor::new(b"\x53").read_le::<PackedData>().unwrap();
```
</div>

## Errors

If the assertion fails and there is no second argument, or a string literal
is given as the second argument, an [`AssertFail`](crate::Error::AssertFail)
error is returned.

If the assertion fails and an expression is given as the second argument,
a [`Custom`](crate::Error::Custom) error containing the result of the
expression is returned.

Arguments other than the condition are not evaluated unless the assertion
fails, so it is safe for them to contain expensive operations without
impacting performance.

In all cases, the <span class="br">reader</span><span class="bw">writer</span>’s
position is reset to where it was before
<span class="br">parsing</span><span class="bw">serialisation</span>
started.

<div class="br">

# Backtrace

When an error is raised during parsing, `BinRead` forms a backtrace, bubbling the
error upwards and attaching additional information (surrounding code, line numbers,
messages, etc.) in order to aid in debugging.

The `#[br(err_context(...))]` attribute can work in one of two ways:

1. If the first (or only) item is a string literal, it will be a message format string,
   with any other arguments being used as arguments. This uses the same formatting as `format!`,
   `println!`, and other standard library formatters.

2. Otherwise, only a single argument is allowed, which will then be attached as a context
   type. This type must implement [`Display`]std::fmt::Display, [`Debug`], [`Send`], and [`Sync`].

## Example

```
# use binrw::{io::Cursor, BinRead, BinReaderExt};
#[derive(BinRead)]
struct InnerMostStruct {
    #[br(little)]
    len: u32,

    #[br(count = len, err_context("len = {}", len))]
    items: Vec<u32>,
}

#[derive(BinRead)]
struct MiddleStruct {
    #[br(little)]
    #[br(err_context("While parsing the innerest most struct"))]
    inner: InnerMostStruct,
}

#[derive(Debug, Clone)] // Display implementation omitted
struct Oops(u32);

#[derive(BinRead)]
struct OutermostStruct {
    #[br(little, err_context(Oops(3 + 1)))]
    middle: MiddleStruct,
}
# let mut x = Cursor::new(b"\0\0\0\x06");
# let err = x.read_be::<OutermostStruct>().map(|_| ()).unwrap_err();
# impl core::fmt::Display for Oops {
#     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#         write!(f, "Oops({})", self.0)
#     }
# }
```
</div>

# Byte order

The `big` and `little` directives specify the [byte order](https://en.wikipedia.org/wiki/Endianness)
of data in a struct, enum, variant, or field:

<div class="br">

```text
#[br(big)]
#[br(little)]
```
</div>
<div class="bw">

```text
#[bw(big)]
#[bw(little)]
```
</div>

The `is_big` and `is_little` directives conditionally set the byte order of
a struct field:

<div class="br">

```text
#[br(is_little = $cond:expr)] or #[br(is_little($cond:expr))]
#[br(is_big = $cond:expr)] or #[br(is_big($cond:expr))]
```
</div>
<div class="bw">

```text
#[bw(is_little = $cond:expr)] or #[bw(is_little($cond:expr))]
#[bw(is_big = $cond:expr)] or #[bw(is_big($cond:expr))]
```
</div>

The `is_big` and `is_little` directives are primarily useful when byte order
is defined in the data itself. Any
<span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can
be referenced in the condition. Conditional byte order directives can only
be used on struct fields.

The order of precedence (from highest to lowest) for determining byte order
within an object is:

1. A directive on a field
2. A directive on an enum variant
3. A directive on the struct or enum
4. The `endian` parameter of the <span class="br">
   [`BinRead::read_options`]crate::BinRead::read_options</span><span class="bw">
   [`BinWrite::write_options`]crate::BinWrite::write_options</span> call

However, if a byte order directive is added to a struct or enum, that byte
order will *always* be used, even if the object is embedded in another
object or explicitly called with a different byte order:

<div class="br">

```
# use binrw::{Endian, prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(little)] // ← this *forces* the struct to be little-endian
struct Child(u32);

#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
struct Parent {
    #[br(big)] // ← this will be ignored
    child: Child,
};

let endian = Endian::Big; /* ← this will be ignored */
# assert_eq!(
Parent::read_options(&mut Cursor::new(b"\x01\0\0\0"), endian, ())
# .unwrap(), Parent { child: Child(1) });
```
</div>
<div class="bw">

```
# use binrw::{Endian, prelude::*, io::Cursor};
#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
#[bw(little)] // ← this *forces* the struct to be little-endian
struct Child(u32);

#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
struct Parent {
    #[bw(big)] // ← this will be ignored
    child: Child,
};

let object = Parent { child: Child(1) };

let endian = Endian::Big; /* ← this will be ignored */
let mut output = Cursor::new(vec![]);
object.write_options(&mut output, endian, ())
# .unwrap();
# assert_eq!(output.into_inner(), b"\x01\0\0\0");
```
</div>

When manually implementing
<span class="br">[`BinRead::read_options`](crate::BinRead::read_options)</span><span class="bw">[`BinWrite::write_options`](crate::BinWrite::write_options)</span> or a
[custom <span class="br">parser</span><span class="bw">writer</span> function](#custom-parserswriters),
the byte order is accessible from the `endian` parameter.

## Examples

### Mixed endianness in one object

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(little)]
struct MyType (
    #[br(big)] u32, // ← will be big-endian
    u32, // ← will be little-endian
);

# assert_eq!(MyType::read(&mut Cursor::new(b"\0\0\0\x01\x01\0\0\0")).unwrap(), MyType(1, 1));
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
#[bw(little)]
struct MyType (
    #[bw(big)] u32, // ← will be big-endian
    u32, // ← will be little-endian
);

# let object = MyType(1, 1);
# let mut output = Cursor::new(vec![]);
# object.write(&mut output).unwrap();
# assert_eq!(output.into_inner(), b"\0\0\0\x01\x01\0\0\0");
```
</div>

### Conditional field endianness

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
# #[derive(Debug, PartialEq)]
#[derive(BinRead)]
#[br(big)]
struct MyType {
    val: u8,
    #[br(is_little = (val == 3))]
    other_val: u16 // ← little-endian if `val == 3`, otherwise big-endian
}

# assert_eq!(
MyType::read(&mut Cursor::new(b"\x03\x01\x00"))
# .unwrap(), MyType { val: 3, other_val: 1 });
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
# #[derive(Debug, PartialEq)]
#[derive(BinWrite)]
#[bw(big)]
struct MyType {
    val: u8,
    #[bw(is_little = (*val == 3))]
    other_val: u16 // ← little-endian if `val == 3`, otherwise big-endian
}

let object = MyType { val: 3, other_val: 1 };
let mut output = Cursor::new(vec![]);
object.write(&mut output)
# .unwrap();
# assert_eq!(output.into_inner(), b"\x03\x01\x00");
```
</div>

# Calculations

<div class="bw">

<div class="warning">

These directives can only be used with [`binwrite`](macro@crate::binwrite).
They will not work with `#[derive(BinWrite)]`.

When using these directives, the `#[binwrite]` attribute must be placed
*before* other attributes like `#[derive(Debug)]`. Otherwise, the other
attributes will generate code that references non-existent fields, and
compilation will fail.
</div>
</div>

The `calc` and `try_calc` directives compute the value of a field instead of
<span class="br">reading data from the reader</span><span class="bw">writing from
a struct field</span>:

<div class="br">

```text
#[br(calc = $value:expr)] or #[br(calc($value:expr))]
#[br(try_calc = $value:expr)] or #[br(try_calc($value:expr))]
```
</div>
<div class="bw">

```text
#[bw(calc = $value:expr)] or #[bw(calc($value:expr))]
#[bw(try_calc = $value:expr)] or #[bw(try_calc($value:expr))]
```
</div>

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be referenced by the expression in the
directive.

When using `try_calc`, the produced value must be a [`Result<T, E>`](Result).

<div class="bw">

Since the field is treated as a temporary variable instead of an actual
field, when deriving `BinRead`, the field should also be annotated with
`#[br(temp)]`.
</div>

## Examples

### Infallible calculation

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    var: u32,
    #[br(calc = 3 + var)]
    var_plus_3: u32,
}

# assert_eq!(Cursor::new(b"\0\0\0\x01").read_be::<MyType>().unwrap().var_plus_3, 4);
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[binwrite] // ← must be before other attributes that use struct fields
#[bw(big)]
struct MyType {
    var: u32,
    #[bw(calc = var - 3)]
    var_minus_3: u32,
}

let object = MyType { var: 4 };

let mut output = Cursor::new(vec![]);
object.write(&mut output).unwrap();
assert_eq!(output.into_inner(), b"\0\0\0\x04\0\0\0\x01");
```
</div>

### Fallible calculation

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    var: u32,
    #[br(try_calc = u16::try_from(var + 3))]
    var_plus_3: u16,
}

# assert_eq!(Cursor::new(b"\0\0\0\x01").read_be::<MyType>().unwrap().var_plus_3, 4);
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[binwrite] // ← must be before other attributes that use struct fields
#[bw(big)]
struct MyType {
    var: u32,
    #[bw(try_calc = u16::try_from(var - 3))]
    var_minus_3: u16,
}

let object = MyType { var: 4 };

let mut output = Cursor::new(vec![]);
object.write(&mut output).unwrap();
assert_eq!(output.into_inner(), b"\0\0\0\x04\0\x01");
```
</div>

# Conditional values

The `if` directive allows conditional
<span class="br">parsing</span><span class="bw">serialisation</span> of a field,
<span class="br">reading</span><span class="bw">writing</span> data if the
condition is true and optionally using a computed value if the condition is
false:

<div class="br">

```text
#[br(if($cond:expr))]
#[br(if($cond:expr, $alternate:expr))]
```
</div>
<div class="bw">

```text
#[bw(if($cond:expr))]
#[bw(if($cond:expr, $alternate:expr))]
```
</div>

If an alternate is provided, that value will be used when the condition is
false; otherwise,
<span class="brw">for reads, the [`default`](core::default::Default) value for
the type will be used, and for writes, no data will be written.</span>
<span class="br">the [`default`](core::default::Default) value for the type
will be used.</span>
<span class="bw">no data will be written.</span>

The alternate expression is not evaluated unless the condition is false, so
it is safe for it to contain expensive operations without impacting
performance.

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be referenced by the
expression in the directive.

<span class="bw">The [`map`](#map) directive can also be used to conditionally
write a field by returning an [`Option`], where a [`None`] value skips
writing.</span>

## Examples

<div class="br">

### Reading an [`Option`] field with no alternate

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    var: u32,

    #[br(if(var == 1))]
    original_byte: Option<u8>,

    #[br(if(var != 1))]
    other_byte: Option<u8>,
}

# assert_eq!(Cursor::new(b"\0\0\0\x01\x03").read_be::<MyType>().unwrap().original_byte, Some(3));
# assert_eq!(Cursor::new(b"\0\0\0\x01\x03").read_be::<MyType>().unwrap().other_byte, None);
```

### Reading a scalar field with an explicit alternate

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    var: u32,

    #[br(if(var == 1, 0))]
    original_byte: u8,

    #[br(if(var != 1, 42))]
    other_byte: u8,
}

# assert_eq!(Cursor::new(b"\0\0\0\x01\x03").read_be::<MyType>().unwrap().original_byte, 3);
# assert_eq!(Cursor::new(b"\0\0\0\x01\x03").read_be::<MyType>().unwrap().other_byte, 42);
```
</div>
<div class="bw">


### Skipping a scalar field with no alternate

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
struct Test {
    x: u8,
    #[bw(if(*x > 1))]
    y: u8,
}

let mut output = Cursor::new(vec![]);
output.write_be(&Test { x: 1, y: 3 }).unwrap();
assert_eq!(output.into_inner(), b"\x01");

let mut output = Cursor::new(vec![]);
output.write_be(&Test { x: 2, y: 3 }).unwrap();
assert_eq!(output.into_inner(), b"\x02\x03");
```

### Writing a scalar field with an explicit alternate

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
struct Test {
    x: u8,
    #[bw(if(*x > 1, 0))]
    y: u8,
}

let mut output = Cursor::new(vec![]);
output.write_be(&Test { x: 1, y: 3 }).unwrap();
assert_eq!(output.into_inner(), b"\x01\0");

let mut output = Cursor::new(vec![]);
output.write_be(&Test { x: 2, y: 3 }).unwrap();
assert_eq!(output.into_inner(), b"\x02\x03");
```
</div>

<div class="br">

# Count

The `count` directive is a shorthand for passing a `count` argument to a
type that accepts it as a named argument:

```text
#[br(count = $count:expr) or #[br(count($count:expr))]
```

It desugars to:

```text
#[br(args { count: $count as usize })]
```

This directive is most commonly used with [`Vec`], which accepts `count`
and `inner` arguments through its
[associated `VecArgs` type](crate::VecArgs).

When manually implementing
[`BinRead::read_options`](crate::BinRead::read_options) or a
[custom parser function](#custom-parserswriters), the `count` value is accessible
from a named argument named `count`.

Any earlier field or [import](#arguments) can be referenced by the
expression in the directive.

## Examples

### Using `count` with [`Vec`]

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct Collection {
    size: u32,
    #[br(count = size)]
    data: Vec<u8>,
}

# assert_eq!(
#    Cursor::new(b"\0\0\0\x04\x01\x02\x03\x04").read_be::<Collection>().unwrap().data,
#    &[1u8, 2, 3, 4]
# );
```

### Using `count` with a [`Vec`] with arguments for the inner type

```
# use binrw::{prelude::*, io::Cursor};

#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(import(version: i16))]
struct Inner(#[br(if(version > 0))] u8);

#[derive(BinRead)]
struct Collection {
    version: i16,
    size: u32,
    #[br(count = size, args { inner: (version,) })]
    data: Vec<Inner>,
}

# assert_eq!(
#    Cursor::new(b"\0\x01\0\0\0\x04\x01\x02\x03\x04").read_be::<Collection>().unwrap().data,
#    &[Inner(1), Inner(2), Inner(3), Inner(4)]
# );
```
</div>

# Custom <span class="br">parsers</span><span class="bw">writers</span>

<div class="br">

The `parse_with` directive specifies a custom parsing function which can be
used to override the default [`BinRead`](crate::BinRead) implementation for
a type, or to parse types which have no `BinRead` implementation at all:

```text
#[br(parse_with = $parse_fn:expr)] or #[br(parse_with($parse_fn:expr))]
```

Use the [`#[parser]`](crate::parser) attribute macro to create compatible
functions.

Any earlier field or [import](#arguments) can be referenced by the
expression in the directive (for example, to construct a parser function at
runtime by calling a function generator).
</div>
<div class="bw">

The `write_with` directive specifies a custom serialisation function which
can be used to override the default [`BinWrite`](crate::BinWrite)
implementation for a type, or to serialise types which have no `BinWrite`
implementation at all:

```text
#[bw(write_with = $write_fn:expr)] or #[bw(write_with($write_fn:expr))]
```

Use the [`#[writer]`](crate::writer) attribute macro to create compatible
functions.

Any field or [import](#arguments) can be referenced by the expression in the
directive (for example, to construct a serialisation function at runtime by
calling a function generator).
</div>

## Examples

<div class="br">

### Using a custom parser to generate a [`HashMap`]std::collections::HashMap

```
# use binrw::{prelude::*, io::{prelude::*, Cursor}, Endian};
# use std::collections::HashMap;
#[binrw::parser(reader, endian)]
fn custom_parser() -> BinResult<HashMap<u16, u16>> {
    let mut map = HashMap::new();
    map.insert(
        <_>::read_options(reader, endian, ())?,
        <_>::read_options(reader, endian, ())?,
    );
    Ok(map)
}

#[derive(BinRead)]
#[br(big)]
struct MyType {
    #[br(parse_with = custom_parser)]
    offsets: HashMap<u16, u16>
}

# assert_eq!(Cursor::new(b"\0\0\0\x01").read_be::<MyType>().unwrap().offsets.get(&0), Some(&1));
```
</div>
<div class="bw">

### Using a custom serialiser to write a [`BTreeMap`]std::collections::BTreeMap

```
# use binrw::{prelude::*, io::{prelude::*, Cursor}, Endian};
# use std::collections::BTreeMap;
#[binrw::writer(writer, endian)]
fn custom_writer(
    map: &BTreeMap<u16, u16>,
) -> BinResult<()> {
    for (key, val) in map.iter() {
        key.write_options(writer, endian, ())?;
        val.write_options(writer, endian, ())?;
    }
    Ok(())
}

#[derive(BinWrite)]
#[bw(big)]
struct MyType {
    #[bw(write_with = custom_writer)]
    offsets: BTreeMap<u16, u16>
}

let object = MyType {
    offsets: BTreeMap::from([(0, 1), (2, 3)]),
};

let mut output = Cursor::new(vec![]);
object.write(&mut output).unwrap();
assert_eq!(output.into_inner(), b"\0\0\0\x01\0\x02\0\x03");
```
</div>

<div class="br">

### Using `FilePtr::parse` to read a `NullString` without storing a `FilePtr`

```
# use binrw::{prelude::*, io::Cursor, FilePtr32, NullString};
#[derive(BinRead)]
struct MyType {
    #[br(parse_with = FilePtr32::parse)]
    some_string: NullString,
}

# let val: MyType = Cursor::new(b"\0\0\0\x04Test\0").read_be().unwrap();
# assert_eq!(val.some_string.to_string(), "Test");
```
</div>

<div class="br">

# Debug

The `dbg` directive prints the offset and value of a field to
[`stderr`](std::io::stderr) for quick and dirty debugging:

```text
#[br(dbg)]
```

The type of the field being inspected must implement [`Debug`](std::fmt::Debug).

Non-nightly Rust versions without support for
[`proc_macro_span`](https://github.com/rust-lang/rust/issues/54725) will emit
line numbers pointing to the binrw attribute on the parent struct or enum rather
than the field.

## Examples

```
# #[cfg(not(feature = "std"))] fn main() {}
# #[cfg(feature = "std")]
# fn main() {
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead, Debug)]
# #[derive(PartialEq)]
#[br(little)]
struct Inner {
    #[br(dbg)]
    a: u32,
    #[br(dbg)]
    b: u32,
}

#[derive(BinRead, Debug)]
# #[derive(PartialEq)]
#[br(little)]
struct Test {
    first: u16,
    #[br(dbg)]
    inner: Inner,
}

// prints:
//
// [file.rs:5 | offset 0x2] a = 0x10
// [file.rs:7 | offset 0x6] b = 0x40302010
// [file.rs:15 | offset 0x2] inner = Inner {
//     a: 0x10,
//     b: 0x40302010,
// }
# assert_eq!(
Test::read(&mut Cursor::new(b"\x01\0\x10\0\0\0\x10\x20\x30\x40")).unwrap(),
# Test { first: 1, inner: Inner { a: 0x10, b: 0x40302010 } }
# );
# }
```

# Enum errors

The `return_all_errors` (default) and `return_unexpected_error` directives
define how to handle errors when parsing an enum:

```text
#[br(return_all_errors)]
#[br(return_unexpected_error)]
```

`return_all_errors` collects the errors that occur when enum variants fail
to parse and returns them in [`binrw::Error::EnumErrors`] when no variants
parse successfully:

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug)]
#[br(return_all_errors)]
enum Test {
    #[br(magic(0u8))]
    A { a: u8 },
    B { b: u32 },
    C { #[br(assert(c != 1))] c: u8 },
}

let error = Test::read_le(&mut Cursor::new(b"\x01")).unwrap_err();
if let binrw::Error::EnumErrors { pos, variant_errors } = error {
    assert_eq!(pos, 0);
    assert!(matches!(variant_errors[0], ("A", binrw::Error::BadMagic { .. })));
    assert!(matches!(
        (variant_errors[1].0, variant_errors[1].1.root_cause()),
        ("B", binrw::Error::Io(..))
    ));
    assert!(matches!(variant_errors[2], ("C", binrw::Error::AssertFail { .. })));
}
# else {
#    panic!("wrong error type");
# }
```

`return_unexpected_error` discards the errors and instead returns a generic
[`binrw::Error::NoVariantMatch`] if all variants fail to parse. This avoids
extra memory allocations required to collect errors, but only provides the
position when parsing fails:

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug)]
#[br(return_unexpected_error)]
enum Test {
    #[br(magic(0u8))]
    A { a: u8 },
    B { b: u32 },
    C { #[br(assert(c != 1))] c: u8 },
}

let error = Test::read_le(&mut Cursor::new(b"\x01")).unwrap_err();
if let binrw::Error::NoVariantMatch { pos } = error {
    assert_eq!(pos, 0);
}
# else {
#    panic!("wrong error type");
# }
```

</div>

# Ignore

<div class="br">

For [`BinRead`](crate::BinRead), the `ignore` directive, and its alias
`default`, sets the value of the field to its
[`Default`] instead of reading data from the reader:

```text
#[br(default)] or #[br(ignore)]
```
</div>
<div class="bw">

For [`BinWrite`](crate::BinWrite), the `ignore` directive skips writing the
field to the writer:

```text
#[bw(ignore)]
```
</div>

## Examples

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
struct Test {
    #[br(ignore)]
    path: Option<std::path::PathBuf>,
}

assert_eq!(
    Test::read_le(&mut Cursor::new(b"")).unwrap(),
    Test { path: None }
);
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
struct Test {
    a: u8,
    #[bw(ignore)]
    b: u8,
    c: u8,
}

let object = Test { a: 1, b: 2, c: 3 };
let mut output = Cursor::new(vec![]);
object.write_le(&mut output).unwrap();
assert_eq!(
    output.into_inner(),
    b"\x01\x03"
);
```
</div>

# Magic

The `magic` directive matches [magic numbers](https://en.wikipedia.org/wiki/Magic_number_(programming))
in data:

<div class="br">

```text
#[br(magic = $magic:literal)] or #[br(magic($magic:literal))]
```
</div>
<div class="bw">

```text
#[bw(magic = $magic:literal)] or #[bw(magic($magic:literal))]
```
</div>

The magic number can be a byte literal, byte string, float, or integer. When
a magic number is matched, parsing begins with the first byte after the
magic number in the data.

To match enum variants based on more complex conditions, or from a magic value
supplied as an [argument](#arguments), use [`pre_assert`](#pre-assert).

<div class="br">

## Fallback handling

To handle an unmatched magic value instead of failing to parse, omit the `magic`
directive from a later variant:

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
enum Command {
    #[br(magic = 0u8)] Start,
    #[br(magic = 1u8)] End,
    Unknown(u8)
}

assert_eq!(Command::read_le(
    &mut Cursor::new(b"\x02")).unwrap(),
    Command::Unknown(2)
);
```
</div>

## Examples

### Using byte strings

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(magic = b"TEST")]
struct Test {
    val: u32
}

# assert_eq!(
Test::read_le(&mut Cursor::new(b"TEST\0\0\0\0"))
# .unwrap(), Test { val: 0 });
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
#[bw(magic = b"TEST")]
struct Test {
    val: u32
}

let object = Test { val: 0 };
let mut output = Cursor::new(vec![]);
object.write_le(&mut output)
# .unwrap();
# assert_eq!(output.into_inner(), b"TEST\0\0\0\0");
```
</div>

### Using float literals

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(big, magic = 1.2f32)]
struct Version(u16);

# assert_eq!(
Version::read(&mut Cursor::new(b"\x3f\x99\x99\x9a\0\0"))
# .unwrap(), Version(0));
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
#[bw(big, magic = 1.2f32)]
struct Version(u16);

let object = Version(0);
let mut output = Cursor::new(vec![]);
object.write(&mut output)
# .unwrap();
# assert_eq!(output.into_inner(), b"\x3f\x99\x99\x9a\0\0");
```
</div>

### Enum variant selection using magic

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
enum Command {
    #[br(magic = 0u8)] Nop,
    #[br(magic = 1u8)] Jump { loc: u32 },
    #[br(magic = 2u8)] Begin { var_count: u16, local_count: u16 }
}

# assert_eq!(
Command::read_le(&mut Cursor::new(b"\x01\0\0\0\0"))
# .unwrap(), Command::Jump { loc: 0 });
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
enum Command {
    #[bw(magic = 0u8)] Nop,
    #[bw(magic = 1u8)] Jump { loc: u32 },
    #[bw(magic = 2u8)] Begin { var_count: u16, local_count: u16 }
}

let object = Command::Jump { loc: 0 };
let mut output = Cursor::new(vec![]);
object.write_le(&mut output)
# .unwrap();
# assert_eq!(output.into_inner(), b"\x01\0\0\0\0");
```
</div>

<div class="br">

## Errors

If the specified magic number does not match the data, a
[`BadMagic`](crate::Error::BadMagic) error is returned and the reader’s
position is reset to where it was before parsing started.
</div>

# Map

The `map` and `try_map` directives allow data to be read using one type and
stored as another:

<div class="br">

```text
#[br(map = $map_fn:expr)] or #[br(map($map_fn:expr)))]
#[br(try_map = $map_fn:expr)] or #[br(try_map($map_fn:expr)))]
```
</div>
<div class="bw">

```text
#[bw(map = $map_fn:expr)] or #[bw(map($map_fn:expr)))]
#[bw(try_map = $map_fn:expr)] or #[bw(try_map($map_fn:expr)))]
```
</div>

<span class="brw">When using `#[br(map)]` on a field, the map function must
explicitly declare the type of the data to be read in its first parameter
and return a value which matches the type of the field.
When using `#[bw(map)]` on a field, the map function will receive
an immutable reference to the field value and must return a type which
implements [`BinWrite`](crate::BinWrite).</span>
<span class="br">When using `map` on a field, the map function must
explicitly declare the type of the data to be read in its first parameter
and return a value which matches the type of the field.</span>
<span class="bw">When using `map` on a field, the map function will receive
an immutable reference to the field value and must return a type which
implements [`BinWrite`](crate::BinWrite).</span>
The map function can be a plain function, closure, or call expression which
returns a plain function or closure.

When using `try_map`, the same rules apply, except that the function must
return a [`Result<T, E>`](Result) instead.

When using `map` or `try_map` on a struct or enum, the map function
<span class="brw">must return `Self` (`map`) or `Result<Self, E>` (`try_map`)
for `BinRead`. For `BinWrite`, it will receive an immutable reference to the
entire object and must return a type that implements [`BinWrite`](crate::BinWrite).</span>
<span class="br">must return `Self` (`map`) or `Result<Self, E>` (`try_map`).</span>
<span class="bw">will receive an immutable reference to the entire object
and must return a type that implements [`BinWrite`](crate::BinWrite).</span>

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be
referenced by the expression in the directive.

## Examples

### Using `map` on a field

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    #[br(map = |x: u8| x.to_string())]
    int_str: String
}

# assert_eq!(Cursor::new(b"\0").read_be::<MyType>().unwrap().int_str, "0");
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
struct MyType {
    #[bw(map = |x| x.parse::<u8>().unwrap())]
    int_str: String
}

let object = MyType { int_str: String::from("1") };
let mut output = Cursor::new(vec![]);
object.write_le(&mut output).unwrap();
assert_eq!(output.into_inner(), b"\x01");
```
</div>

### Using `try_map` on a field

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    #[br(try_map = |x: i8| x.try_into())]
    value: u8
}

# assert_eq!(Cursor::new(b"\0").read_be::<MyType>().unwrap().value, 0);
# assert!(Cursor::new(b"\xff").read_be::<MyType>().is_err());
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinWrite)]
struct MyType {
    #[bw(try_map = |x| { i8::try_from(*x) })]
    value: u8
}

let mut writer = Cursor::new(Vec::new());
writer.write_be(&MyType { value: 3 });
assert_eq!(writer.into_inner(), b"\x03")
```
</div>

### Using `map` on a struct to create a bit field

Either the [bilge](https://docs.rs/bilge/) or the
[modular-bitfield](https://docs.rs/modular-bitfield/) crate can be used along
with `map` to create a struct out of raw bits.

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
use modular_bitfield::prelude::*;

// This reads a single byte from the reader
#[bitfield]
#[derive(BinRead)]
#[br(map = Self::from_bytes)]
pub struct PackedData {
    status: B4,
    is_fast: bool,
    is_static: bool,
    is_alive: bool,
    is_good: bool,
}

// example byte: 0x53
// [good] [alive] [static] [fast] [status]
//      0       1        0      1     0011
//  false    true    false   true        3

let data = Cursor::new(b"\x53").read_le::<PackedData>().unwrap();
assert_eq!(data.is_good(), false);
assert_eq!(data.is_alive(), true);
assert_eq!(data.is_static(), false);
assert_eq!(data.is_fast(), true);
assert_eq!(data.status(), 3);
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::Cursor};
use modular_bitfield::prelude::*;

// The cursor dumps a single byte
#[bitfield]
#[derive(BinWrite, Clone, Copy)]
#[bw(map = |&x| Self::into_bytes(x))]
pub struct PackedData {
    status: B4,
    is_fast: bool,
    is_static: bool,
    is_alive: bool,
    is_good: bool,
}

let object = PackedData::new()
    .with_is_alive(true)
    .with_is_fast(true)
    .with_status(3);
let mut output = Cursor::new(vec![]);
output.write_le(&object).unwrap();
assert_eq!(output.into_inner(), b"\x53");
```
</div>

## Errors

If the `try_map` function returns a [`binrw::io::Error`](crate::io::Error)
or [`std::io::Error`], an [`Io`](crate::Error::Io) error is returned. For
any other error type, a [`Custom`](crate::Error::Custom) error is returned.

In all cases, the
<span class="br">reader’s</span><span class="bw">writer’s</span> position is
reset to where it was before parsing started.

<div class="br">

# Offset

The `offset` directive is shorthand for passing `offset` to a parser that
operates like [`FilePtr`](crate::FilePtr):

```text
#[br(offset = $offset:expr)] or #[br(offset($offset:expr))]
```

When manually implementing
[`BinRead::read_options`](crate::BinRead::read_options) or a
[custom parser function](#custom-parserswriters), the offset is accessible
from a named argument named `offset`.

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be
referenced by the expression in the directive.

## Examples

```
# use binrw::{prelude::*, io::Cursor, FilePtr};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(little)]
struct OffsetTest {
    #[br(offset = 4)]
    test: FilePtr<u8, u16>
}

# assert_eq!(
#   *OffsetTest::read(&mut Cursor::new(b"\0\xFF\xFF\xFF\x02\0")).unwrap().test,
#   2u16
# );
```

## Errors

If seeking to or reading from the offset fails, an [`Io`](crate::Error::Io)
error is returned and the reader’s position is reset to where it was before
parsing started.

</div>

# Padding and alignment

binrw includes directives for common forms of
[data structure alignment](https://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding).

The `pad_before` and `pad_after` directives skip a specific number of bytes
either before or after
<span class="br">reading</span><span class="bw">writing</span> a field,
respectively:

<div class="br">

```text
#[br(pad_after = $skip_bytes:expr)] or #[br(pad_after($skip_bytes:expr))]
#[br(pad_before = $skip_bytes:expr)] or #[br(pad_before($skip_bytes:expr))]
```
</div>
<div class="bw">

```text
#[bw(pad_after = $skip_bytes:expr)] or #[bw(pad_after($skip_bytes:expr))]
#[bw(pad_before = $skip_bytes:expr)] or #[bw(pad_before($skip_bytes:expr))]
```
</div>

This is equivalent to:

```
# let mut pos = 0;
# let padding = 0;
pos += padding;
```

---

The `align_before` and `align_after` directives align the next
<span class="br">read</span><span class="bw">write</span> to the
given byte alignment either before or after
<span class="br">reading</span><span class="bw">writing</span> a field,
respectively:

<div class="br">

```text
#[br(align_after = $align_to:expr)] or #[br(align_after($align_to:expr))]
#[br(align_before = $align_to:expr)] or #[br(align_before($align_to:expr))]
```
</div>
<div class="bw">

```text
#[bw(align_after = $align_to:expr)] or #[bw(align_after($align_to:expr))]
#[bw(align_before = $align_to:expr)] or #[bw(align_before($align_to:expr))]
```
</div>

This is equivalent to:

```
# let mut pos = 0;
# let align = 1;
if pos % align != 0 {
    pos += align - (pos % align);
}
```

---

The `seek_before` directive accepts a [`SeekFrom`](crate::io::SeekFrom)
object and seeks the
<span class="br">reader</span><span class="bw">writer</span> to an arbitrary
position before
<span class="br">reading</span><span class="bw">writing</span> a field:

<div class="br">

```text
#[br(seek_before = $seek_from:expr)] or #[br(seek_before($seek_from:expr))]
```
</div>
<div class="bw">

```text
#[bw(seek_before = $seek_from:expr)] or #[bw(seek_before($seek_from:expr))]
```
</div>

This is equivalent to:

```
# use binrw::io::Seek;
# let mut stream = binrw::io::Cursor::new(vec![]);
# let seek_from = binrw::io::SeekFrom::Start(0);
stream.seek(seek_from)?;
# Ok::<(), binrw::io::Error>(())
```

The position of the
<span class="br">reader</span><span class="bw">writer</span> will not be
restored after the seek; use the
[`restore_position`](#restore-position) directive to seek, then
<span class="br">read</span><span class="bw">write</span>, then restore
position.

---

The `pad_size_to` directive will ensure that the
<span class="br">reader</span><span class="bw">writer</span> has advanced at
least the number of bytes given after the field has been
<span class="br">read</span><span class="bw">written</span>:

<div class="br">

```text
#[br(pad_size_to = $size:expr)] or #[br(pad_size_to($size:expr))]
```
</div>
<div class="bw">

```text
#[bw(pad_size_to = $size:expr)] or #[bw(pad_size_to($size:expr))]
```
</div>

For example, if a format uses a null-terminated string, but always reserves
at least 256 bytes for that string, [`NullString`](crate::NullString) will
read the string and `pad_size_to(256)` will ensure the reader skips whatever
padding, if any, remains. If the string is longer than 256 bytes, no padding
will be skipped.

Any <span class="brw">(earlier only, when reading)</span><span class="br">earlier</span>
field or [import](#arguments) can be
referenced by the expressions in any of these directives.

## Examples

<div class="br">

```
# use binrw::{prelude::*, NullString, io::SeekFrom};
#[derive(BinRead)]
struct MyType {
    #[br(align_before = 4, pad_after = 1, align_after = 4)]
    str: NullString,

    #[br(pad_size_to = 0x10)]
    test: u64,

    #[br(seek_before = SeekFrom::End(-4))]
    end: u32,
}
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, NullString, io::SeekFrom};
#[derive(BinWrite)]
struct MyType {
    #[bw(align_before = 4, pad_after = 1, align_after = 4)]
    str: NullString,

    #[bw(pad_size_to = 0x10)]
    test: u64,

    #[bw(seek_before = SeekFrom::End(-4))]
    end: u32,
}
```
</div>

## Errors

If seeking fails, an [`Io`](crate::Error::Io) error is returned and the
<span class="br">reader’s</span><span class="bw">writer’s</span> position is
reset to where it was before
<span class="br">parsing</span><span class="bw">serialisation</span>
started.

<div class="br">

# Pre-assert

`pre_assert` works like [`assert`](#assert), but checks the condition before
data is read instead of after:

```text
#[br(pre_assert($cond:expr $(,)?))]
#[br(pre_assert($cond:expr, $msg:literal $(,)?)]
#[br(pre_assert($cond:expr, $fmt:literal, $($arg:expr),* $(,)?))]
#[br(pre_assert($cond:expr, $err:expr $(,)?)]
```

This is most useful when validating arguments or selecting an enum variant.

## Examples

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
#[br(import { ty: u8 })]
enum Command {
    #[br(pre_assert(ty == 0))] Variant0(u16, u16),
    #[br(pre_assert(ty == 1))] Variant1(u32)
}

#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
struct Message {
    ty: u8,
    len: u8,
    #[br(args { ty })]
    data: Command
}

let msg = Cursor::new(b"\x01\x04\0\0\0\xFF").read_be::<Message>();
assert!(msg.is_ok());
let msg = msg.unwrap();
assert_eq!(msg, Message { ty: 1, len: 4, data: Command::Variant1(0xFF) });
```
</div>

# Repr

The `repr` directive is used on a unit-like (C-style) enum to specify the
underlying type to use when
<span class="br">reading</span><span class="bw">writing</span> the
field<span class="br"> and matching variants</span>:

<div class="br">

```text
#[br(repr = $ty:ty)] or #[br(repr($ty:ty))]
```
</div>
<div class="bw">

```text
#[bw(repr = $ty:ty)] or #[bw(repr($ty:ty))]
```
</div>

## Examples

<div class="br">

```
# use binrw::BinRead;
#[derive(BinRead)]
#[br(big, repr = i16)]
enum FileKind {
    Unknown = -1,
    Text,
    Archive,
    Document,
    Picture,
}
```
</div>
<div class="bw">

```
# use binrw::BinWrite;
#[derive(BinWrite)]
#[bw(big, repr = i16)]
enum FileKind {
    Unknown = -1,
    Text,
    Archive,
    Document,
    Picture,
}
```
</div>

## Errors

If a <span class="br">read</span><span class="bw">write</span> fails, an
[`Io`](crate::Error::Io) error is returned. <span class="br">If no variant
matches, a [`NoVariantMatch`](crate::Error::NoVariantMatch) error is
returned.</span>

In all cases, the
<span class="br">reader’s</span><span class="bw">writer’s</span> position is
reset to where it was before
<span class="br">parsing</span><span class="bw">serialisation</span>
started.

# Restore position

The `restore_position` directive restores the position of the
<span class="br">reader</span><span class="bw">writer</span> after a field
is <span class="br">read</span><span class="bw">written</span>:

<div class="br">

```text
#[br(restore_position)]
```
</div>
<div class="bw">

```text
#[bw(restore_position)]
```
</div>

To seek to an arbitrary position, use [`seek_before`](#padding-and-alignment)
instead.

## Examples

<div class="br">

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
# #[derive(Debug, PartialEq)]
struct MyType {
    #[br(restore_position)]
    test: u32,
    test_bytes: [u8; 4]
}

# assert_eq!(
#   Cursor::new(b"\0\0\0\x01").read_be::<MyType>().unwrap(),
#   MyType { test: 1, test_bytes: [0,0,0,1]}
# );
```
</div>
<div class="bw">

```
# use binrw::{prelude::*, io::{Cursor, SeekFrom}};
#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
#[bw(big)]
struct Relocation {
    #[bw(ignore)]
    delta: u32,
    #[bw(seek_before(SeekFrom::Current((*delta).into())))]
    reloc: u32,
}

#[derive(BinWrite)]
# #[derive(Debug, PartialEq)]
#[bw(big)]
struct Executable {
    #[bw(restore_position)]
    code: Vec<u8>,
    relocations: Vec<Relocation>,
}

let object = Executable {
    code: vec![ 1, 2, 3, 4, 0, 0, 0, 0, 9, 10, 0, 0, 0, 0 ],
    relocations: vec![
        Relocation { delta: 4, reloc: 84281096 },
        Relocation { delta: 2, reloc: 185339150 },
    ]
};
let mut output = Cursor::new(vec![]);
object.write(&mut output).unwrap();
assert_eq!(
  output.into_inner(),
  b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e"
);
```
</div>

## Errors

If querying or restoring the
<span class="br">reader</span><span class="bw">writer</span> position fails,
an [`Io`](crate::Error::Io) error is returned and the
<span class="br">reader’s</span><span class="bw">writer’s</span>
position is reset to where it was before
<span class="br">parsing</span><span class="bw">serialisation</span>
started.

# Stream access and manipulation

The `stream` directive allows direct access to the underlying
<span class="br">read</span><span class="bw">write</span> stream on a struct or
enum:

<div class="br">

```text
#[br(stream = $ident:ident)] or #[br(stream($ident:ident))]
```
</div>
<div class="bw">

```text
#[bw(stream = $ident:ident)] or #[bw(stream($ident:ident))]
```
</div>

The `map_stream` directive allows the <span class="br">read</span><span class="bw">write</span>
stream to be replaced with another stream when <span class="br">reading</span><span class="bw">writing</span>
an object or field:

<div class="br">

```text
#[br(map_stream = $map_fn:expr)] or #[br(map_stream($map_fn:expr))]
```
</div>
<div class="bw">

```text
#[bw(map_stream = $map_fn:expr)] or #[bw(map_stream($map_fn:expr))]
```
</div>

The map function can be a plain function, closure, or call expression which
returns a plain function or closure. The returned object must
implement <span class="br">[`Read`](crate::io::Read) + [`Seek`](crate::io::Seek)</span><span class="brw"> (for reading)
or </span><span class="bw">[`Write`](crate::io::Write) + [`Seek`](crate::io::Seek)</span><span class="brw"> (for writing)</span>.

The mapped stream is used to <span class="br">read</span><span class="bw">write</span>
the *contents* of the field or object it is applied to:

<div class="br">

```
# use binrw::{prelude::*, io::{TakeSeek, TakeSeekExt}};
fn make_stream<S: binrw::io::Read + binrw::io::Seek>(s: S) -> /**/
    /**/
# S {
#     s
}

#[derive(BinRead)]
// `magic` does not use the mapped stream
#[br(magic = b"foo", map_stream = make_stream)]
struct Foo {
    // everything inside the struct uses the mapped stream
    a: u32,
    /* … */
}

#[derive(BinRead)]
struct Bar {
    // `pad_before` and `pad_after` do not use the mapped stream
    #[br(pad_before(4), pad_after(4), map_stream = make_stream)]
    b: u64 // reading `u64` uses the mapped stream
}
```
</div>

<div class="bw">

```
# use binrw::{prelude::*, io::{TakeSeek, TakeSeekExt}};
fn make_stream<S: binrw::io::Write + binrw::io::Seek>(s: S) -> /**/
    /**/
# S {
#     s
}

#[derive(BinWrite)]
// `magic` does not use the mapped stream
#[bw(magic = b"foo", map_stream = make_stream)]
struct Foo {
    // everything inside the struct uses the mapped stream
    a: u32,
    /* … */
}

#[derive(BinWrite)]
struct Bar {
    // `pad_before` and `pad_after` do not use the mapped stream
    #[bw(pad_before(4), pad_after(4), map_stream = make_stream)]
    b: u64 // writing `u64` uses the mapped stream
}
```
</div>

## Examples

<div class="br">

### Verifying a checksum

```
# use core::num::Wrapping;
# use binrw::{binread, BinRead, io::{Cursor, Read, Seek, SeekFrom}};
#
# struct Checksum<T> {
#     inner: T,
#     check: Wrapping<u8>,
# }
#
# impl<T> Checksum<T> {
#    fn new(inner: T) -> Self {
#         Self {
#             inner,
#             check: Wrapping(0),
#         }
#    }
#
#    fn check(&self) -> u8 {
#        self.check.0
#    }
# }
#
# impl<T: Read> Read for Checksum<T> {
#     fn read(&mut self, buf: &mut [u8]) -> binrw::io::Result<usize> {
#         let size = self.inner.read(buf)?;
#         for b in &buf[0..size] {
#             self.check += b;
#         }
#         Ok(size)
#     }
# }
#
# impl<T: Seek> Seek for Checksum<T> {
#     fn seek(&mut self, pos: SeekFrom) -> binrw::io::Result<u64> {
#         self.inner.seek(pos)
#     }
# }
#
#[binread]
# #[derive(Debug, PartialEq)]
#[br(little, stream = r, map_stream = Checksum::new)]
struct Test {
    a: u16,
    b: u16,
    #[br(temp, assert(c == r.check() - c, "bad checksum: {:#x?} != {:#x?}", c, r.check() - c))]
    c: u8,
}

assert_eq!(
    Test::read(&mut Cursor::new(b"\x01\x02\x03\x04\x0a")).unwrap(),
    Test {
        a: 0x201,
        b: 0x403,
    }
);
```

### Reading encrypted blocks

```
# use binrw::{binread, BinRead, io::{Cursor, Read, Seek, SeekFrom}, helpers::until_eof};
#
# struct BadCrypt<T> {
#     inner: T,
#     key: u8,
# }
#
# impl<T> BadCrypt<T> {
#     fn new(inner: T, key: u8) -> Self {
#         Self { inner, key }
#     }
# }
#
# impl<T: Read> Read for BadCrypt<T> {
#     fn read(&mut self, buf: &mut [u8]) -> binrw::io::Result<usize> {
#         let size = self.inner.read(buf)?;
#         for b in &mut buf[0..size] {
#             *b ^= core::mem::replace(&mut self.key, *b);
#         }
#         Ok(size)
#     }
# }
#
# impl<T: Seek> Seek for BadCrypt<T> {
#     fn seek(&mut self, pos: SeekFrom) -> binrw::io::Result<u64> {
#         self.inner.seek(pos)
#     }
# }
#
#[binread]
# #[derive(Debug, PartialEq)]
#[br(little)]
struct Test {
    iv: u8,
    #[br(parse_with = until_eof, map_stream = |reader| BadCrypt::new(reader, iv))]
    data: Vec<u8>,
}

assert_eq!(
    Test::read(&mut Cursor::new(b"\x01\x03\0\x04\x01")).unwrap(),
    Test {
        iv: 1,
        data: vec![2, 3, 4, 5],
    }
);
```

</div>

<div class="bw">

### Writing a checksum

```
# use core::num::Wrapping;
# use binrw::{binwrite, BinWrite, io::{Cursor, Write, Seek, SeekFrom}};
# struct Checksum<T> {
#     inner: T,
#     check: Wrapping<u8>,
# }
#
# impl<T> Checksum<T> {
#    fn new(inner: T) -> Self {
#         Self {
#             inner,
#             check: Wrapping(0),
#         }
#    }
#
#    fn check(&self) -> u8 {
#        self.check.0
#    }
# }
#
# impl<T: Write> Write for Checksum<T> {
#     fn write(&mut self, buf: &[u8]) -> binrw::io::Result<usize> {
#         for b in buf {
#             self.check += b;
#         }
#         self.inner.write(buf)
#     }
#
#     fn flush(&mut self) -> binrw::io::Result<()> {
#         self.inner.flush()
#     }
# }
#
# impl<T: Seek> Seek for Checksum<T> {
#     fn seek(&mut self, pos: SeekFrom) -> binrw::io::Result<u64> {
#         self.inner.seek(pos)
#     }
# }
#
#[binwrite]
#[bw(little, stream = w, map_stream = Checksum::new)]
struct Test {
    a: u16,
    b: u16,
    #[bw(calc(w.check()))]
    c: u8,
}

let mut out = Cursor::new(Vec::new());
Test { a: 0x201, b: 0x403 }.write(&mut out).unwrap();

assert_eq!(out.into_inner(), b"\x01\x02\x03\x04\x0a");
```

### Writing encrypted blocks

```
# use binrw::{binwrite, BinWrite, io::{Cursor, Write, Seek, SeekFrom}};
#
# struct BadCrypt<T> {
#     inner: T,
#     key: u8,
# }
#
# impl<T> BadCrypt<T> {
#     fn new(inner: T, key: u8) -> Self {
#         Self { inner, key }
#     }
# }
#
# impl<T: Write> Write for BadCrypt<T> {
#     fn write(&mut self, buf: &[u8]) -> binrw::io::Result<usize> {
#         let mut w = 0;
#         for b in buf {
#             self.key ^= b;
#             w += self.inner.write(&[self.key])?;
#         }
#         Ok(w)
#     }
#
#     fn flush(&mut self) -> binrw::io::Result<()> {
#         self.inner.flush()
#     }
# }
#
# impl<T: Seek> Seek for BadCrypt<T> {
#     fn seek(&mut self, pos: SeekFrom) -> binrw::io::Result<u64> {
#         self.inner.seek(pos)
#     }
# }
#
#[binwrite]
# #[derive(Debug, PartialEq)]
#[bw(little)]
struct Test {
    iv: u8,
    #[bw(map_stream = |writer| BadCrypt::new(writer, *iv))]
    data: Vec<u8>,
}

let mut out = Cursor::new(Vec::new());
Test { iv: 1, data: vec![2, 3, 4, 5] }.write(&mut out).unwrap();
assert_eq!(out.into_inner(), b"\x01\x03\0\x04\x01");
```
</div>

<div class="br">

# Temp

<div class="warning">

This directive can only be used with [`binread`](macro@crate::binread). It
will not work with `#[derive(BinRead)]`.

When using `#[br(temp)]`, the `#[binread]` attribute must be placed *before*
other attributes like `#[derive(Debug)]`. Otherwise, the other attributes will
generate code that references non-existent fields, and compilation will fail.
</div>

The `temp` directive causes a field to be treated as a temporary variable
instead of an actual field. The field will be removed from the struct
definition generated by [`binread`](macro@crate::binread):

```text
#[br(temp)]
```

This allows data to be read which is necessary for parsing an object but
which doesn’t need to be stored in the final object. To skip data entirely,
use an [alignment directive](#padding-and-alignment) instead.

## Examples

```
# use binrw::{BinRead, io::Cursor, binread};
#[binread] // ← must be before other attributes that use struct fields
# #[derive(Debug, PartialEq)]
#[br(big)]
struct Test {
    // Since `Vec` stores its own length, this field is redundant
    #[br(temp)]
    len: u32,

    #[br(count = len)]
    data: Vec<u8>
}

assert_eq!(
    Test::read(&mut Cursor::new(b"\0\0\0\x05ABCDE")).unwrap(),
    Test { data: b"ABCDE".to_vec() }
);
```
</div>

<div class="br">

# Try

The `try` directive allows parsing of a field to fail instead
of returning an error:

```text
#[br(try)]
```

If the field cannot be parsed, the position of the reader will be restored
and the value of the field will be set to the [`default`](core::default::Default) value for the type.

## Examples

```
# use binrw::{prelude::*, io::Cursor};
#[derive(BinRead)]
struct MyType {
    #[br(try)]
    maybe_u32: Option<u32>
}

assert_eq!(Cursor::new(b"").read_be::<MyType>().unwrap().maybe_u32, None);
```
</div>