hao 0.0.19

Read, edit, create and write .net assemblies
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
use crate::{
    dotnet::md::{
        calculator::{CalculateTableSize, SizeCalculator},
        streams::Version,
    },
    error::Result,
    io::ReadData,
};

use super::{coded_tokens::*, reader::TablesStreamReader, streams_offsets::*};
use bitflags::bitflags;

/// A row of the Module table (ECMA-335 §II.22.30): this module's name and
/// identity. A valid file has exactly one.
#[derive(Debug, Clone)]
pub struct ModulesTableRow {
    /// Edit and Continue generation; 0 in a normal file.
    pub generation: u16,
    /// File name of the module, e.g. `Example.dll`, in #Strings.
    pub name: StringsStreamOffset,
    /// The module version ID in #GUID, a GUID that changes on every build.
    pub mvid: GuidStreamOffset,
    /// Edit and Continue ID in #GUID; 0 in a normal file.
    pub enc_id: GuidStreamOffset,
    /// Edit and Continue base ID in #GUID; 0 in a normal file.
    pub enc_base_id: GuidStreamOffset,
}

impl<'a> CalculateTableSize<ModulesTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u16>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + GuidStreamOffset::streams_offset_size(self.flags).byte_size()
            + GuidStreamOffset::streams_offset_size(self.flags).byte_size()
            + GuidStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<ModulesTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ModulesTableRow> {
        if self.header.table_locations.module.rows != 1 {
            return Err(crate::error::HaoError::BadImageFormat(
                "Module table should have exactly one entry",
            ));
        }
        Ok(ModulesTableRow {
            generation: self.read()?,
            name: self.read()?,
            mvid: self.read()?,
            enc_id: self.read()?,
            enc_base_id: self.read()?,
        })
    }
}

/// A row of the TypeRef table (ECMA-335 §II.22.38): a type defined in another
/// module or assembly.
#[derive(Debug, Clone)]
pub struct TypeRefTableRow {
    /// Where the type is defined: an assembly, a module, or for a nested
    /// type the enclosing TypeRef.
    pub resolution_scope: CodedToken<ResolutionScopeToken>,
    /// Type name in #Strings.
    pub name: StringsStreamOffset,
    /// Namespace in #Strings; empty for nested types.
    pub namespace: StringsStreamOffset,
}

impl<'a> CalculateTableSize<TypeRefTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        ResolutionScopeToken::token_size(self.coded_tokens_sizes).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<TypeRefTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<TypeRefTableRow> {
        Ok(TypeRefTableRow {
            resolution_scope: self.read()?,
            name: self.read()?,
            namespace: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a TypeDef or ExportedType row (ECMA-335 §II.23.1.15): visibility,
    /// layout, class or interface, and interop string format.
    ///
    /// Masked groups (visibility, layout, ...) are values, not bits: compare
    /// `flags & TypeAttributes::VisibilityMask` against a value instead of using
    /// `contains`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct TypeAttributes: u32 {
        /// Mask for the visibility values, `NotPublic` to `NestedFamORAssem`.
        const VisibilityMask = 0x00000007;
        /// Top-level, not visible outside the assembly (`internal`).
        const NotPublic = 0x00000000;
        /// Top-level, visible outside the assembly.
        const Public = 0x00000001;
        /// Nested, `public`.
        const NestedPublic = 0x00000002;
        /// Nested, `private`.
        const NestedPrivate = 0x00000003;
        /// Nested, `protected`.
        const NestedFamily = 0x00000004;
        /// Nested, `internal`.
        const NestedAssembly = 0x00000005;
        /// Nested, `private protected`.
        const NestedFamANDAssem = 0x00000006;
        /// Nested, `protected internal`.
        const NestedFamORAssem = 0x00000007;

        /// Mask for the field layout values.
        const LayoutMask = 0x00000018;
        /// The runtime picks the field layout.
        const AutoLayout = 0x00000000;
        /// Fields are laid out in declaration order.
        const SequentialLayout = 0x00000008;
        /// Field offsets are given explicitly, in the FieldLayout table.
        const ExplicitLayout = 0x00000010;

        /// Mask for class or interface.
        const ClassSemanticsMask = 0x00000060;
        /// A class or value type.
        const Class = 0x00000000;
        /// An interface.
        const Interface = 0x00000020;

        /// Can't be instantiated.
        const Abstract = 0x00000080;
        /// Can't be inherited from.
        const Sealed = 0x00000100;
        /// The name has a special meaning, described by the name.
        const SpecialName = 0x00000400;

        /// Imported from a COM type library.
        const Import = 0x00001000;
        /// Can be serialized (`[Serializable]`).
        const Serializable = 0x00002000;

        /// Mask for how `LPTSTR` strings are marshalled.
        const StringFormatMask = 0x00030000;
        /// Strings marshal as ANSI.
        const AnsiClass = 0x00000000;
        /// Strings marshal as UTF-16.
        const UnicodeClass = 0x00010000;
        /// The platform picks how strings marshal.
        const AutoClass = 0x00020000;
        /// Strings use a non-standard encoding, given by `CustomFormatMask`.
        const CustomFormatClass = 0x00030000;
        /// Mask for the non-standard string encoding; its meaning is unspecified.
        const CustomFormatMask = 0x00C00000;

        /// The type initializer may run any time before the first static field
        /// access, rather than exactly at it.
        const BeforeFieldInit = 0x00100000;
        /// On an ExportedType: a type forwarder to another assembly.
        const Forwarder = 0x00200000;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0x00040800;
        /// The runtime checks the name's encoding.
        const RTSpecialName = 0x00000800;
        /// Has declarative security (DeclSecurity rows).
        const HasSecurity = 0x00040000;
    }
}

/// A row of the TypeDef table (ECMA-335 §II.22.37): a type defined in this
/// module. Row 1 is the global `<Module>` type.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeDefTableRow {
    /// Visibility, layout, class or interface, and more.
    pub flags: TypeAttributes,
    /// Type name in #Strings.
    pub name: StringsStreamOffset,
    /// Namespace in #Strings; empty for nested types.
    pub namespace: StringsStreamOffset,
    /// Base type; null (row 0) for interfaces and `System.Object`.
    pub extends: CodedToken<TypeDefOrRefToken>,
    /// First of the type's fields. They run up to the next type's
    /// `field_list`.
    pub field_list: FieldTableOffset,
    /// First of the type's methods. They run up to the next type's
    /// `method_list`.
    pub method_list: MethodTableOffset,
}

impl<'a> CalculateTableSize<TypeDefTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<TypeAttributes>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + TypeDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
            + FieldTableOffset::table_offset_size(self.rows).byte_size()
            + MethodTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<TypeDefTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<TypeDefTableRow> {
        Ok(TypeDefTableRow {
            flags: TypeAttributes::from_bits_retain(self.read()?),
            name: self.read()?,
            namespace: self.read()?,
            extends: self.read()?,
            field_list: self.read()?,
            method_list: self.read()?,
        })
    }
}

/// A row of the FieldPtr table: an indirection that unoptimized (`#-`)
/// metadata uses to list Fields out of order. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct FieldPtrTableRow {
    /// The Field row this slot stands for.
    pub field: FieldTableOffset,
}

impl<'a> CalculateTableSize<FieldPtrTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        FieldTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<FieldPtrTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FieldPtrTableRow> {
        Ok(FieldPtrTableRow {
            field: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a Field row (ECMA-335 §II.23.1.5): accessibility, `static`,
    /// `readonly`, `const` and where extra data about the field is.
    ///
    /// The accessibility values are not bits: compare
    /// `flags & FieldFlags::FieldAccessMask` against one.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct FieldFlags: u16 {
        /// Mask for the accessibility values.
        const FieldAccessMask = 0x0007;
        /// Can't be referenced; compiler-controlled.
        const PrivateScope = 0x0000;
        /// `private`: only the declaring type.
        const Private = 0x0001;
        /// `private protected`: subtypes in this assembly.
        const FamANDAssem = 0x0002;
        /// `internal`: anything in this assembly.
        const Assembly = 0x0003;
        /// `protected`: the declaring type and its subtypes.
        const Family = 0x0004;
        /// `protected internal`: subtypes anywhere, plus this assembly.
        const FamORAssem = 0x0005;
        /// `public`.
        const Public = 0x0006;

        /// One per type rather than one per instance.
        const Static = 0x0010;
        /// Only set by a constructor (`readonly`).
        const InitOnly = 0x0020;
        /// A compile-time constant (`const`); the value is in the Constant table.
        const Literal = 0x0040;
        /// Skipped when the type is serialized (`[NonSerialized]`).
        const NotSerialized = 0x0080;

        /// The name has a special meaning, described by the name.
        const SpecialName = 0x0200;

        /// Implemented through P/Invoke (ImplMap table).
        const PinvokeImpl = 0x2000;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0x9500;
        /// The runtime checks the name's encoding.
        const RTSpecialName = 0x0400;
        /// Has marshalling info (FieldMarshal table).
        const HasFieldMarshal = 0x1000;
        /// Has a default value (Constant table).
        const HasDefault = 0x8000;
        /// Has initial data in the image (FieldRVA table), e.g. an array initializer.
        const HasFieldRVA = 0x0100;
    }
}

/// A row of the Field table (ECMA-335 §II.22.15): a field defined in this module.
#[derive(Debug, Clone)]
pub struct FieldTableRow {
    /// Accessibility, `static`, `readonly`, `const`, and more.
    pub flags: FieldFlags,
    /// Field name in #Strings.
    pub name: StringsStreamOffset,
    /// Field signature (§II.23.2.4) in #Blob: the field's type.
    pub signature: BlobStreamOffset,
}

impl<'a> CalculateTableSize<FieldTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<FieldFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<FieldTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FieldTableRow> {
        Ok(FieldTableRow {
            flags: FieldFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            signature: self.read()?,
        })
    }
}

/// A row of the MethodPtr table: an indirection that unoptimized (`#-`)
/// metadata uses to list MethodDefs out of order. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct MethodPtrTableRow {
    /// The MethodDef row this slot stands for.
    pub method: MethodTableOffset,
}

impl<'a> CalculateTableSize<MethodPtrTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        MethodTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<MethodPtrTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodPtrTableRow> {
        Ok(MethodPtrTableRow {
            method: self.read()?,
        })
    }
}

bitflags! {
    /// Implementation flags of a MethodDef row (ECMA-335 §II.23.1.11): what kind of
    /// code the body is, and how the runtime treats it.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct MethodImplFlags: u16 {
        /// Mask for the code type values.
        const CodeTypeMask = 0x0003;
        /// The body is CIL.
        const IL = 0x0000;
        /// The body is native code.
        const Native = 0x0001;
        /// Optimized CIL; reserved, shouldn't be set.
        const OPTIL = 0x0002;
        /// The runtime provides the body, e.g. a delegate's `Invoke`.
        const Runtime = 0x0003;

        /// Mask for managed or unmanaged.
        const ManagedMask = 0x0004;
        /// The body is unmanaged code.
        const Unmanaged = 0x0004;
        /// The body is managed code.
        const Managed = 0x0000;

        /// Declared here but defined elsewhere; used when merging modules.
        const ForwardRef = 0x0010;
        /// The signature is exported as is, without HRESULT conversion.
        const PreserveSig = 0x0080;

        /// Implemented inside the runtime (`[MethodImpl(InternalCall)]`).
        const InternalCall = 0x1000;

        /// The body holds a lock while it runs (`[MethodImpl(Synchronized)]`).
        const Synchronized = 0x0020;
        /// Must not be inlined.
        const NoInlining = 0x0008;
        /// Range check value, not a flag.
        const MaxMethodImplVal = 0xffff;
    }
}

bitflags! {
    /// Flags of a MethodDef row (ECMA-335 §II.23.1.10): accessibility, `static`,
    /// `virtual`, vtable layout and interop.
    ///
    /// The accessibility and vtable layout values are not bits: compare
    /// `flags & MethodFlags::MemberAccessMask` against one.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct MethodFlags: u16 {
        /// Mask for the accessibility values.
        const MemberAccessMask = 0x0007;
        /// Can't be referenced; compiler-controlled.
        const PrivateScope = 0x0000;
        /// `private`: only the declaring type.
        const Private = 0x0001;
        /// `private protected`: subtypes in this assembly.
        const FamANDAssem = 0x0002;
        /// `internal`: anything in this assembly.
        const Assem = 0x0003;
        /// `protected`: the declaring type and its subtypes.
        const Family = 0x0004;
        /// `protected internal`: subtypes anywhere, plus this assembly.
        const FamORAssem = 0x0005;
        /// `public`.
        const Public = 0x0006;

        /// Has no `this`; called on the type.
        const Static = 0x0010;
        /// Can't be overridden (`sealed override`).
        const Final = 0x0020;
        /// Dispatched through the vtable.
        const Virtual = 0x0040;
        /// Hides base methods by name and signature, not by name alone.
        const HideBySig = 0x0080;

        /// Mask for the vtable slot values.
        const VtableLayoutMask = 0x0100;
        /// Reuses the base method's vtable slot, overriding it. The default.
        const ReuseSlot = 0x0000;
        /// Gets a new vtable slot (`new virtual`).
        const NewSlot = 0x0100;

        /// Can only be overridden where it is also accessible.
        const CheckAccessOnOverride = 0x0200;
        /// Has no body.
        const Abstract = 0x0400;
        /// The name has a special meaning, e.g. property accessors and operators.
        const SpecialName = 0x0800;

        /// Implemented through P/Invoke (ImplMap table).
        const PinvokeImpl = 0x2000;
        /// Exported to unmanaged code through a thunk.
        const UnmanagedExport = 0x0008;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0xd000;
        /// The runtime checks the name, as for `.ctor` and `.cctor`.
        const RTSpecialName = 0x1000;
        /// Has declarative security (DeclSecurity rows).
        const HasSecurity = 0x4000;
        /// Calls another method that has security code.
        const RequireSecObject = 0x8000;
    }
}

/// A row of the MethodDef table (ECMA-335 §II.22.26): a method defined in this
/// module.
#[derive(Debug, Clone)]
pub struct MethodTableRow {
    /// RVA of the method body; 0 for abstract, runtime-provided and P/Invoke
    /// methods.
    pub rva: u32,
    /// Code type (IL, native, runtime) and implementation details.
    pub impl_flags: MethodImplFlags,
    /// Accessibility, `static`, `virtual`, vtable layout, and more.
    pub flags: MethodFlags,
    /// Method name in #Strings.
    pub name: StringsStreamOffset,
    /// Method signature (§II.23.2.1) in #Blob: calling convention,
    /// parameter and return types.
    pub signature: BlobStreamOffset,
    /// First of the method's Param rows. They run up to the next method's
    /// `param_list`.
    pub param_list: ParamTableOffset,
}

impl<'a> CalculateTableSize<MethodTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
            + self.size_of_prim::<MethodImplFlags>()
            + self.size_of_prim::<MethodFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
            + ParamTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<MethodTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodTableRow> {
        Ok(MethodTableRow {
            rva: self.read()?,
            impl_flags: MethodImplFlags::from_bits_retain(self.read()?),
            flags: MethodFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            signature: self.read()?,
            param_list: self.read()?,
        })
    }
}

/// A row of the ParamPtr table: an indirection that unoptimized (`#-`)
/// metadata uses to list Params out of order. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct ParamPtrTableRow {
    /// The Param row this slot stands for.
    pub param: ParamTableOffset,
}

impl<'a> CalculateTableSize<ParamPtrTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        ParamTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<ParamPtrTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ParamPtrTableRow> {
        Ok(ParamPtrTableRow {
            param: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a Param row (ECMA-335 §II.23.1.13).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct ParamFlags: u16 {
        /// An input parameter (`[In]`).
        const In = 0x0001;
        /// An output parameter (`[Out]`, as on `out`).
        const Out = 0x0002;
        /// Optional (`[Optional]`).
        const Optional = 0x0010;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0xf000;
        /// Has a default value (Constant table).
        const HasDefault = 0x1000;
        /// Has marshalling info (FieldMarshal table).
        const HasFieldMarshal = 0x2000;

        /// Bits ECMA-335 leaves unused.
        const Unused = 0xcfe0;
    }
}

/// A row of the Param table (ECMA-335 §II.22.33): a parameter's name and flags.
/// Parameter types are in the method's signature, not here.
#[derive(Debug, Clone)]
pub struct ParamTableRow {
    /// `[In]`/`[Out]`, optional, and whether it has a default or marshalling.
    pub flags: ParamFlags,
    /// Position: 1 for the first parameter, 0 for the return value.
    pub sequence: u16,
    /// Parameter name in #Strings.
    pub name: StringsStreamOffset,
}

impl<'a> CalculateTableSize<ParamTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<ParamFlags>()
            + self.size_of_prim::<u16>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<ParamTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ParamTableRow> {
        Ok(ParamTableRow {
            flags: ParamFlags::from_bits_retain(self.read()?),
            sequence: self.read()?,
            name: self.read()?,
        })
    }
}

/// A row of the InterfaceImpl table (ECMA-335 §II.22.23): an interface a type
/// implements.
#[derive(Debug, Clone)]
pub struct InterfaceImplTableRow {
    /// The implementing type.
    pub class: TypeDefTableOffset,
    /// The implemented interface.
    pub interface: CodedToken<TypeDefOrRefToken>,
}

impl<'a> CalculateTableSize<InterfaceImplTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        TypeDefTableOffset::table_offset_size(self.rows).byte_size()
            + TypeDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<InterfaceImplTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<InterfaceImplTableRow> {
        Ok(InterfaceImplTableRow {
            class: self.read()?,
            interface: self.read()?,
        })
    }
}

/// A row of the MemberRef table (ECMA-335 §II.22.25): a reference to a method
/// or field, usually of a type in another module.
#[derive(Debug, Clone)]
pub struct MemberRefTableRow {
    /// Where the member is, usually its declaring type.
    pub class: CodedToken<MemberRefParentToken>,
    /// Member name in #Strings.
    pub name: StringsStreamOffset,
    /// Method or field signature in #Blob.
    pub signature: BlobStreamOffset,
}

impl<'a> CalculateTableSize<MemberRefTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        MemberRefParentToken::token_size(self.coded_tokens_sizes).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<MemberRefTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MemberRefTableRow> {
        Ok(MemberRefTableRow {
            class: self.read()?,
            name: self.read()?,
            signature: self.read()?,
        })
    }
}

/// A row of the Constant table (ECMA-335 §II.22.9): the default value of a field,
/// parameter or property.
#[derive(Debug, Clone)]
pub struct ConstantTableRow {
    /// Element type of the value (§II.23.1.16), e.g. `ELEMENT_TYPE_I4`.
    pub ty: u8,
    /// Padding byte, 0.
    pub padding: u8,
    /// The field, parameter or property the value belongs to.
    pub parent: CodedToken<HasConstantToken>,
    /// The value's bytes in #Blob.
    pub value: BlobStreamOffset,
}

impl<'a> CalculateTableSize<ConstantTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u8>()
            + self.size_of_prim::<u8>()
            + HasConstantToken::token_size(self.coded_tokens_sizes).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<ConstantTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ConstantTableRow> {
        Ok(ConstantTableRow {
            ty: self.read()?,
            padding: self.read()?,
            parent: self.read()?,
            value: self.read()?,
        })
    }
}

/// A row of the CustomAttribute table (ECMA-335 §II.22.10): a custom attribute
/// applied to something.
#[derive(Debug, Clone)]
pub struct CustomAttributeTableRow {
    /// What the attribute is applied to.
    pub parent: CodedToken<HasCustomAttributeToken>,
    /// The attribute's constructor.
    pub ty: CodedToken<CustomAttributeTypeToken>,
    /// Constructor and named arguments (§II.23.3) in #Blob.
    pub value: BlobStreamOffset,
}

impl<'a> CalculateTableSize<CustomAttributeTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        HasCustomAttributeToken::token_size(self.coded_tokens_sizes).byte_size()
            + CustomAttributeTypeToken::token_size(self.coded_tokens_sizes).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<CustomAttributeTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<CustomAttributeTableRow> {
        Ok(CustomAttributeTableRow {
            parent: self.read()?,
            ty: self.read()?,
            value: self.read()?,
        })
    }
}

/// A row of the FieldMarshal table (ECMA-335 §II.22.17): how a field or
/// parameter marshals to native code.
#[derive(Debug, Clone)]
pub struct FieldMarshalTableRow {
    /// The field or parameter.
    pub parent: CodedToken<HasFieldMarshalToken>,
    /// Marshalling descriptor (§II.23.4) in #Blob.
    pub native_type: BlobStreamOffset,
}

impl<'a> CalculateTableSize<FieldMarshalTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        HasFieldMarshalToken::token_size(self.coded_tokens_sizes).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<FieldMarshalTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FieldMarshalTableRow> {
        Ok(FieldMarshalTableRow {
            parent: self.read()?,
            native_type: self.read()?,
        })
    }
}

/// A row of the DeclSecurity table (ECMA-335 §II.22.11): a declarative security
/// permission set.
#[derive(Debug, Clone)]
pub struct DeclSecurityTableRow {
    /// Security action, e.g. `Demand` or `Assert`.
    pub action: u16,
    /// The type, method or assembly the permissions apply to.
    pub parent: CodedToken<HasDeclSecurityToken>,
    /// The permission set in #Blob.
    pub permission_set: BlobStreamOffset,
}

impl<'a> CalculateTableSize<DeclSecurityTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u16>()
            + HasDeclSecurityToken::token_size(self.coded_tokens_sizes).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<DeclSecurityTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<DeclSecurityTableRow> {
        Ok(DeclSecurityTableRow {
            action: self.read()?,
            parent: self.read()?,
            permission_set: self.read()?,
        })
    }
}

/// A row of the ClassLayout table (ECMA-335 §II.22.8): explicit packing and size
/// of a type.
#[derive(Debug, Clone)]
pub struct ClassLayoutTableRow {
    /// Field alignment in bytes (`Pack`); 0 for the default.
    pub packing_size: u16,
    /// Size of the type in bytes (`Size`); 0 for the default.
    pub class_size: u32,
    /// The type this layout applies to.
    pub parent: TypeDefTableOffset,
}

impl<'a> CalculateTableSize<ClassLayoutTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u16>()
            + self.size_of_prim::<u32>()
            + TypeDefTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<ClassLayoutTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ClassLayoutTableRow> {
        Ok(ClassLayoutTableRow {
            packing_size: self.read()?,
            class_size: self.read()?,
            parent: self.read()?,
        })
    }
}

/// A row of the FieldLayout table (ECMA-335 §II.22.16): a field's offset in an
/// explicit layout type.
#[derive(Debug, Clone)]
pub struct FieldLayoutTableRow {
    /// Byte offset of the field within its type.
    pub offset: u32,
    /// The field.
    pub field: FieldTableOffset,
}

impl<'a> CalculateTableSize<FieldLayoutTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>() + FieldTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<FieldLayoutTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FieldLayoutTableRow> {
        Ok(FieldLayoutTableRow {
            offset: self.read()?,
            field: self.read()?,
        })
    }
}

/// A row of the StandAloneSig table (ECMA-335 §II.22.36): a signature that isn't
/// a member's, such as a method body's locals or a `calli` call site.
#[derive(Debug, Clone)]
pub struct StandAloneSigTableRow {
    /// The signature in #Blob.
    pub signature: BlobStreamOffset,
}

impl<'a> CalculateTableSize<StandAloneSigTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<StandAloneSigTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<StandAloneSigTableRow> {
        Ok(StandAloneSigTableRow {
            signature: self.read()?,
        })
    }
}

/// A row of the EventMap table (ECMA-335 §II.22.12): the run of events a type
/// owns.
#[derive(Debug, Clone)]
pub struct EventMapTableRow {
    /// The owning type.
    pub parent: TypeDefTableOffset,
    /// First of the type's events. They run up to the next row's
    /// `event_list`.
    pub event_list: EventTableOffset,
}

impl<'a> CalculateTableSize<EventMapTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        TypeDefTableOffset::table_offset_size(self.rows).byte_size()
            + EventTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<EventMapTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<EventMapTableRow> {
        Ok(EventMapTableRow {
            parent: self.read()?,
            event_list: self.read()?,
        })
    }
}

/// A row of the EventPtr table: an indirection that unoptimized (`#-`)
/// metadata uses to list Events out of order. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct EventPtrTableRow {
    /// The Event row this slot stands for.
    pub event: EventTableOffset,
}

impl<'a> CalculateTableSize<EventPtrTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        EventTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<EventPtrTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<EventPtrTableRow> {
        Ok(EventPtrTableRow {
            event: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of an Event row (ECMA-335 §II.23.1.4).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct EventFlags: u16 {
        /// The name has a special meaning, described by the name.
        const SpecialName = 0x0200;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0x0400;
        /// The runtime checks the name's encoding.
        const RTSpecialName = 0x0400;
    }
}

/// A row of the Event table (ECMA-335 §II.22.13): an event. Its accessors are
/// found through the MethodSemantics table.
#[derive(Debug, Clone)]
pub struct EventTableRow {
    /// Special name flags.
    pub event_flags: EventFlags,
    /// Event name in #Strings.
    pub name: StringsStreamOffset,
    /// The event's delegate type.
    pub event_type: CodedToken<TypeDefOrRefToken>,
}

impl<'a> CalculateTableSize<EventTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<EventFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + TypeDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<EventTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<EventTableRow> {
        Ok(EventTableRow {
            event_flags: EventFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            event_type: self.read()?,
        })
    }
}

/// A row of the PropertyMap table (ECMA-335 §II.22.35): the run of properties a
/// type owns.
#[derive(Debug, Clone)]
pub struct PropertyMapTableRow {
    /// The owning type.
    pub parent: TypeDefTableOffset,
    /// First of the type's properties. They run up to the next row's
    /// `property_list`.
    pub property_list: PropertyTableOffset,
}

impl<'a> CalculateTableSize<PropertyMapTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        TypeDefTableOffset::table_offset_size(self.rows).byte_size()
            + PropertyTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<PropertyMapTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<PropertyMapTableRow> {
        Ok(PropertyMapTableRow {
            parent: self.read()?,
            property_list: self.read()?,
        })
    }
}

/// A row of the PropertyPtr table: an indirection that unoptimized (`#-`)
/// metadata uses to list Propertys out of order. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct PropertyPtrTableRow {
    /// The Property row this slot stands for.
    pub property: PropertyTableOffset,
}

impl<'a> CalculateTableSize<PropertyPtrTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        PropertyTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<PropertyPtrTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<PropertyPtrTableRow> {
        Ok(PropertyPtrTableRow {
            property: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a Property row (ECMA-335 §II.23.1.14).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct PropertyFlags: u16 {
        /// The name has a special meaning, described by the name.
        const SpecialName = 0x0200;

        /// Mask for the flags reserved for the runtime.
        const ReservedMask = 0xf400;
        /// The runtime checks the name's encoding.
        const RTSpecialName = 0x0400;
        /// Has a default value (Constant table).
        const HasDefault = 0x1000;

        /// Bits ECMA-335 leaves unused.
        const Unused = 0xe9ff;
    }
}

/// A row of the Property table (ECMA-335 §II.22.34): a property. Its accessors
/// are found through the MethodSemantics table.
#[derive(Debug, Clone)]
pub struct PropertyTableRow {
    /// Special name flags, and whether it has a default value.
    pub prop_flags: PropertyFlags,
    /// Property name in #Strings.
    pub name: StringsStreamOffset,
    /// Property signature (§II.23.2.5) in #Blob: its type and index
    /// parameters.
    pub ty: BlobStreamOffset,
}

impl<'a> CalculateTableSize<PropertyTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<PropertyFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<PropertyTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<PropertyTableRow> {
        Ok(PropertyTableRow {
            prop_flags: PropertyFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            ty: self.read()?,
        })
    }
}

bitflags! {
    /// The role of a method in a MethodSemantics row (ECMA-335 §II.23.1.12).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct MethodSemanticsFlags: u16 {
        /// The property's setter.
        const Setter = 0x0001;
        /// The property's getter.
        const Getter = 0x0002;
        /// Another method of the property or event.
        const Other = 0x0004;
        /// The event's `add` method.
        const AddOn = 0x0008;
        /// The event's `remove` method.
        const RemoveOn = 0x0010;
        /// The event's `raise` method.
        const Fire = 0x0020;
    }
}

/// A row of the MethodSemantics table (ECMA-335 §II.22.28): ties a method to a
/// property or event as its getter, setter, `add`, `remove`, ...
#[derive(Debug, Clone)]
pub struct MethodSemanticsTableRow {
    /// The method's role.
    pub semantic: MethodSemanticsFlags,
    /// The accessor method.
    pub method: MethodTableOffset,
    /// The property or event.
    pub association: CodedToken<HasSemanticToken>,
}

impl<'a> CalculateTableSize<MethodSemanticsTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<MethodSemanticsFlags>()
            + MethodTableOffset::table_offset_size(self.rows).byte_size()
            + HasSemanticToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<MethodSemanticsTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodSemanticsTableRow> {
        Ok(MethodSemanticsTableRow {
            semantic: MethodSemanticsFlags::from_bits_retain(self.read()?),
            method: self.read()?,
            association: self.read()?,
        })
    }
}

/// A row of the MethodImpl table (ECMA-335 §II.22.27): an explicit override,
/// such as an explicit interface implementation.
#[derive(Debug, Clone)]
pub struct MethodImplTableRow {
    /// The type the override is in.
    pub class: TypeDefTableOffset,
    /// The implementing method.
    pub method_body: CodedToken<MethodDefOrRefToken>,
    /// The method being overridden or implemented.
    pub method_declaration: CodedToken<MethodDefOrRefToken>,
}

impl<'a> CalculateTableSize<MethodImplTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        TypeDefTableOffset::table_offset_size(self.rows).byte_size()
            + MethodDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
            + MethodDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<MethodImplTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodImplTableRow> {
        Ok(MethodImplTableRow {
            class: self.read()?,
            method_body: self.read()?,
            method_declaration: self.read()?,
        })
    }
}

/// A row of the ModuleRef table (ECMA-335 §II.22.31): another module, either a
/// native library for P/Invoke or a module of this assembly.
#[derive(Debug, Clone)]
pub struct ModuleRefTableRow {
    /// Module or library name in #Strings.
    pub name: StringsStreamOffset,
}

impl<'a> CalculateTableSize<ModuleRefTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        StringsStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<ModuleRefTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ModuleRefTableRow> {
        Ok(ModuleRefTableRow { name: self.read()? })
    }
}

/// A row of the TypeSpec table (ECMA-335 §II.22.39): a constructed type, such as
/// a generic instance, array or pointer, where a token is needed.
#[derive(Debug, Clone)]
pub struct TypeSpecTableRow {
    /// Type signature (§II.23.2.14) in #Blob.
    pub signature: BlobStreamOffsetTypeSpec,
}

impl<'a> CalculateTableSize<TypeSpecTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        BlobStreamOffsetTypeSpec::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<TypeSpecTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<TypeSpecTableRow> {
        Ok(TypeSpecTableRow {
            signature: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of an ImplMap row (ECMA-335 §II.23.1.8): how a P/Invoke call finds
    /// its native function and marshals strings.
    ///
    /// The masked groups are values, not bits: compare
    /// `flags & PInvokeMapFlags::CharSetMask` against one.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct PInvokeMapFlags: u16 {
        /// Use the name exactly as given; don't try `A`/`W` suffixed names.
        const NoMangle = 0x0001;

        /// Mask for the character set values.
        const CharSetMask = 0x0006;
        /// Character set not specified.
        const CharSetNotSpec = 0x0000;
        /// Strings marshal as ANSI.
        const CharSetAnsi = 0x0002;
        /// Strings marshal as UTF-16.
        const CharSetUnicode = 0x0004;
        /// The platform picks the character set.
        const CharSetAuto = 0x0006;

        /// Best-fit mapping as the assembly specifies.
        const BestFitUseAssem = 0x0000;
        /// Map unmappable characters to close matches.
        const BestFitEnabled = 0x0010;
        /// Don't map unmappable characters to close matches.
        const BestFitDisabled = 0x0020;
        /// Mask for the best-fit values.
        const BestFitMask = 0x0030;

        /// Throw on unmappable characters as the assembly specifies.
        const ThrowOnUnmappableCharUseAssem = 0x0000;
        /// Throw on unmappable characters.
        const ThrowOnUnmappableCharEnabled = 0x1000;
        /// Don't throw on unmappable characters.
        const ThrowOnUnmappableCharDisabled = 0x2000;
        /// Mask for the throw-on-unmappable values.
        const ThrowOnUnmappableCharMask = 0x3000;

        /// The native function sets the last error (`SetLastError = true`).
        const SupportsLastError = 0x0040;

        /// Mask for the calling convention values.
        const CallConvMask = 0x0700;
        /// The platform's default calling convention.
        const CallConvWinapi = 0x0100;
        /// `cdecl`.
        const CallConvCdecl = 0x0200;
        /// `stdcall`.
        const CallConvStdcall = 0x0300;
        /// `thiscall`.
        const CallConvThiscall = 0x0400;
        /// `fastcall`.
        const CallConvFastcall = 0x0500;

        /// Range check value, not a flag.
        const MaxValue = 0xFFFF;
    }
}

/// A row of the ImplMap table (ECMA-335 §II.22.22): the native function a
/// P/Invoke method calls.
#[derive(Debug, Clone)]
pub struct ImplMapTableRow {
    /// Character set, calling convention and error handling.
    pub mapping_flags: PInvokeMapFlags,
    /// The P/Invoke method.
    pub member_forwarded: CodedToken<MemberForwardedToken>,
    /// Name of the native function in #Strings.
    pub import_name: StringsStreamOffset,
    /// The native library.
    pub import_scope: ModuleRefTableOffset,
}

impl<'a> CalculateTableSize<ImplMapTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<PInvokeMapFlags>()
            + MemberForwardedToken::token_size(self.coded_tokens_sizes).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + ModuleRefTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<ImplMapTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ImplMapTableRow> {
        Ok(ImplMapTableRow {
            mapping_flags: PInvokeMapFlags::from_bits_retain(self.read()?),
            member_forwarded: self.read()?,
            import_name: self.read()?,
            import_scope: self.read()?,
        })
    }
}

/// A row of the FieldRVA table (ECMA-335 §II.22.18): a field's initial data in
/// the image, e.g. the bytes behind an array initializer.
#[derive(Debug, Clone)]
pub struct FieldRVATableRow {
    /// RVA of the data.
    pub rva: u32,
    /// The field.
    pub field: FieldTableOffset,
}

impl<'a> CalculateTableSize<FieldRVATableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>() + FieldTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<FieldRVATableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FieldRVATableRow> {
        Ok(FieldRVATableRow {
            rva: self.read()?,
            field: self.read()?,
        })
    }
}

/// A row of the ENCLog table: an Edit and Continue log entry. Not in ECMA-335.
#[derive(Debug, Clone)]
pub struct ENCLogTableRow {
    /// Token of the changed row.
    pub token: u32,
    /// What was done to it.
    pub func_code: u32,
}

impl<'a> CalculateTableSize<ENCLogTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>() + self.size_of_prim::<u32>()
    }
}

impl<'a> ReadData<ENCLogTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ENCLogTableRow> {
        Ok(ENCLogTableRow {
            token: self.read()?,
            func_code: self.read()?,
        })
    }
}

/// A row of the ENCMap table: an Edit and Continue token map entry. Not in
/// ECMA-335.
#[derive(Debug, Clone)]
pub struct ENCMapTableRow {
    /// Token of a row in this delta.
    pub token: u32,
}

impl<'a> CalculateTableSize<ENCMapTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
    }
}

impl<'a> ReadData<ENCMapTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ENCMapTableRow> {
        Ok(ENCMapTableRow {
            token: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of an Assembly or AssemblyRef row (ECMA-335 §II.23.1.2).
    ///
    /// The processor architecture (`PA_*`) is a value under `PA_Mask`, not bits.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct AssemblyFlags: u32 {
        /// The row holds the full public key, not its token.
        const PublicKey = 0x0001;

        /// Processor architecture not specified.
        const PA_None = 0x0000;
        /// Processor neutral (AnyCPU).
        const PA_MSIL = 0x0010;
        /// x86.
        const PA_x86 = 0x0020;
        /// Itanium.
        const PA_IA64 = 0x0030;
        /// x64.
        const PA_AMD64 = 0x0040;
        /// The architecture bits are set and carry over to AssemblyRef rows.
        const PA_Specified = 0x0080;
        /// Mask for the processor architecture value.
        const PA_Mask = 0x0070;
        /// Mask for the processor architecture value plus `PA_Specified`.
        const PA_FullMask = 0x00F0;
        /// Not a flag: shift from the architecture bits to an index.
        const PA_Shift = 0x0004;

        /// JIT tracking on (from `DebuggableAttribute`).
        const EnableJITcompileTracking = 0x8000;
        /// JIT optimizations off (from `DebuggableAttribute`).
        const DisableJITcompileOptimizer = 0x4000;

        /// Can be retargeted at runtime to an assembly from another publisher.
        const Retargetable = 0x0100;
    }
}

/// A row of the Assembly table (ECMA-335 §II.22.2): this assembly's name,
/// version and key. A netmodule has none.
#[derive(Debug, Clone)]
pub struct AssemblyTableRow {
    /// Hash algorithm of the File table hashes, e.g. `0x8004` for SHA-1.
    pub hash_alg_id: u32,
    /// First part of the version.
    pub major_version: u16,
    /// Second part of the version.
    pub minor_version: u16,
    /// Third part of the version.
    pub build_number: u16,
    /// Fourth part of the version.
    pub revision_number: u16,
    /// Public key, retargetable and processor architecture.
    pub flags: AssemblyFlags,
    /// Full public key in #Blob; 0 if the assembly isn't signed.
    pub public_key: BlobStreamOffset,
    /// Assembly name, without extension, in #Strings.
    pub name: StringsStreamOffset,
    /// Culture, e.g. `en-US`, in #Strings; empty for neutral.
    pub locale: StringsStreamOffset,
}

impl<'a> CalculateTableSize<AssemblyTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<AssemblyFlags>()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<AssemblyTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyTableRow> {
        if self.header.table_locations.assembly.rows != 1 {
            return Err(crate::error::HaoError::BadImageFormat(
                "Assembly table should have exactly one entry",
            ));
        }

        Ok(AssemblyTableRow {
            hash_alg_id: self.read()?,
            major_version: self.read()?,
            minor_version: self.read()?,
            build_number: self.read()?,
            revision_number: self.read()?,
            flags: AssemblyFlags::from_bits_retain(self.read()?),
            public_key: self.read()?,
            name: self.read()?,
            locale: self.read()?,
        })
    }
}

/// A row of the AssemblyProcessor table (ECMA-335 §II.22.4). Unused: the
/// runtime ignores it.
#[derive(Debug, Clone)]
pub struct AssemblyProcessorTableRow {
    /// Processor id.
    pub processor: u32,
}

impl<'a> CalculateTableSize<AssemblyProcessorTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
    }
}

impl<'a> ReadData<AssemblyProcessorTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyProcessorTableRow> {
        Ok(AssemblyProcessorTableRow {
            processor: self.read()?,
        })
    }
}

/// A row of the AssemblyOS table (ECMA-335 §II.22.3). Unused: the runtime
/// ignores it.
#[derive(Debug, Clone)]
pub struct AssemblyOSTableRow {
    /// Target OS platform id.
    pub os_platform_id: u32,
    /// Target OS major version.
    pub os_major_version: u32,
    /// Target OS minor version.
    pub os_minor_version: u32,
}

impl<'a> CalculateTableSize<AssemblyOSTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>() + self.size_of_prim::<u32>() + self.size_of_prim::<u32>()
    }
}

impl<'a> ReadData<AssemblyOSTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyOSTableRow> {
        Ok(AssemblyOSTableRow {
            os_platform_id: self.read()?,
            os_major_version: self.read()?,
            os_minor_version: self.read()?,
        })
    }
}

/// A row of the AssemblyRef table (ECMA-335 §II.22.5): an assembly this module
/// references.
#[derive(Debug, Clone)]
pub struct AssemblyRefTableRow {
    /// First part of the version.
    pub major_version: u16,
    /// Second part of the version.
    pub minor_version: u16,
    /// Third part of the version.
    pub build_number: u16,
    /// Fourth part of the version.
    pub revision_number: u16,
    /// `PublicKey` says whether `public_key_or_token` is a full key.
    pub flags: AssemblyFlags,
    /// Public key or its 8-byte token in #Blob; 0 if unsigned.
    pub public_key_or_token: BlobStreamOffset,
    /// Assembly name, without extension, in #Strings.
    pub name: StringsStreamOffset,
    /// Culture, e.g. `en-US`, in #Strings; empty for neutral.
    pub locale: StringsStreamOffset,
    /// Hash of the referenced assembly in #Blob; usually 0.
    pub hash_value: BlobStreamOffset,
}

impl<'a> CalculateTableSize<AssemblyRefTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<u16>()
            + self.size_of_prim::<AssemblyFlags>()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<AssemblyRefTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyRefTableRow> {
        Ok(AssemblyRefTableRow {
            major_version: self.read()?,
            minor_version: self.read()?,
            build_number: self.read()?,
            revision_number: self.read()?,
            flags: AssemblyFlags::from_bits_retain(self.read()?),
            public_key_or_token: self.read()?,
            name: self.read()?,
            locale: self.read()?,
            hash_value: self.read()?,
        })
    }
}

/// A row of the AssemblyRefProcessor table (ECMA-335 §II.22.7). Unused: the
/// runtime ignores it.
#[derive(Debug, Clone)]
pub struct AssemblyRefProcessorTableRow {
    /// Processor id.
    pub processor: u32,
    /// The reference this applies to.
    pub assembly_ref: AssemblyRefTableOffset,
}

impl<'a> CalculateTableSize<AssemblyRefProcessorTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
            + AssemblyRefTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<AssemblyRefProcessorTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyRefProcessorTableRow> {
        Ok(AssemblyRefProcessorTableRow {
            processor: self.read()?,
            assembly_ref: self.read()?,
        })
    }
}

/// A row of the AssemblyRefOS table (ECMA-335 §II.22.6). Unused: the runtime
/// ignores it.
#[derive(Debug, Clone)]
pub struct AssemblyRefOSTableRow {
    /// Target OS platform id.
    pub os_platform_id: u32,
    /// Target OS major version.
    pub os_major_version: u32,
    /// Target OS minor version.
    pub os_minor_version: u32,
    /// The reference this applies to.
    pub assembly_ref: AssemblyRefTableOffset,
}

impl<'a> CalculateTableSize<AssemblyRefOSTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
            + self.size_of_prim::<u32>()
            + self.size_of_prim::<u32>()
            + AssemblyRefTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<AssemblyRefOSTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<AssemblyRefOSTableRow> {
        Ok(AssemblyRefOSTableRow {
            os_platform_id: self.read()?,
            os_major_version: self.read()?,
            os_minor_version: self.read()?,
            assembly_ref: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a File row (ECMA-335 §II.23.1.6).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct FileFlags: u32 {
        /// Has metadata (a module). This is 0, so test for `ContainsNoMetaData`
        /// instead.
        const ContainsMetaData = 0x0000;
        /// Has no metadata: a resource or other file.
        const ContainsNoMetaData = 0x0001;
    }
}

/// A row of the File table (ECMA-335 §II.22.19): another file of a multi-file
/// assembly.
#[derive(Debug, Clone)]
pub struct FileTableRow {
    /// Whether the file has metadata.
    pub flags: FileFlags,
    /// File name in #Strings.
    pub name: StringsStreamOffset,
    /// Hash of the file's contents in #Blob.
    pub hash_value: BlobStreamOffset,
}

impl<'a> CalculateTableSize<FileTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<FileFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<FileTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<FileTableRow> {
        Ok(FileTableRow {
            flags: FileFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            hash_value: self.read()?,
        })
    }
}

/// A row of the ExportedType table (ECMA-335 §II.22.14): a type this assembly
/// exposes from elsewhere, such as a type forwarder or a type in another module.
#[derive(Debug, Clone)]
pub struct ExportedTypeTableRow {
    /// Visibility; `Forwarder` for a type forwarder.
    pub flags: TypeAttributes,
    /// Hint: the type's TypeDef row in the other module. May be 0.
    pub type_def_id: u32,
    /// Type name in #Strings.
    pub type_name: StringsStreamOffset,
    /// Namespace in #Strings.
    pub type_namespace: StringsStreamOffset,
    /// Where the type is: a File, an AssemblyRef (for a forwarder), or
    /// for a nested type the enclosing ExportedType.
    pub implementation: CodedToken<ImplementationToken>,
}

impl<'a> CalculateTableSize<ExportedTypeTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<TypeAttributes>()
            + self.size_of_prim::<u32>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + ImplementationToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<ExportedTypeTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ExportedTypeTableRow> {
        Ok(ExportedTypeTableRow {
            flags: TypeAttributes::from_bits_retain(self.read()?),
            type_def_id: self.read()?,
            type_name: self.read()?,
            type_namespace: self.read()?,
            implementation: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a ManifestResource row (ECMA-335 §II.23.1.9).
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct ManifestResourceFlags: u32 {
        /// Mask for the visibility values.
        const VisibilityMask = 0x0007;
        /// Exported from the assembly.
        const Public = 0x0001;
        /// Private to the assembly.
        const Private = 0x0002;
    }
}

/// A row of the ManifestResource table (ECMA-335 §II.22.24): a resource,
/// embedded in this image or in another file or assembly.
#[derive(Debug, Clone)]
pub struct ManifestResourceTableRow {
    /// Byte offset of the data: in the image's resources directory when
    /// embedded, otherwise in the file.
    pub offset: u32,
    /// Public or private.
    pub flags: ManifestResourceFlags,
    /// Resource name in #Strings.
    pub name: StringsStreamOffset,
    /// Where the data is: null (row 0) for this image, otherwise a File
    /// or an AssemblyRef.
    pub implementation: CodedToken<ImplementationToken>,
}

impl<'a> CalculateTableSize<ManifestResourceTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u32>()
            + self.size_of_prim::<ManifestResourceFlags>()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + ImplementationToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<ManifestResourceTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ManifestResourceTableRow> {
        Ok(ManifestResourceTableRow {
            offset: self.read()?,
            flags: ManifestResourceFlags::from_bits_retain(self.read()?),
            name: self.read()?,
            implementation: self.read()?,
        })
    }
}

/// A row of the NestedClass table (ECMA-335 §II.22.32): which type a nested type
/// is declared in.
#[derive(Debug, Clone)]
pub struct NestedClassTableRow {
    /// The nested type.
    pub nested_class: TypeDefTableOffset,
    /// The type it is declared in.
    pub enclosing_class: TypeDefTableOffset,
}

impl<'a> CalculateTableSize<NestedClassTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        TypeDefTableOffset::table_offset_size(self.rows).byte_size()
            + TypeDefTableOffset::table_offset_size(self.rows).byte_size()
    }
}

impl<'a> ReadData<NestedClassTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<NestedClassTableRow> {
        Ok(NestedClassTableRow {
            nested_class: self.read()?,
            enclosing_class: self.read()?,
        })
    }
}

bitflags! {
    /// Flags of a GenericParam row (ECMA-335 §II.23.1.7): variance and special
    /// constraints.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
    #[cfg_attr(feature = "reflect", derive(facet::Facet), facet(opaque))]
    pub struct GenericParamFlags: u16 {
        /// Mask for the variance values. Only interface and delegate parameters vary.
        const VarianceMask = 0x0003;
        /// Invariant.
        const NonVariant = 0x0000;
        /// Covariant (`out T`).
        const Covariant = 0x0001;
        /// Contravariant (`in T`).
        const Contravariant = 0x0002;

        /// Mask for the special constraints.
        const SpecialConstraintMask = 0x001C;
        /// No special constraint.
        const NoSpecialConstraint = 0x0000;
        /// Must be a reference type (`where T : class`).
        const ReferenceTypeConstraint = 0x0004;
        /// Must be a non-nullable value type (`where T : struct`).
        const NotNullableValueTypeConstraint = 0x0008;
        /// Must have a public parameterless constructor (`where T : new()`).
        const DefaultConstructorConstraint = 0x0010;
    }
}

/// A row of the GenericParam table (ECMA-335 §II.22.20): a generic parameter of
/// a type or method.
#[derive(Debug, Clone)]
pub struct GenericParamTableRow {
    /// Position in the owner's parameter list, from 0.
    pub number: u16,
    /// Variance and special constraints.
    pub flags: GenericParamFlags,
    /// The generic type or method.
    pub owner: CodedToken<TypeOrMethodDefToken>,
    /// Parameter name, e.g. `T`, in #Strings.
    pub name: StringsStreamOffset,
    /// An extra column only in version 1.1 tables streams; `None` otherwise.
    pub kind: Option<CodedToken<TypeDefOrRefToken>>,
}

impl<'a> CalculateTableSize<GenericParamTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        self.size_of_prim::<u16>()
            + self.size_of_prim::<GenericParamFlags>()
            + TypeOrMethodDefToken::token_size(self.coded_tokens_sizes).byte_size()
            + StringsStreamOffset::streams_offset_size(self.flags).byte_size()
            + if self.version == Version(1, 1) {
                TypeDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
            } else {
                0
            }
    }
}

impl<'a> ReadData<GenericParamTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<GenericParamTableRow> {
        Ok(GenericParamTableRow {
            number: self.read()?,
            flags: GenericParamFlags::from_bits_retain(self.read()?),
            owner: self.read()?,
            name: self.read()?,
            kind: (self.header.version == Version(1, 1))
                .then(|| self.read())
                .transpose()?,
        })
    }
}

/// A row of the MethodSpec table (ECMA-335 §II.22.29): a generic method
/// instance, e.g. `M<int>`.
#[derive(Debug, Clone)]
pub struct MethodSpecTableRow {
    /// The generic method.
    pub method: CodedToken<MethodDefOrRefToken>,
    /// Type arguments (§II.23.2.15) in #Blob.
    pub instantiation: BlobStreamOffset,
}

impl<'a> CalculateTableSize<MethodSpecTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        MethodDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<MethodSpecTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodSpecTableRow> {
        Ok(MethodSpecTableRow {
            method: self.read()?,
            instantiation: self.read()?,
        })
    }
}

/// A row of the GenericParamConstraint table (ECMA-335 §II.22.21): a type a
/// generic parameter must derive from or implement.
#[derive(Debug, Clone)]
pub struct GenericParamConstraintTableRow {
    /// The constrained generic parameter.
    pub owner: GenericParamTableOffset,
    /// The required base type or interface.
    pub constraint: CodedToken<TypeDefOrRefToken>,
}

impl<'a> CalculateTableSize<GenericParamConstraintTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        GenericParamTableOffset::table_offset_size(self.rows).byte_size()
            + TypeDefOrRefToken::token_size(self.coded_tokens_sizes).byte_size()
    }
}

impl<'a> ReadData<GenericParamConstraintTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<GenericParamConstraintTableRow> {
        Ok(GenericParamConstraintTableRow {
            owner: self.read()?,
            constraint: self.read()?,
        })
    }
}

/// A row of the Portable PDB Document table: a source file.
#[derive(Debug, Clone)]
pub struct DocumentTableRow {
    /// Path of the file, as a document name blob, in #Blob.
    pub name: BlobStreamOffset,
    /// Hash algorithm of `hash` in #GUID.
    pub hash_algorithm: GuidStreamOffset,
    /// Hash of the file's contents in #Blob.
    pub hash: BlobStreamOffset,
    /// Source language (e.g. C#) in #GUID.
    pub language: GuidStreamOffset,
}

impl<'a> CalculateTableSize<DocumentTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        BlobStreamOffset::streams_offset_size(self.flags).byte_size()
            + GuidStreamOffset::streams_offset_size(self.flags).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
            + GuidStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<DocumentTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<DocumentTableRow> {
        Ok(DocumentTableRow {
            name: self.read()?,
            hash_algorithm: self.read()?,
            hash: self.read()?,
            language: self.read()?,
        })
    }
}

/// A row of the Portable PDB MethodDebugInformation table: the sequence points
/// of the MethodDef with the same row number.
#[derive(Debug, Clone)]
pub struct MethodDebugInformationTableRow {
    /// The source file; 0 when the points span several files.
    pub document: DocumentTableRowOffset,
    /// Sequence points in #Blob; 0 if there are none.
    pub sequence_points: BlobStreamOffset,
}

impl<'a> CalculateTableSize<MethodDebugInformationTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        DocumentTableRowOffset::table_offset_size(self.rows).byte_size()
            + BlobStreamOffset::streams_offset_size(self.flags).byte_size()
    }
}

impl<'a> ReadData<MethodDebugInformationTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<MethodDebugInformationTableRow> {
        Ok(MethodDebugInformationTableRow {
            document: self.read()?,
            sequence_points: self.read()?,
        })
    }
}

/// A row of the Portable PDB LocalScope table: a range of a method body where
/// some locals and constants are in scope.
#[derive(Debug, Clone)]
pub struct LocalScopeTableRow {
    /// The method.
    pub method: MethodTableOffset,
    /// The namespace imports in effect.
    pub import_scope: ImportScopeTableOffset,
    /// First of the scope's local variables.
    pub variable_list: LocalVariableTableOffset,
    /// First of the scope's local constants.
    pub constant_list: LocalConstantTableOffset,
    /// IL offset where the scope starts.
    pub start_offset: u32,
    /// Length of the scope in IL bytes.
    pub length: u32,
}

impl<'a> CalculateTableSize<LocalScopeTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        MethodTableOffset::table_offset_size(self.rows).byte_size()
            + ImportScopeTableOffset::table_offset_size(self.rows).byte_size()
            + LocalVariableTableOffset::table_offset_size(self.rows).byte_size()
            + LocalConstantTableOffset::table_offset_size(self.rows).byte_size()
            + self.size_of_prim::<u32>()
            + self.size_of_prim::<u32>()
    }
}

impl<'a> ReadData<LocalScopeTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<LocalScopeTableRow> {
        Ok(LocalScopeTableRow {
            method: self.read()?,
            import_scope: self.read()?,
            variable_list: self.read()?,
            constant_list: self.read()?,
            start_offset: self.read()?,
            length: self.read()?,
        })
    }
}

/// A row of the Portable PDB LocalVariable table: a local variable's name.
///
/// Not parsed yet: the columns are placeholders and the row takes no bytes.
#[derive(Debug, Clone)]
pub struct LocalVariableTableRow {
    /// Not read yet.
    pub attributes: (),
    /// Not read yet.
    pub index: (),
    /// Not read yet.
    pub name: (),
}

impl<'a> CalculateTableSize<LocalVariableTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        0
    }
}

impl<'a> ReadData<LocalVariableTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<LocalVariableTableRow> {
        Ok(LocalVariableTableRow {
            attributes: self.read()?,
            index: self.read()?,
            name: self.read()?,
        })
    }
}

/// A row of the Portable PDB LocalConstant table: a local constant's name and value.
///
/// Not parsed yet: the columns are placeholders and the row takes no bytes.
#[derive(Debug, Clone)]
pub struct LocalConstantTableRow {
    /// Not read yet.
    pub name: (),
    /// Not read yet.
    pub signature: (),
}

impl<'a> CalculateTableSize<LocalConstantTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        0
    }
}

impl<'a> ReadData<LocalConstantTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<LocalConstantTableRow> {
        Ok(LocalConstantTableRow {
            name: self.read()?,
            signature: self.read()?,
        })
    }
}

/// A row of the Portable PDB ImportScope table: a set of namespace imports.
///
/// Not parsed yet: the columns are placeholders and the row takes no bytes.
#[derive(Debug, Clone)]
pub struct ImportScopeTableRow {
    /// Not read yet.
    pub parent: (),
    /// Not read yet.
    pub imports: (),
}

impl<'a> CalculateTableSize<ImportScopeTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        0
    }
}

impl<'a> ReadData<ImportScopeTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<ImportScopeTableRow> {
        Ok(ImportScopeTableRow {
            parent: self.read()?,
            imports: self.read()?,
        })
    }
}

/// A row of the Portable PDB StateMachineMethod table: ties an async or iterator `MoveNext` to the
/// method that starts it.
///
/// Not parsed yet: the columns are placeholders and the row takes no bytes.
#[derive(Debug, Clone)]
pub struct StateMachineMethodTableRow {
    /// Not read yet.
    pub move_next_method: (),
    /// Not read yet.
    pub kickoff_method: (),
}

impl<'a> CalculateTableSize<StateMachineMethodTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        0
    }
}

impl<'a> ReadData<StateMachineMethodTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<StateMachineMethodTableRow> {
        Ok(StateMachineMethodTableRow {
            move_next_method: self.read()?,
            kickoff_method: self.read()?,
        })
    }
}

/// A row of the Portable PDB CustomDebugInformation table: extra debug data attached to
/// anything.
///
/// Not parsed yet: the columns are placeholders and the row takes no bytes.
#[derive(Debug, Clone)]
pub struct CustomDebugInformationTableRow {
    /// Not read yet.
    pub parent: (),
    /// Not read yet.
    pub kind: (),
    /// Not read yet.
    pub value: (),
}

impl<'a> CalculateTableSize<CustomDebugInformationTableRow> for SizeCalculator<'a> {
    fn calculate_table_size_bytes(&self) -> usize {
        0
    }
}

impl<'a> ReadData<CustomDebugInformationTableRow> for TablesStreamReader<'a> {
    fn read(&mut self) -> Result<CustomDebugInformationTableRow> {
        Ok(CustomDebugInformationTableRow {
            parent: self.read()?,
            kind: self.read()?,
            value: self.read()?,
        })
    }
}