ristretto_classfile 0.31.0

A library for reading, writing and verifying Java classfiles.
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
use crate::Error::InvalidInstructionOffset;
use crate::attributes::bootstrap_method::BootstrapMethod;
use crate::attributes::inner_class::InnerClass;
use crate::attributes::line_number::LineNumber;
use crate::attributes::offset_utils::{self, lookup_byte_offset, lookup_byte_offset_le};
use crate::attributes::parameter_annotation::ParameterAnnotation;
use crate::attributes::{
    Annotation, AnnotationElement, ExceptionTableEntry, Exports, Instruction, LocalVariableTable,
    LocalVariableTypeTable, MethodParameter, ModuleAccessFlags, Opens, Provides, Record, Requires,
    StackFrame, TypeAnnotation,
};
use crate::byte_reader::ByteReader;
use crate::constant::Constant;
use crate::constant_pool::ConstantPool;
use crate::display::indent_lines;
use crate::error::Error::{InvalidAttributeLength, InvalidAttributeNameIndex};
use crate::error::Result;
use crate::version::Version;
use crate::{JAVA_5, JAVA_6, JAVA_7, JAVA_8, JAVA_9, JAVA_11, JAVA_16, JAVA_17, mutf8};
use ahash::AHashMap;
use byteorder::{BigEndian, WriteBytesExt};
use std::fmt;

const VERSION_45_3: Version = Version::Java1_0_2 { minor: 3 };
const VERSION_49_0: Version = JAVA_5;
const VERSION_50_0: Version = JAVA_6;
const VERSION_51_0: Version = JAVA_7;
const VERSION_52_0: Version = JAVA_8;
const VERSION_53_0: Version = JAVA_9;
const VERSION_55_0: Version = JAVA_11;
const VERSION_60_0: Version = JAVA_16;
const VERSION_61_0: Version = JAVA_17;

/// Represents a class file attribute as defined in the Java Virtual Machine Specification.
///
/// Attributes are used to provide additional information about class files, fields, methods, and code.
/// Each attribute has a name and specific data related to its purpose. The JVM specification defines
/// standard attributes, but custom attributes can also be created.
///
/// # Examples
///
/// Creating a `SourceFile` attribute:
///
/// ```
/// use ristretto_classfile::attributes::Attribute;
/// use ristretto_classfile::ConstantPool;
///
/// // Assuming we have a constant pool with a UTF8 entry for "SourceFile" at index 1
/// // and a UTF8 entry for the source file name at index 2
/// let source_file_attr = Attribute::SourceFile {
///     name_index: 1,
///     source_file_index: 2,
/// };
/// ```
///
/// Serializing an attribute to bytes:
///
/// ```
/// use ristretto_classfile::attributes::Attribute;
/// use ristretto_classfile::Result;
///
/// let source_file_attr = Attribute::SourceFile {
///     name_index: 1,
///     source_file_index: 2,
/// };
///
/// let mut bytes = Vec::new();
/// source_file_attr.to_bytes(&mut bytes)?;
/// # Ok::<(), ristretto_classfile::Error>(())
/// ```
///
/// # References
///
/// - [JVMS §4.7](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7)
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Attribute {
    /// Represents a constant value for a field.
    ///
    /// This attribute is used for fields that have a constant value. The `constant_value_index`
    /// points to the constant pool entry containing the value.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.2](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.2)
    ConstantValue {
        name_index: u16,
        constant_value_index: u16,
    },

    /// Contains the bytecode and auxiliary information for a method implementation.
    ///
    /// The Code attribute contains the instructions, exception handlers, and additional attributes
    /// needed to execute a method. It also specifies the maximum stack size and local variable
    /// count.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.3](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.3)
    Code {
        name_index: u16,
        max_stack: u16,
        max_locals: u16,
        code: Vec<Instruction>,
        exception_table: Vec<ExceptionTableEntry>,
        attributes: Vec<Attribute>,
    },

    /// Represents a stack map table for type checking during bytecode verification.
    ///
    /// The `StackMapTable` attribute is used by the Java Virtual Machine's bytecode verifier to
    /// type check code without requiring the loading of referenced classes. It contains information
    /// about the state of the operand stack and local variables at specific offsets in the code.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.4](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.4)
    StackMapTable {
        name_index: u16,
        frames: Vec<StackFrame>,
    },

    /// Lists the checked exceptions that a method may throw.
    ///
    /// The Exceptions attribute indicates which checked exceptions a method can throw. Each entry
    /// in the `exception_indexes` list points to a `CONSTANT_Class_info` structure representing a
    /// class type that this method is declared to throw.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.5](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.5)
    Exceptions {
        name_index: u16,
        exception_indexes: Vec<u16>,
    },

    /// Records the inner classes and interfaces of a class or interface.
    ///
    /// This attribute provides information about the inner classes and interfaces declared within a
    /// class. For each inner class or interface, it specifies the class name, enclosing class,
    /// inner name, and access flags.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.6](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.6)
    InnerClasses {
        name_index: u16,
        classes: Vec<InnerClass>,
    },

    /// Indicates that a class is a local or anonymous class.
    ///
    /// The `EnclosingMethod` attribute provides information about the enclosing context of a local
    /// or anonymous class. It identifies the class within which the local or anonymous class is
    /// declared, and may optionally specify the method within that class.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.7](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.7)
    EnclosingMethod {
        name_index: u16,
        class_index: u16,
        method_index: u16,
    },

    /// Indicates that a class, field, or method was generated by the compiler and does not appear
    /// in source code.
    ///
    /// The `Synthetic` attribute marks a class member that does not have a corresponding construct
    /// in the source code. It is used to denote members that were introduced by the compiler during
    /// compilation.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.8](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.8)
    Synthetic { name_index: u16 },

    /// Stores generic signature information for a class, field, or method.
    ///
    /// The Signature attribute records generic signature information for a class, interface,
    /// constructor, method, or field declaration when that signature includes type variables or
    /// parameterized types.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.9](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.9)
    Signature {
        name_index: u16,
        signature_index: u16,
    },

    /// Indicates the source file from which a class file was compiled.
    ///
    /// The `SourceFile` attribute points to a `CONSTANT_Utf8_info` structure in the constant pool
    /// that contains the name of the source file from which this class file was compiled.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.10](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.10)
    SourceFile {
        name_index: u16,
        source_file_index: u16,
    },

    /// Provides additional debugging information not included in the standard source file.
    ///
    /// The `SourceDebugExtension` attribute is an optional attribute that contains additional
    /// debugging information which tools can use to implement source-level debugging. The attribute
    /// typically stores information for non-Java source files.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.11](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.11)
    SourceDebugExtension {
        name_index: u16,
        debug_extension: String,
    },

    /// Maps bytecode instruction offsets to source code line numbers.
    ///
    /// The `LineNumberTable` attribute maps bytecode instruction offsets to line numbers in the
    /// original source file. This attribute is used by debuggers to determine which line of source
    /// is being executed and by exception handlers to display line numbers.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.12](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.12)
    LineNumberTable {
        name_index: u16,
        line_numbers: Vec<LineNumber>,
    },

    /// Maps ranges of bytecode to information about local variables.
    ///
    /// The `LocalVariableTable` attribute records information about the local variables in a
    /// method, allowing debuggers to determine the value of a given local variable during
    /// execution. Each entry maps a range of bytecode to a specific local variable.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.13](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.13)
    LocalVariableTable {
        name_index: u16,
        variables: Vec<LocalVariableTable>,
    },

    /// Provides type information for generic local variables.
    ///
    /// The `LocalVariableTypeTable` attribute records signature information for local variables in
    /// generic code, allowing debuggers to display and interact with generic types. It complements
    /// the `LocalVariableTable` by providing generic type information.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.14](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.14)
    LocalVariableTypeTable {
        name_index: u16,
        variable_types: Vec<LocalVariableTypeTable>,
    },

    /// Indicates that a class, field, or method is deprecated.
    ///
    /// The Deprecated attribute indicates that a class, interface, method, or field is deprecated
    /// and should no longer be used. It corresponds to the @Deprecated annotation in Java source
    /// code.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.15](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.15)
    Deprecated { name_index: u16 },

    /// Stores annotations that are visible at runtime.
    ///
    /// The `RuntimeVisibleAnnotations` attribute records the annotations on a program element that
    /// are visible to the reflection API at runtime. These correspond to annotations without a
    /// `RetentionPolicy.SOURCE` or `RetentionPolicy.CLASS`.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.16](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.16)
    RuntimeVisibleAnnotations {
        name_index: u16,
        annotations: Vec<Annotation>,
    },

    /// Stores annotations that are not visible at runtime.
    ///
    /// The `RuntimeInvisibleAnnotations` attribute records the annotations on a program element
    /// that are not visible to the reflection API at runtime. These correspond to annotations with
    /// `RetentionPolicy.CLASS`.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.17](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.17)
    RuntimeInvisibleAnnotations {
        name_index: u16,
        annotations: Vec<Annotation>,
    },

    /// Stores runtime-visible annotations on method parameters.
    ///
    /// The `RuntimeVisibleParameterAnnotations` attribute records annotations on method parameters
    /// that are visible to the reflection API at runtime. Each parameter can have multiple
    /// annotations.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.18](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.18)
    RuntimeVisibleParameterAnnotations {
        name_index: u16,
        parameter_annotations: Vec<ParameterAnnotation>,
    },

    /// Stores runtime-invisible annotations on method parameters.
    ///
    /// The `RuntimeInvisibleParameterAnnotations` attribute records annotations on method
    /// parameters that are not visible to the reflection API at runtime. These correspond to
    /// annotations with `RetentionPolicy.CLASS`.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.19](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.19)
    RuntimeInvisibleParameterAnnotations {
        name_index: u16,
        parameter_annotations: Vec<ParameterAnnotation>,
    },

    /// Stores runtime-visible type annotations.
    ///
    /// The `RuntimeVisibleTypeAnnotations` attribute records type annotations that are visible to
    /// the reflection API at runtime. Type annotations can target a wider range of program elements
    /// than traditional annotations, including type uses and type declarations.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.20](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.20)
    RuntimeVisibleTypeAnnotations {
        name_index: u16,
        type_annotations: Vec<TypeAnnotation>,
    },

    /// Stores runtime-invisible type annotations.
    ///
    /// The `RuntimeInvisibleTypeAnnotations` attribute records type annotations that are not
    /// visible to the reflection API at runtime. These correspond to type annotations with
    /// `RetentionPolicy.CLASS`.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.21](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.21)
    RuntimeInvisibleTypeAnnotations {
        name_index: u16,
        type_annotations: Vec<TypeAnnotation>,
    },

    /// Specifies the default value for an annotation type element.
    ///
    /// The `AnnotationDefault` attribute defines the default value for an element in an annotation
    /// type. It appears in methods of annotation interfaces that provide default values.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.22](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.22)
    AnnotationDefault {
        name_index: u16,
        element: AnnotationElement,
    },

    /// Stores bootstrap method references used by invokedynamic instructions.
    ///
    /// The `BootstrapMethods` attribute records bootstrap methods referenced by invokedynamic
    /// instructions. Each method entry contains a reference to the bootstrap method and its
    /// static arguments, which are used for dynamic method invocation.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.23](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.23)
    BootstrapMethods {
        name_index: u16,
        methods: Vec<BootstrapMethod>,
    },

    /// Provides information about method parameters, including names and access flags.
    ///
    /// The `MethodParameters` attribute records information about the formal parameters of a
    /// method, including names and access flags. This allows for reflection on method parameter
    /// names and modifiers (such as final or synthetic parameters).
    ///
    /// # References
    ///
    /// - [JVMS §4.7.24](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.24)
    MethodParameters {
        name_index: u16,
        parameters: Vec<MethodParameter>,
    },

    /// Defines a module, its dependencies, exports, and services.
    ///
    /// The Module attribute describes a module, including its name, requirements (dependencies),
    /// exports, opens, uses, and provides declarations. It appears in module-info class files
    /// and is part of the Java Platform Module System.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.25](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.25)
    Module {
        name_index: u16,
        module_name_index: u16,
        flags: ModuleAccessFlags,
        version_index: u16,
        requires: Vec<Requires>,
        exports: Vec<Exports>,
        opens: Vec<Opens>,
        uses: Vec<u16>,
        provides: Vec<Provides>,
    },

    /// Lists all packages exported or opened by a module.
    ///
    /// The `ModulePackages` attribute records all packages that are exported or opened by a module.
    /// This information is used by various tools and APIs that need to know the complete set of
    /// packages belonging to a module.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.26](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.26)
    ModulePackages {
        name_index: u16,
        package_indexes: Vec<u16>,
    },

    /// Specifies the main class of a module.
    ///
    /// The `ModuleMainClass` attribute indicates the main class of a module, which is the class
    /// containing the main method that should be executed when the module is run directly.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.27](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.27)
    ModuleMainClass {
        name_index: u16,
        main_class_index: u16,
    },

    /// Identifies the host class of a nested class.
    ///
    /// The `NestHost` attribute records the top-level class that serves as the nest host for a nest
    /// member class. This attribute helps implement the new nesting-based access control in Java,
    /// which allows nested classes to access each other's private members.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.28](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.28)
    NestHost {
        name_index: u16,
        host_class_index: u16,
    },

    /// Lists the member classes of a nest.
    ///
    /// The `NestMembers` attribute appears in the nest host class and records all the classes that
    /// are members of the nest. This attribute works with `NestHost` to implement nesting-based
    /// access control in Java.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.29](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.29)
    NestMembers {
        name_index: u16,
        class_indexes: Vec<u16>,
    },

    /// Describes the components of a record class.
    ///
    /// The Record attribute stores information about the components of a record class, including
    /// their names, descriptors, and attributes. This attribute is used to implement the record
    /// feature introduced in Java 16.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.30](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.30)
    Record {
        name_index: u16,
        records: Vec<Record>,
    },

    /// Lists the permitted direct subclasses of a sealed class.
    ///
    /// The `PermittedSubclasses` attribute records the classes that are permitted to extend a
    /// sealed class or implement a sealed interface. It is used to implement the sealed classes
    /// feature introduced in Java 17.
    ///
    /// # References
    ///
    /// - [JVMS §4.7.31](https://docs.oracle.com/javase/specs/jvms/se25/html/jvms-4.html#jvms-4.7.31)
    PermittedSubclasses {
        name_index: u16,
        class_indexes: Vec<u16>,
    },

    /// Used to support reading future classes where the structure is not known beforehand.
    ///
    /// This variant allows the parser to handle unknown attribute types gracefully by storing the
    /// raw bytes of the attribute.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::Attribute;
    ///
    /// let unknown_attr = Attribute::Unknown {
    ///     name_index: 1,  // Index in constant pool pointing to the attribute name
    ///     info: vec![0, 1, 2, 3],  // Raw attribute data
    /// };
    /// ```
    Unknown { name_index: u16, info: Vec<u8> },
}

impl Attribute {
    /// Returns the name of the Attribute as a static string.
    ///
    /// This method returns the standard name of the attribute type
    /// regardless of the actual name used in the class file.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::Attribute;
    ///
    /// let attr = Attribute::SourceFile {
    ///     name_index: 1,
    ///     source_file_index: 2,
    /// };
    ///
    /// assert_eq!(attr.name(), "SourceFile");
    /// ```
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Attribute::ConstantValue { .. } => "ConstantValue",
            Attribute::Code { .. } => "Code",
            Attribute::StackMapTable { .. } => "StackMapTable",
            Attribute::Exceptions { .. } => "Exceptions",
            Attribute::InnerClasses { .. } => "InnerClasses",
            Attribute::EnclosingMethod { .. } => "EnclosingMethod",
            Attribute::Synthetic { .. } => "Synthetic",
            Attribute::Signature { .. } => "Signature",
            Attribute::SourceFile { .. } => "SourceFile",
            Attribute::SourceDebugExtension { .. } => "SourceDebugExtension",
            Attribute::LineNumberTable { .. } => "LineNumberTable",
            Attribute::LocalVariableTable { .. } => "LocalVariableTable",
            Attribute::LocalVariableTypeTable { .. } => "LocalVariableTypeTable",
            Attribute::Deprecated { .. } => "Deprecated",
            Attribute::RuntimeVisibleAnnotations { .. } => "RuntimeVisibleAnnotations",
            Attribute::RuntimeInvisibleAnnotations { .. } => "RuntimeInvisibleAnnotations",
            Attribute::RuntimeVisibleParameterAnnotations { .. } => {
                "RuntimeVisibleParameterAnnotations"
            }
            Attribute::RuntimeInvisibleParameterAnnotations { .. } => {
                "RuntimeInvisibleParameterAnnotations"
            }
            Attribute::RuntimeVisibleTypeAnnotations { .. } => "RuntimeVisibleTypeAnnotations",
            Attribute::RuntimeInvisibleTypeAnnotations { .. } => "RuntimeInvisibleTypeAnnotations",
            Attribute::AnnotationDefault { .. } => "AnnotationDefault",
            Attribute::BootstrapMethods { .. } => "BootstrapMethods",
            Attribute::MethodParameters { .. } => "MethodParameters",
            Attribute::Module { .. } => "Module",
            Attribute::ModulePackages { .. } => "ModulePackages",
            Attribute::ModuleMainClass { .. } => "ModuleMainClass",
            Attribute::NestHost { .. } => "NestHost",
            Attribute::NestMembers { .. } => "NestMembers",
            Attribute::Record { .. } => "Record",
            Attribute::PermittedSubclasses { .. } => "PermittedSubclasses",
            Attribute::Unknown { .. } => "Unknown",
        }
    }

    /// Checks if the Attribute is valid for the given Java version.
    ///
    /// Each attribute type was introduced in a specific Java version. This method checks if the
    /// attribute is supported in the specified version.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::Attribute;
    /// use ristretto_classfile::{Version, JAVA_8};
    ///
    /// let attr = Attribute::SourceFile {
    ///     name_index: 1,
    ///     source_file_index: 2,
    /// };
    ///
    /// // SourceFile was introduced early and is supported in Java 8
    /// assert!(attr.valid_for_version(&JAVA_8));
    ///
    /// // NestMembers was introduced in Java 11 and wouldn't be valid in Java 8
    /// let nest_members = Attribute::NestMembers {
    ///     name_index: 1,
    ///     class_indexes: vec![2],
    /// };
    /// assert!(!nest_members.valid_for_version(&JAVA_8));
    /// ```
    #[expect(clippy::match_same_arms)]
    #[must_use]
    pub fn valid_for_version(&self, version: &Version) -> bool {
        match self {
            Attribute::ConstantValue { .. } => *version >= VERSION_45_3,
            Attribute::Code { .. } => *version >= VERSION_45_3,
            Attribute::StackMapTable { .. } => *version >= VERSION_50_0,
            Attribute::Exceptions { .. } => *version >= VERSION_45_3,
            Attribute::InnerClasses { .. } => *version >= VERSION_45_3,
            Attribute::EnclosingMethod { .. } => *version >= VERSION_49_0,
            Attribute::Synthetic { .. } => *version >= VERSION_45_3,
            Attribute::Signature { .. } => *version >= VERSION_49_0,
            Attribute::SourceFile { .. } => *version >= VERSION_45_3,
            Attribute::SourceDebugExtension { .. } => *version >= VERSION_49_0,
            Attribute::LineNumberTable { .. } => *version >= VERSION_45_3,
            Attribute::LocalVariableTable { .. } => *version >= VERSION_49_0,
            Attribute::LocalVariableTypeTable { .. } => *version >= VERSION_45_3,
            Attribute::Deprecated { .. } => *version >= VERSION_45_3,
            Attribute::RuntimeVisibleAnnotations { .. } => *version >= VERSION_49_0,
            Attribute::RuntimeInvisibleAnnotations { .. } => *version >= VERSION_49_0,
            Attribute::RuntimeVisibleParameterAnnotations { .. } => *version >= VERSION_49_0,
            Attribute::RuntimeInvisibleParameterAnnotations { .. } => *version >= VERSION_49_0,
            Attribute::RuntimeVisibleTypeAnnotations { .. } => *version >= VERSION_52_0,
            Attribute::RuntimeInvisibleTypeAnnotations { .. } => *version >= VERSION_52_0,
            Attribute::AnnotationDefault { .. } => *version >= VERSION_49_0,
            Attribute::BootstrapMethods { .. } => *version >= VERSION_51_0,
            Attribute::MethodParameters { .. } => *version >= VERSION_52_0,
            Attribute::Module { .. } => *version >= VERSION_53_0,
            Attribute::ModulePackages { .. } => *version >= VERSION_53_0,
            Attribute::ModuleMainClass { .. } => *version >= VERSION_53_0,
            Attribute::NestHost { .. } => *version >= VERSION_55_0,
            Attribute::NestMembers { .. } => *version >= VERSION_55_0,
            Attribute::Record { .. } => *version >= VERSION_60_0,
            Attribute::PermittedSubclasses { .. } => *version >= VERSION_61_0,
            Attribute::Unknown { .. } => *version >= VERSION_45_3,
        }
    }

    /// Deserializes an Attribute from bytes.
    ///
    /// This method reads an attribute from the provided byte reader, using the constant pool to
    /// resolve attribute names.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::Attribute;
    /// use ristretto_classfile::ConstantPool;
    /// use ristretto_classfile::byte_reader::ByteReader;
    /// use byteorder::{BigEndian, WriteBytesExt};
    ///
    /// // Create a constant pool with the necessary entries
    /// let mut constant_pool = ConstantPool::new();
    /// let name_index = constant_pool.add_utf8("SourceFile")?;
    /// let source_file_index = constant_pool.add_utf8("MyClass.java")?;
    ///
    /// // Create bytes representing a SourceFile attribute
    /// let mut bytes = Vec::new();
    /// bytes.write_u16::<BigEndian>(name_index)?;        // name_index
    /// bytes.write_u32::<BigEndian>(2)?;                 // attribute_length
    /// bytes.write_u16::<BigEndian>(source_file_index)?; // source_file_index
    ///
    /// // Deserialize the attribute
    /// let mut reader = ByteReader::new(&bytes);
    /// let attribute = Attribute::from_bytes(&constant_pool, &mut reader)?;
    ///
    /// // Verify the deserialized attribute
    /// if let Attribute::SourceFile { name_index: attr_name_idx, source_file_index: attr_source_idx } = attribute {
    ///     assert_eq!(attr_name_idx, name_index);
    ///     assert_eq!(attr_source_idx, source_file_index);
    /// } else {
    ///     panic!("Expected SourceFile attribute");
    /// }
    /// # Ok::<(), ristretto_classfile::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - Returns `InvalidAttributeNameIndex` if the name index is invalid in the constant pool.
    /// - Returns `InvalidAttributeLength` if the attribute length doesn't match the expected length.
    /// - Returns other errors if deserialization of specific attribute types fails.
    #[expect(clippy::too_many_lines)]
    pub fn from_bytes(
        constant_pool: &ConstantPool<'_>,
        bytes: &mut ByteReader<'_>,
    ) -> Result<Attribute> {
        let name_index = bytes.read_u16()?;
        let Some(Constant::Utf8(attribute_name)) = constant_pool.get_unchecked(name_index) else {
            return Err(InvalidAttributeNameIndex(name_index));
        };

        let info_length = bytes.read_u32()?;
        let attribute = match attribute_name.as_bytes() {
            b"ConstantValue" => {
                if info_length != 2 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::ConstantValue {
                    name_index,
                    constant_value_index: bytes.read_u16()?,
                }
            }
            b"Code" => {
                // Instruction pointers are converted from byte offsets to instruction offsets to
                // facilitate faster / easier instruction manipulation at runtime.  During runtime,
                // the instruction offset can be used directly and calculating the next instruction
                // byte offset is unnecessary. This separates the physical storage of the
                // instructions from the logical representation.
                let max_stack = bytes.read_u16()?;
                let max_locals = bytes.read_u16()?;

                let code_length = bytes.read_u32()?;
                let code_slice = bytes.read_bytes(code_length as usize)?;
                let (byte_to_instruction_pairs, instructions) =
                    offset_utils::instructions_from_bytes(&mut ByteReader::new(code_slice))?;

                let exception_length = bytes.read_u16()?;
                let mut exception_table = Vec::with_capacity(exception_length as usize);
                for _ in 0..exception_length {
                    let mut exception = ExceptionTableEntry::from_bytes(bytes)?;
                    exception.range_pc.start =
                        lookup_byte_offset(&byte_to_instruction_pairs, exception.range_pc.start)
                            .ok_or(InvalidInstructionOffset(u32::from(
                                exception.range_pc.start,
                            )))?;
                    exception.range_pc.end =
                        lookup_byte_offset_le(&byte_to_instruction_pairs, exception.range_pc.end)
                            .ok_or(InvalidInstructionOffset(u32::from(exception.range_pc.end)))?;
                    exception.handler_pc =
                        lookup_byte_offset(&byte_to_instruction_pairs, exception.handler_pc)
                            .ok_or(InvalidInstructionOffset(u32::from(exception.handler_pc)))?;
                    exception_table.push(exception);
                }
                let attributes = Self::from_bytes_code_attributes(
                    constant_pool,
                    bytes,
                    &byte_to_instruction_pairs,
                )?;
                Attribute::Code {
                    name_index,
                    max_stack,
                    max_locals,
                    code: instructions,
                    exception_table,
                    attributes,
                }
            }
            b"StackMapTable" => {
                let frames_count = bytes.read_u16()?;
                let mut frames = Vec::with_capacity(frames_count as usize);
                for _ in 0..frames_count {
                    let stack_frame = StackFrame::from_bytes(bytes)?;
                    frames.push(stack_frame);
                }
                Attribute::StackMapTable { name_index, frames }
            }
            b"Exceptions" => {
                let exception_indexes_count = bytes.read_u16()?;
                let mut exception_indexes = Vec::with_capacity(exception_indexes_count as usize);
                for _ in 0..exception_indexes_count {
                    exception_indexes.push(bytes.read_u16()?);
                }
                Attribute::Exceptions {
                    name_index,
                    exception_indexes,
                }
            }
            b"InnerClasses" => {
                let classes_count = bytes.read_u16()?;
                let mut classes = Vec::with_capacity(classes_count as usize);
                for _ in 0..classes_count {
                    let inner_class = InnerClass::from_bytes(bytes)?;
                    classes.push(inner_class);
                }
                Attribute::InnerClasses {
                    name_index,
                    classes,
                }
            }
            b"EnclosingMethod" => {
                if info_length != 4 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::EnclosingMethod {
                    name_index,
                    class_index: bytes.read_u16()?,
                    method_index: bytes.read_u16()?,
                }
            }
            b"Synthetic" => {
                if info_length != 0 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::Synthetic { name_index }
            }
            b"Signature" => {
                if info_length != 2 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::Signature {
                    name_index,
                    signature_index: bytes.read_u16()?,
                }
            }
            b"SourceFile" => {
                if info_length != 2 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::SourceFile {
                    name_index,
                    source_file_index: bytes.read_u16()?,
                }
            }
            b"SourceDebugExtension" => {
                let debug_extension_bytes = bytes.read_bytes(info_length as usize)?;
                let debug_extension = mutf8::from_bytes(debug_extension_bytes)?;
                Attribute::SourceDebugExtension {
                    name_index,
                    debug_extension,
                }
            }
            b"LineNumberTable" => {
                let line_number_table_count = bytes.read_u16()?;
                let mut line_numbers = Vec::with_capacity(line_number_table_count as usize);
                for _ in 0..line_number_table_count {
                    line_numbers.push(LineNumber::from_bytes(bytes)?);
                }
                Attribute::LineNumberTable {
                    name_index,
                    line_numbers,
                }
            }
            b"LocalVariableTable" => {
                let variables_count = bytes.read_u16()?;
                let mut variables = Vec::with_capacity(variables_count as usize);
                for _ in 0..variables_count {
                    variables.push(LocalVariableTable::from_bytes(bytes)?);
                }
                Attribute::LocalVariableTable {
                    name_index,
                    variables,
                }
            }
            b"LocalVariableTypeTable" => {
                let variable_types_count = bytes.read_u16()?;
                let mut variable_types = Vec::with_capacity(variable_types_count as usize);
                for _ in 0..variable_types_count {
                    variable_types.push(LocalVariableTypeTable::from_bytes(bytes)?);
                }
                Attribute::LocalVariableTypeTable {
                    name_index,
                    variable_types,
                }
            }
            b"Deprecated" => {
                if info_length != 0 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::Deprecated { name_index }
            }
            b"RuntimeVisibleAnnotations" => {
                let annotations_count = bytes.read_u16()?;
                let mut annotations = Vec::with_capacity(annotations_count as usize);
                for _ in 0..annotations_count {
                    let annotation = Annotation::from_bytes(bytes)?;
                    annotations.push(annotation);
                }
                Attribute::RuntimeVisibleAnnotations {
                    name_index,
                    annotations,
                }
            }
            b"RuntimeInvisibleAnnotations" => {
                let annotations_count = bytes.read_u16()?;
                let mut annotations = Vec::with_capacity(annotations_count as usize);
                for _ in 0..annotations_count {
                    let annotation = Annotation::from_bytes(bytes)?;
                    annotations.push(annotation);
                }
                Attribute::RuntimeInvisibleAnnotations {
                    name_index,
                    annotations,
                }
            }
            b"RuntimeVisibleParameterAnnotations" => {
                let parameter_annotations_count = bytes.read_u8()?;
                let mut parameter_annotations =
                    Vec::with_capacity(parameter_annotations_count as usize);
                for _ in 0..parameter_annotations_count {
                    let parameter_annotation = ParameterAnnotation::from_bytes(bytes)?;
                    parameter_annotations.push(parameter_annotation);
                }
                Attribute::RuntimeVisibleParameterAnnotations {
                    name_index,
                    parameter_annotations,
                }
            }
            b"RuntimeInvisibleParameterAnnotations" => {
                let parameter_annotations_count = bytes.read_u8()?;
                let mut parameter_annotations =
                    Vec::with_capacity(parameter_annotations_count as usize);
                for _ in 0..parameter_annotations_count {
                    let parameter_annotation = ParameterAnnotation::from_bytes(bytes)?;
                    parameter_annotations.push(parameter_annotation);
                }
                Attribute::RuntimeInvisibleParameterAnnotations {
                    name_index,
                    parameter_annotations,
                }
            }
            b"RuntimeVisibleTypeAnnotations" => {
                let type_annotations_count = bytes.read_u16()?;
                let mut type_annotations = Vec::with_capacity(type_annotations_count as usize);
                for _ in 0..type_annotations_count {
                    let type_annotation = TypeAnnotation::from_bytes(bytes)?;
                    type_annotations.push(type_annotation);
                }
                Attribute::RuntimeVisibleTypeAnnotations {
                    name_index,
                    type_annotations,
                }
            }
            b"RuntimeInvisibleTypeAnnotations" => {
                let type_annotations_count = bytes.read_u16()?;
                let mut type_annotations = Vec::with_capacity(type_annotations_count as usize);
                for _ in 0..type_annotations_count {
                    let type_annotation = TypeAnnotation::from_bytes(bytes)?;
                    type_annotations.push(type_annotation);
                }
                Attribute::RuntimeInvisibleTypeAnnotations {
                    name_index,
                    type_annotations,
                }
            }
            b"AnnotationDefault" => {
                let element = AnnotationElement::from_bytes(bytes)?;
                Attribute::AnnotationDefault {
                    name_index,
                    element,
                }
            }
            b"BootstrapMethods" => {
                let bootstrap_methods_count = bytes.read_u16()?;
                let mut methods = Vec::with_capacity(bootstrap_methods_count as usize);
                for _ in 0..bootstrap_methods_count {
                    let bootstrap_method = BootstrapMethod::from_bytes(bytes)?;
                    methods.push(bootstrap_method);
                }
                Attribute::BootstrapMethods {
                    name_index,
                    methods,
                }
            }
            b"MethodParameters" => {
                let parameters_count = bytes.read_u8()?;
                let mut parameters = Vec::with_capacity(parameters_count as usize);
                for _ in 0..parameters_count {
                    let method_parameters = MethodParameter::from_bytes(bytes)?;
                    parameters.push(method_parameters);
                }
                Attribute::MethodParameters {
                    name_index,
                    parameters,
                }
            }
            b"Module" => {
                let module_name_index = bytes.read_u16()?;
                let flags = ModuleAccessFlags::from_bytes(bytes)?;
                let version_index = bytes.read_u16()?;
                let requires_count = bytes.read_u16()?;
                let mut requires = Vec::with_capacity(requires_count as usize);
                for _ in 0..requires_count {
                    let require = Requires::from_bytes(bytes)?;
                    requires.push(require);
                }
                let exports_count = bytes.read_u16()?;
                let mut exports = Vec::with_capacity(exports_count as usize);
                for _ in 0..exports_count {
                    let export = Exports::from_bytes(bytes)?;
                    exports.push(export);
                }
                let opens_count = bytes.read_u16()?;
                let mut opens = Vec::with_capacity(opens_count as usize);
                for _ in 0..opens_count {
                    let open = Opens::from_bytes(bytes)?;
                    opens.push(open);
                }
                let uses_count = bytes.read_u16()?;
                let mut uses = Vec::with_capacity(uses_count as usize);
                for _ in 0..uses_count {
                    uses.push(bytes.read_u16()?);
                }
                let provides_count = bytes.read_u16()?;
                let mut provides = Vec::with_capacity(provides_count as usize);
                for _ in 0..provides_count {
                    let provide = Provides::from_bytes(bytes)?;
                    provides.push(provide);
                }
                Attribute::Module {
                    name_index,
                    module_name_index,
                    flags,
                    version_index,
                    requires,
                    exports,
                    opens,
                    uses,
                    provides,
                }
            }
            b"ModulePackages" => {
                let package_indexes_count = bytes.read_u16()?;
                let mut package_indexes = Vec::with_capacity(package_indexes_count as usize);
                for _ in 0..package_indexes_count {
                    package_indexes.push(bytes.read_u16()?);
                }
                Attribute::ModulePackages {
                    name_index,
                    package_indexes,
                }
            }
            b"ModuleMainClass" => {
                if info_length != 2 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::ModuleMainClass {
                    name_index,
                    main_class_index: bytes.read_u16()?,
                }
            }
            b"NestHost" => {
                if info_length != 2 {
                    return Err(InvalidAttributeLength(info_length));
                }
                Attribute::NestHost {
                    name_index,
                    host_class_index: bytes.read_u16()?,
                }
            }
            b"NestMembers" => {
                let class_indexes_count = bytes.read_u16()?;
                let mut class_indexes = Vec::with_capacity(class_indexes_count as usize);
                for _ in 0..class_indexes_count {
                    class_indexes.push(bytes.read_u16()?);
                }
                Attribute::NestMembers {
                    name_index,
                    class_indexes,
                }
            }
            b"Record" => {
                let record_count = bytes.read_u16()?;
                let mut records = Vec::with_capacity(record_count as usize);
                for _ in 0..record_count {
                    let record = Record::from_bytes(constant_pool, bytes)?;
                    records.push(record);
                }
                Attribute::Record {
                    name_index,
                    records,
                }
            }
            b"PermittedSubclasses" => {
                let class_indexes_count = bytes.read_u16()?;
                let mut class_indexes = Vec::with_capacity(class_indexes_count as usize);
                for _ in 0..class_indexes_count {
                    class_indexes.push(bytes.read_u16()?);
                }
                Attribute::PermittedSubclasses {
                    name_index,
                    class_indexes,
                }
            }
            _ => {
                let info = bytes.read_bytes(info_length as usize)?.to_vec();
                Attribute::Unknown { name_index, info }
            }
        };
        Ok(attribute)
    }

    fn from_bytes_code_attributes(
        constant_pool: &ConstantPool<'_>,
        bytes: &mut ByteReader<'_>,
        byte_to_instruction_pairs: &[(u16, u16)],
    ) -> Result<Vec<Attribute>> {
        let attributes_count = bytes.read_u16()?;
        let mut attributes = Vec::with_capacity(attributes_count as usize);
        for _ in 0..attributes_count {
            let attribute = Attribute::from_bytes(constant_pool, bytes)?;
            match attribute {
                Attribute::LineNumberTable {
                    name_index,
                    mut line_numbers,
                } => {
                    for line_number in &mut line_numbers {
                        line_number.start_pc =
                            lookup_byte_offset(byte_to_instruction_pairs, line_number.start_pc)
                                .ok_or(InvalidInstructionOffset(u32::from(line_number.start_pc)))?;
                    }
                    let attribute = Attribute::LineNumberTable {
                        name_index,
                        line_numbers,
                    };
                    attributes.push(attribute);
                }
                Attribute::StackMapTable {
                    name_index,
                    mut frames,
                } => {
                    let mut first_frame = true;
                    let mut last_byte_offset: u16 = 0;
                    let mut last_instruction_offset: u16 = 0;
                    for frame in &mut frames {
                        let offset_delta = frame.offset_delta();
                        let byte_offset = if first_frame {
                            offset_delta
                        } else {
                            last_byte_offset
                                .saturating_add(offset_delta)
                                .saturating_add(1)
                        };

                        let instruction_offset =
                            lookup_byte_offset(byte_to_instruction_pairs, byte_offset)
                                .ok_or(InvalidInstructionOffset(u32::from(byte_offset)))?;
                        // Calculate the instruction delta offset from the last instruction offset
                        // subtracting 1 to account for the current instruction.
                        let instruction_delta_offset = if first_frame {
                            first_frame = false;
                            instruction_offset
                        } else {
                            instruction_offset
                                .saturating_sub(last_instruction_offset)
                                .saturating_sub(1)
                        };

                        match frame {
                            StackFrame::SameFrame { frame_type } => {
                                // SameFrame uses the offset as the frame type
                                *frame_type = u8::try_from(instruction_delta_offset)?;
                            }
                            StackFrame::SameLocals1StackItemFrame { frame_type, .. } => {
                                // SameLocals1StackItemFrame requires that the 64 is added to the
                                // delta offset as it is used as the frame type.
                                let instruction_delta_offset =
                                    instruction_delta_offset.saturating_add(64);
                                *frame_type = u8::try_from(instruction_delta_offset)?;
                            }
                            StackFrame::AppendFrame { offset_delta, .. }
                            | StackFrame::ChopFrame { offset_delta, .. }
                            | StackFrame::FullFrame { offset_delta, .. }
                            | StackFrame::SameFrameExtended { offset_delta, .. }
                            | StackFrame::SameLocals1StackItemFrameExtended {
                                offset_delta, ..
                            } => {
                                *offset_delta = instruction_delta_offset;
                            }
                        }
                        last_byte_offset = byte_offset;
                        last_instruction_offset = instruction_offset;
                    }
                    let attribute = Attribute::StackMapTable { name_index, frames };
                    attributes.push(attribute);
                }
                _ => attributes.push(attribute),
            }
        }
        Ok(attributes)
    }

    /// Serialize the Attribute to bytes.
    ///
    /// This method writes the attribute to the provided byte vector in the format expected by the
    /// JVM specification.
    ///
    /// # Errors
    ///
    /// - Returns an error if serialization of any part of the attribute fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::Attribute;
    /// use ristretto_classfile::Result;
    ///
    /// let source_file = Attribute::SourceFile {
    ///     name_index: 1,
    ///     source_file_index: 2,
    /// };
    ///
    /// let mut bytes = Vec::new();
    /// source_file.to_bytes(&mut bytes)?;
    ///
    /// assert_eq!(bytes, vec![0, 1, 0, 0, 0, 2, 0, 2]);
    /// # Ok::<(), ristretto_classfile::Error>(())
    /// ```
    #[expect(clippy::too_many_lines)]
    #[expect(clippy::match_same_arms)]
    pub fn to_bytes(&self, bytes: &mut Vec<u8>) -> Result<()> {
        let (name_index, info) = match self {
            Attribute::ConstantValue {
                name_index,
                constant_value_index,
            } => (name_index, constant_value_index.to_be_bytes().to_vec()),
            Attribute::Code {
                name_index,
                max_stack,
                max_locals,
                code,
                exception_table,
                attributes,
            } => {
                let mut bytes = Vec::new();
                bytes.write_u16::<BigEndian>(*max_stack)?;
                bytes.write_u16::<BigEndian>(*max_locals)?;

                let (instruction_to_byte_map, code_bytes) =
                    offset_utils::instructions_to_bytes(code)?;
                let code_length = u32::try_from(code_bytes.len())?;
                bytes.write_u32::<BigEndian>(code_length)?;
                bytes.extend_from_slice(code_bytes.as_slice());

                let exceptions_length = u16::try_from(exception_table.len())?;
                bytes.write_u16::<BigEndian>(exceptions_length)?;
                for exception in &mut exception_table.clone() {
                    // Convert the instruction offset to byte offset
                    exception.range_pc.start = *instruction_to_byte_map
                        .get(&exception.range_pc.start)
                        .ok_or(InvalidInstructionOffset(u32::from(
                            exception.range_pc.start,
                        )))?;
                    exception.range_pc.end = instruction_to_byte_map
                        .iter()
                        .filter(|&(&k, _)| k <= exception.range_pc.end)
                        .max_by_key(|&(&k, _)| k)
                        .map(|(_, &v)| v)
                        .ok_or(InvalidInstructionOffset(u32::from(exception.range_pc.end)))?;
                    exception.handler_pc = *instruction_to_byte_map
                        .get(&exception.handler_pc)
                        .ok_or(InvalidInstructionOffset(u32::from(exception.handler_pc)))?;
                    exception.to_bytes(&mut bytes)?;
                }

                Self::to_bytes_code_attributes(attributes, &mut bytes, &instruction_to_byte_map)?;
                (name_index, bytes)
            }
            Attribute::StackMapTable { name_index, frames } => {
                let mut bytes = Vec::new();
                let frames_length = u16::try_from(frames.len())?;
                bytes.write_u16::<BigEndian>(frames_length)?;
                for frame in frames {
                    frame.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::Exceptions {
                name_index,
                exception_indexes,
            } => {
                let mut bytes = Vec::new();
                let exception_indexes_length = u16::try_from(exception_indexes.len())?;
                bytes.write_u16::<BigEndian>(exception_indexes_length)?;
                for exception_index in exception_indexes {
                    bytes.write_u16::<BigEndian>(*exception_index)?;
                }
                (name_index, bytes)
            }
            Attribute::InnerClasses {
                name_index,
                classes,
            } => {
                let mut bytes = Vec::new();
                let classes_length = u16::try_from(classes.len())?;
                bytes.write_u16::<BigEndian>(classes_length)?;
                for inner_class in classes {
                    inner_class.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::EnclosingMethod {
                name_index,
                class_index,
                method_index,
            } => (
                name_index,
                [class_index.to_be_bytes(), method_index.to_be_bytes()].concat(),
            ),
            Attribute::Synthetic { name_index } => (name_index, Vec::new()),
            Attribute::Signature {
                name_index,
                signature_index,
            } => (name_index, signature_index.to_be_bytes().to_vec()),
            Attribute::SourceFile {
                name_index,
                source_file_index: sourcefile_index,
            } => (name_index, sourcefile_index.to_be_bytes().to_vec()),
            Attribute::SourceDebugExtension {
                name_index,
                debug_extension,
            } => {
                let bytes = mutf8::to_bytes(debug_extension)?;
                (name_index, bytes)
            }
            Attribute::LineNumberTable {
                name_index,
                line_numbers,
            } => {
                let mut bytes = Vec::new();
                let line_numbers_length = u16::try_from(line_numbers.len())?;
                bytes.write_u16::<BigEndian>(line_numbers_length)?;
                for line_number in line_numbers {
                    line_number.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::LocalVariableTable {
                name_index,
                variables,
            } => {
                let mut bytes = Vec::new();
                let variables_length = u16::try_from(variables.len())?;
                bytes.write_u16::<BigEndian>(variables_length)?;
                for variable in variables {
                    variable.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::LocalVariableTypeTable {
                name_index,
                variable_types,
            } => {
                let mut bytes = Vec::new();
                let variable_types_length = u16::try_from(variable_types.len())?;
                bytes.write_u16::<BigEndian>(variable_types_length)?;
                for variable_type in variable_types {
                    variable_type.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::Deprecated { name_index } => (name_index, Vec::new()),
            Attribute::RuntimeVisibleAnnotations {
                name_index,
                annotations,
            } => {
                let mut bytes = Vec::new();
                let annotations_length = u16::try_from(annotations.len())?;
                bytes.write_u16::<BigEndian>(annotations_length)?;
                for annotation in annotations {
                    annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::RuntimeInvisibleAnnotations {
                name_index,
                annotations,
            } => {
                let mut bytes = Vec::new();
                let annotations_length = u16::try_from(annotations.len())?;
                bytes.write_u16::<BigEndian>(annotations_length)?;
                for annotation in annotations {
                    annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::RuntimeVisibleParameterAnnotations {
                name_index,
                parameter_annotations,
            } => {
                let mut bytes = Vec::new();
                let parameter_annotations_length = u8::try_from(parameter_annotations.len())?;
                bytes.write_u8(parameter_annotations_length)?;
                for parameter_annotation in parameter_annotations {
                    parameter_annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::RuntimeInvisibleParameterAnnotations {
                name_index,
                parameter_annotations,
            } => {
                let mut bytes = Vec::new();
                let parameter_annotations_length = u8::try_from(parameter_annotations.len())?;
                bytes.write_u8(parameter_annotations_length)?;
                for parameter_annotation in parameter_annotations {
                    parameter_annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::RuntimeVisibleTypeAnnotations {
                name_index,
                type_annotations,
            } => {
                let mut bytes = Vec::new();
                let type_annotations_length = u16::try_from(type_annotations.len())?;
                bytes.write_u16::<BigEndian>(type_annotations_length)?;
                for type_annotation in type_annotations {
                    type_annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::RuntimeInvisibleTypeAnnotations {
                name_index,
                type_annotations,
            } => {
                let mut bytes = Vec::new();
                let type_annotations_length = u16::try_from(type_annotations.len())?;
                bytes.write_u16::<BigEndian>(type_annotations_length)?;
                for type_annotation in type_annotations {
                    type_annotation.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::AnnotationDefault {
                name_index,
                element,
            } => {
                let mut bytes = Vec::new();
                element.to_bytes(&mut bytes)?;
                (name_index, bytes)
            }
            Attribute::BootstrapMethods {
                name_index,
                methods,
            } => {
                let mut bytes = Vec::new();
                let methods_length = u16::try_from(methods.len())?;
                bytes.write_u16::<BigEndian>(methods_length)?;
                for method in methods {
                    method.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::MethodParameters {
                name_index,
                parameters,
            } => {
                let mut bytes = Vec::new();
                let parameters_length = u8::try_from(parameters.len())?;
                bytes.write_u8(parameters_length)?;
                for parameter in parameters {
                    parameter.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::Module {
                name_index,
                module_name_index,
                flags,
                version_index,
                requires,
                exports,
                opens,
                uses,
                provides,
            } => {
                let mut bytes = Vec::new();
                bytes.write_u16::<BigEndian>(*module_name_index)?;
                flags.to_bytes(&mut bytes)?;
                bytes.write_u16::<BigEndian>(*version_index)?;

                let requires_length = u16::try_from(requires.len())?;
                bytes.write_u16::<BigEndian>(requires_length)?;
                for require in requires {
                    require.to_bytes(&mut bytes)?;
                }

                let exports_length = u16::try_from(exports.len())?;
                bytes.write_u16::<BigEndian>(exports_length)?;
                for export in exports {
                    export.to_bytes(&mut bytes)?;
                }

                let opens_length = u16::try_from(opens.len())?;
                bytes.write_u16::<BigEndian>(opens_length)?;
                for open in opens {
                    open.to_bytes(&mut bytes)?;
                }

                let use_index_length = u16::try_from(uses.len())?;
                bytes.write_u16::<BigEndian>(use_index_length)?;
                for use_index in uses {
                    bytes.write_u16::<BigEndian>(*use_index)?;
                }

                let provides_length = u16::try_from(provides.len())?;
                bytes.write_u16::<BigEndian>(provides_length)?;
                for provide in provides {
                    provide.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::ModulePackages {
                name_index,
                package_indexes,
            } => {
                let mut bytes = Vec::new();
                let package_indexes_length = u16::try_from(package_indexes.len())?;
                bytes.write_u16::<BigEndian>(package_indexes_length)?;
                for package_index in package_indexes {
                    bytes.write_u16::<BigEndian>(*package_index)?;
                }
                (name_index, bytes)
            }
            Attribute::ModuleMainClass {
                name_index,
                main_class_index,
            } => (name_index, main_class_index.to_be_bytes().to_vec()),
            Attribute::NestHost {
                name_index,
                host_class_index,
            } => (name_index, host_class_index.to_be_bytes().to_vec()),
            Attribute::NestMembers {
                name_index,
                class_indexes,
            } => {
                let mut bytes = Vec::new();
                let class_indexes_length = u16::try_from(class_indexes.len())?;
                bytes.write_u16::<BigEndian>(class_indexes_length)?;
                for class_index in class_indexes {
                    bytes.write_u16::<BigEndian>(*class_index)?;
                }
                (name_index, bytes)
            }
            Attribute::Record {
                name_index,
                records,
            } => {
                let mut bytes = Vec::new();
                let records_length = u16::try_from(records.len())?;
                bytes.write_u16::<BigEndian>(records_length)?;
                for record in records {
                    record.to_bytes(&mut bytes)?;
                }
                (name_index, bytes)
            }
            Attribute::PermittedSubclasses {
                name_index,
                class_indexes,
            } => {
                let mut bytes = Vec::new();
                let class_indexes_length = u16::try_from(class_indexes.len())?;
                bytes.write_u16::<BigEndian>(class_indexes_length)?;
                for class_index in class_indexes {
                    bytes.write_u16::<BigEndian>(*class_index)?;
                }
                (name_index, bytes)
            }
            Attribute::Unknown { name_index, info } => (name_index, info.clone()),
        };

        bytes.write_u16::<BigEndian>(*name_index)?;

        let info_length = u32::try_from(info.len())?;
        bytes.write_u32::<BigEndian>(info_length)?;
        bytes.extend_from_slice(info.as_slice());
        Ok(())
    }

    /// Serializes the attributes of a Code attribute to bytes, handling special cases.
    ///
    /// This method is used internally by the `to_bytes` method when serializing a Code attribute.
    /// It handles the conversion of instruction offsets to byte offsets for attributes that contain
    /// instruction references (like `LineNumberTable` and `StackMapTable`).
    ///
    /// # Note
    ///
    /// This method is necessary because the JVM uses byte offsets in class files, but our in-memory
    /// representation uses instruction offsets for easier manipulation.
    ///
    /// # Errors
    ///
    /// - Returns an error if any instruction offset cannot be mapped to a byte offset.
    #[expect(clippy::too_many_lines)]
    fn to_bytes_code_attributes(
        attributes: &Vec<Attribute>,
        bytes: &mut Vec<u8>,
        instruction_to_byte_map: &AHashMap<u16, u16>,
    ) -> Result<()> {
        let attributes_length = u16::try_from(attributes.len())?;
        bytes.write_u16::<BigEndian>(attributes_length)?;
        for attribute in attributes {
            match attribute {
                Attribute::LineNumberTable {
                    name_index,
                    line_numbers,
                } => {
                    let mut new_line_numbers = Vec::new();
                    for line_number in line_numbers {
                        let start_pc = *instruction_to_byte_map
                            .get(&line_number.start_pc)
                            .ok_or(InvalidInstructionOffset(u32::from(line_number.start_pc)))?;
                        new_line_numbers.push(LineNumber {
                            start_pc,
                            line_number: line_number.line_number,
                        });
                    }
                    let attribute = Attribute::LineNumberTable {
                        name_index: *name_index,
                        line_numbers: new_line_numbers,
                    };
                    attribute.to_bytes(bytes)?;
                }
                Attribute::StackMapTable { name_index, frames } => {
                    let mut first_frame = true;
                    let mut last_byte_offset: u16 = 0;
                    let mut last_instruction_offset: u16 = 0;
                    let mut new_frames = Vec::new();
                    for frame in frames {
                        let offset_delta = frame.offset_delta();
                        let instruction_offset = if first_frame {
                            offset_delta
                        } else {
                            last_instruction_offset
                                .saturating_add(offset_delta)
                                .saturating_add(1)
                        };

                        let byte_offset = *instruction_to_byte_map
                            .get(&instruction_offset)
                            .ok_or(InvalidInstructionOffset(u32::from(instruction_offset)))?;
                        // Calculate the byte delta offset from the last instruction offset
                        // subtracting 1 to account for the current instruction.
                        let byte_delta_offset = if last_byte_offset == 0 {
                            first_frame = false;
                            byte_offset
                        } else {
                            byte_offset
                                .saturating_sub(last_byte_offset)
                                .saturating_sub(1)
                        };

                        match frame {
                            StackFrame::SameFrame { .. } => {
                                // SameFrame uses the offset as the frame type
                                new_frames.push(StackFrame::SameFrame {
                                    frame_type: u8::try_from(byte_delta_offset)?,
                                });
                            }
                            StackFrame::SameLocals1StackItemFrame { stack, .. } => {
                                // SameLocals1StackItemFrame requires that the 64 is added to the
                                // delta offset as it is used as the frame type.
                                let byte_delta_offset = byte_delta_offset.saturating_add(64);
                                new_frames.push(StackFrame::SameLocals1StackItemFrame {
                                    frame_type: u8::try_from(byte_delta_offset)?,
                                    stack: stack.clone(),
                                });
                            }
                            StackFrame::AppendFrame {
                                frame_type, locals, ..
                            } => {
                                new_frames.push(StackFrame::AppendFrame {
                                    frame_type: *frame_type,
                                    offset_delta: byte_delta_offset,
                                    locals: locals.clone(),
                                });
                            }
                            StackFrame::ChopFrame { frame_type, .. } => {
                                new_frames.push(StackFrame::ChopFrame {
                                    frame_type: *frame_type,
                                    offset_delta: byte_delta_offset,
                                });
                            }
                            StackFrame::FullFrame {
                                frame_type,
                                locals,
                                stack,
                                ..
                            } => {
                                new_frames.push(StackFrame::FullFrame {
                                    frame_type: *frame_type,
                                    offset_delta: byte_delta_offset,
                                    locals: locals.clone(),
                                    stack: stack.clone(),
                                });
                            }
                            StackFrame::SameFrameExtended { frame_type, .. } => {
                                new_frames.push(StackFrame::SameFrameExtended {
                                    frame_type: *frame_type,
                                    offset_delta: byte_delta_offset,
                                });
                            }
                            StackFrame::SameLocals1StackItemFrameExtended {
                                frame_type,
                                stack,
                                ..
                            } => {
                                new_frames.push(StackFrame::SameLocals1StackItemFrameExtended {
                                    frame_type: *frame_type,
                                    offset_delta: byte_delta_offset,
                                    stack: stack.clone(),
                                });
                            }
                        }
                        last_byte_offset = byte_offset;
                        last_instruction_offset = instruction_offset;
                    }
                    let attribute = Attribute::StackMapTable {
                        name_index: *name_index,
                        frames: new_frames,
                    };
                    attribute.to_bytes(bytes)?;
                }
                _ => attribute.to_bytes(bytes)?,
            }
        }
        Ok(())
    }
}

impl fmt::Display for Attribute {
    /// Implements the `Display` trait for `Attribute` to provide human-readable output.
    ///
    /// This implementation provides specialized formatting for certain attribute types:
    /// - `Code` attributes show detailed bytecode instructions with line numbers and offsets
    /// - `StackMapTable` attributes display frames in a structured format
    /// - Other attributes fall back to a Debug-like representation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ristretto_classfile::attributes::{Attribute, LineNumber};
    /// use ristretto_classfile::attributes::Instruction;
    ///
    /// // Create a LineNumberTable attribute
    /// let line_number_table = Attribute::LineNumberTable {
    ///     name_index: 1,
    ///     line_numbers: vec![
    ///         LineNumber { start_pc: 0, line_number: 1 },
    ///         LineNumber { start_pc: 5, line_number: 2 },
    ///     ],
    /// };
    ///
    /// // Display the attribute as a string
    /// let output = line_number_table.to_string();
    /// assert!(output.contains("LineNumberTable"));
    /// assert!(output.contains("start_pc: 0"));
    /// assert!(output.contains("line_number: 1"));
    ///
    /// // Code attributes have special formatting
    /// let code_attribute = Attribute::Code {
    ///     name_index: 1,
    ///     max_stack: 2,
    ///     max_locals: 1,
    ///     code: vec![Instruction::Iconst_1, Instruction::Ireturn],
    ///     exception_table: vec![],
    ///     attributes: vec![],
    /// };
    ///
    /// let output = code_attribute.to_string();
    /// assert!(output.contains("Code:"));
    /// assert!(output.contains("stack=2, locals=1"));
    /// assert!(output.contains("iconst_1"));
    /// assert!(output.contains("ireturn"));
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Attribute::Code {
                max_stack,
                max_locals,
                code,
                exception_table,
                attributes,
                ..
            } => {
                writeln!(f, "Code:")?;
                writeln!(f, "  stack={max_stack}, locals={max_locals}")?;

                let (instruction_to_byte_map, code_bytes) =
                    offset_utils::instructions_to_bytes(code).map_err(|_| fmt::Error)?;
                let code_length = code_bytes.len();
                let mut reader = ByteReader::new(&code_bytes);
                while reader.position() < code_length {
                    let index = reader.position();
                    let mut instruction =
                        Instruction::from_bytes(&mut reader).map_err(|_| fmt::Error)?;
                    match instruction {
                        Instruction::Tableswitch(ref mut table_switch) => {
                            let position = i32::try_from(index).map_err(|_| fmt::Error)?;
                            table_switch.default += position;
                            for offset in &mut table_switch.offsets {
                                *offset += position;
                            }
                        }
                        Instruction::Lookupswitch(ref mut lookupswitch) => {
                            let position = i32::try_from(index).map_err(|_| fmt::Error)?;
                            lookupswitch.default += position;
                            for offset in lookupswitch.pairs.values_mut() {
                                *offset += position;
                            }
                        }
                        _ => {}
                    }
                    let value = instruction.to_string();
                    let (name, value) = value.split_once(' ').unwrap_or((value.as_str(), ""));
                    let value = format!("{name:<13} {value}");
                    writeln!(f, "{index:>6}: {}", value.trim())?;
                }

                let mut exception_table = exception_table.clone();
                for exception in &mut exception_table {
                    exception.range_pc.start = *instruction_to_byte_map
                        .get(&exception.range_pc.start)
                        .ok_or(fmt::Error)?;
                    exception.range_pc.end = instruction_to_byte_map
                        .iter()
                        .filter(|&(&k, _)| k <= exception.range_pc.end)
                        .max_by_key(|&(&k, _)| k)
                        .map(|(_, &v)| v + 1)
                        .ok_or(fmt::Error)?;
                    exception.handler_pc = *instruction_to_byte_map
                        .get(&exception.handler_pc)
                        .ok_or(fmt::Error)?;
                }
                if !exception_table.is_empty() {
                    writeln!(f, "  {exception_table:?}")?;
                }

                for attribute in attributes {
                    match attribute {
                        Attribute::LineNumberTable { line_numbers, .. } => {
                            writeln!(f, "  LineNumberTable:")?;
                            for line_number in line_numbers {
                                let start_pc = instruction_to_byte_map
                                    .get(&line_number.start_pc)
                                    .ok_or(fmt::Error)?;
                                let line_number = line_number.line_number;
                                writeln!(f, "    line {line_number}: {start_pc}")?;
                            }
                        }
                        _ => writeln!(f, "{}", indent_lines(&attribute.to_string(), "  "))?,
                    }
                }
            }
            Attribute::StackMapTable { frames, .. } => {
                writeln!(f, "StackMapTable: number_of_entries = {}", frames.len())?;
                for frame in frames {
                    writeln!(f, "{}", indent_lines(&frame.to_string(), "  "))?;
                }
            }
            _ => write!(f, "{self:?}")?,
        }

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::JAVA_1_0_2;
    use crate::attributes::annotation_value_pair::AnnotationValuePair;
    use crate::attributes::nested_class_access_flags::NestedClassAccessFlags;
    use crate::attributes::{
        AnnotationElement, ExportsFlags, OpensFlags, RequiresFlags, TargetPath, TargetType,
        VerificationType,
    };
    use crate::method_access_flags::MethodAccessFlags;
    use indoc::indoc;

    const VERSION_45_0: Version = JAVA_1_0_2;

    #[test]
    fn test_invalid_attribute_name_index_error() {
        let expected_bytes = [0, 1, 0, 0, 0, 0];

        assert_eq!(
            Err(InvalidAttributeNameIndex(1)),
            Attribute::from_bytes(
                &ConstantPool::default(),
                &mut ByteReader::new(&expected_bytes)
            )
        );
    }

    fn test_invalid_attribute_from_bytes_error(attribute: &str) -> Result<()> {
        let mut constant_pool = ConstantPool::default();
        constant_pool.add_utf8(attribute)?;
        let expected_bytes = [0, 1, 0, 0, 0, 64];

        assert_eq!(
            Err(InvalidAttributeLength(64)),
            Attribute::from_bytes(&constant_pool, &mut ByteReader::new(&expected_bytes))
        );
        Ok(())
    }

    fn test_attribute(
        attribute: &Attribute,
        expected_bytes: &[u8],
        supported_versions: &Version,
    ) -> Result<()> {
        let name = attribute.name();
        let mut constant_pool = ConstantPool::default();
        constant_pool.add_utf8(name)?;

        assert!(attribute.valid_for_version(supported_versions));
        assert!(!attribute.valid_for_version(&VERSION_45_0));

        let mut bytes = Vec::new();
        attribute.to_bytes(&mut bytes)?;
        assert_eq!(expected_bytes, &bytes[..]);
        let mut reader = ByteReader::new(expected_bytes);
        assert_eq!(
            *attribute,
            Attribute::from_bytes(&constant_pool, &mut reader)?
        );
        Ok(())
    }

    #[test]
    fn test_constant_value_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("ConstantValue")
    }

    #[test]
    fn test_constant_value() -> Result<()> {
        let attribute = Attribute::ConstantValue {
            name_index: 1,
            constant_value_index: 42,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[expect(clippy::too_many_lines)]
    #[test]
    fn test_code() -> Result<()> {
        let constant = Attribute::ConstantValue {
            name_index: 2,
            constant_value_index: 42,
        };
        let line_number_table = Attribute::LineNumberTable {
            name_index: 3,
            line_numbers: vec![LineNumber {
                start_pc: 0,
                line_number: 1,
            }],
        };
        let frames = vec![
            StackFrame::SameFrame { frame_type: 0 },
            StackFrame::SameLocals1StackItemFrame {
                frame_type: 65,
                stack: vec![VerificationType::Null],
            },
            StackFrame::SameLocals1StackItemFrameExtended {
                frame_type: 247,
                offset_delta: 0,
                stack: vec![VerificationType::Null],
            },
            StackFrame::ChopFrame {
                frame_type: 248,
                offset_delta: 0,
            },
            StackFrame::SameFrameExtended {
                frame_type: 251,
                offset_delta: 0,
            },
            StackFrame::AppendFrame {
                frame_type: 252,
                offset_delta: 0,
                locals: vec![VerificationType::Null],
            },
            StackFrame::FullFrame {
                frame_type: 255,
                offset_delta: 0,
                locals: vec![VerificationType::Null],
                stack: vec![VerificationType::Integer],
            },
        ];
        let stack_map_table = Attribute::StackMapTable {
            name_index: 4,
            frames: frames.clone(),
        };
        let exception_table_entry = ExceptionTableEntry {
            range_pc: 0..1,
            handler_pc: 0,
            catch_type: 4,
        };
        let mut attribute = Attribute::Code {
            name_index: 1,
            max_stack: 2,
            max_locals: 3,
            code: vec![
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Nop,
                Instruction::Return,
            ],
            exception_table: vec![exception_table_entry],
            attributes: vec![
                constant.clone(),
                line_number_table.clone(),
                stack_map_table.clone(),
            ],
        };
        let expected_bytes = [
            0, 1, 0, 0, 0, 83, 0, 2, 0, 3, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 177, 0, 1, 0, 0, 0,
            1, 0, 0, 0, 4, 0, 3, 0, 2, 0, 0, 0, 2, 0, 42, 0, 3, 0, 0, 0, 6, 0, 1, 0, 0, 0, 1, 0, 4,
            0, 0, 0, 28, 0, 7, 0, 66, 5, 247, 0, 0, 5, 248, 0, 0, 251, 0, 0, 252, 0, 0, 5, 255, 0,
            0, 0, 1, 5, 0, 1, 1,
        ];
        let expected = indoc! {"\
            Code:
              stack=2, locals=3
                 0: nop
                 1: nop
                 2: nop
                 3: nop
                 4: nop
                 5: nop
                 6: nop
                 7: nop
                 8: return
              [ExceptionTableEntry { range_pc: 0..2, handler_pc: 0, catch_type: 4 }]
              ConstantValue { name_index: 2, constant_value_index: 42 }
              LineNumberTable:
                line 1: 0
              StackMapTable: number_of_entries = 7
                frame_type = 0 /* same */
                frame_type = 65 /* same_locals_1_stack_item */
                  stack = [ null ]
                frame_type = 247 /* same_locals_1_stack_item_frame_extended */
                  offset_delta = 0
                  stack = [ null ]
                frame_type = 248 /* chop */
                  offset_delta = 0
                frame_type = 251 /* same_frame_extended */
                  offset_delta = 0
                frame_type = 252 /* append */
                  offset_delta = 0
                  locals = [ null ]
                frame_type = 255 /* full_frame */
                  offset_delta = 0
                  locals = [ null ]
                  stack = [ int ]
        "};

        assert_eq!(expected, attribute.to_string());

        let mut constant_pool = ConstantPool::default();
        constant_pool.add_utf8(attribute.name())?;
        constant_pool.add_utf8(constant.name())?;
        constant_pool.add_utf8(line_number_table.name())?;
        constant_pool.add_utf8(stack_map_table.name())?;

        assert!(attribute.valid_for_version(&VERSION_50_0)); // Update to VERSION_50_0 since StackMapTable requires it
        assert!(!attribute.valid_for_version(&VERSION_45_0));

        let mut bytes = Vec::new();
        attribute.to_bytes(&mut bytes)?;
        assert_eq!(expected_bytes, &bytes[..]);
        let mut reader = ByteReader::new(&expected_bytes);

        // Adjust the frame_type offest before comparing
        if let Attribute::Code { attributes, .. } = &mut attribute
            && let Some(Attribute::StackMapTable { frames, .. }) = attributes.get_mut(2)
            && let Some(StackFrame::SameLocals1StackItemFrame { frame_type, .. }) =
                frames.get_mut(1)
        {
            *frame_type = 66; // Update to match the expected frame type
        }
        let code_attribute = Attribute::from_bytes(&constant_pool, &mut reader)?;
        assert_eq!(attribute, code_attribute);
        Ok(())
    }

    #[test]
    fn test_stack_map_table() -> Result<()> {
        let attribute = Attribute::StackMapTable {
            name_index: 1,
            frames: vec![StackFrame::SameFrame { frame_type: 0 }],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 3, 0, 1, 0];

        assert_eq!(
            indoc! {"
                StackMapTable: number_of_entries = 1
                  frame_type = 0 /* same */
            "},
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_50_0)
    }

    #[test]
    fn test_exceptions() -> Result<()> {
        let attribute = Attribute::Exceptions {
            name_index: 1,
            exception_indexes: vec![42],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 4, 0, 1, 0, 42];

        assert_eq!(
            "Exceptions { name_index: 1, exception_indexes: [42] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_inner_classes() -> Result<()> {
        let inner_class = InnerClass {
            class_info_index: 1,
            outer_class_info_index: 2,
            name_index: 3,
            access_flags: NestedClassAccessFlags::PUBLIC,
        };
        let attribute = Attribute::InnerClasses {
            name_index: 1,
            classes: vec![inner_class],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 10, 0, 1, 0, 1, 0, 2, 0, 3, 0, 1];

        assert_eq!(
            "InnerClasses { name_index: 1, classes: [InnerClass { class_info_index: 1, outer_class_info_index: 2, name_index: 3, access_flags: NestedClassAccessFlags(PUBLIC) }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_enclosing_method_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("EnclosingMethod")
    }

    #[test]
    fn test_enclosing_method() -> Result<()> {
        let attribute = Attribute::EnclosingMethod {
            name_index: 1,
            class_index: 42,
            method_index: 3,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 4, 0, 42, 0, 3];

        assert_eq!(
            "EnclosingMethod { name_index: 1, class_index: 42, method_index: 3 }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_synthetic_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("Synthetic")
    }

    #[test]
    fn test_synthetic() -> Result<()> {
        let attribute = Attribute::Synthetic { name_index: 1 };
        let expected_bytes = [0, 1, 0, 0, 0, 0];

        assert_eq!("Synthetic { name_index: 1 }", attribute.to_string());
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_signature_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("Signature")
    }

    #[test]
    fn test_signature() -> Result<()> {
        let attribute = Attribute::Signature {
            name_index: 1,
            signature_index: 42,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        assert_eq!(
            "Signature { name_index: 1, signature_index: 42 }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_source_file_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("SourceFile")
    }

    #[test]
    fn test_source_file() -> Result<()> {
        let attribute = Attribute::SourceFile {
            name_index: 1,
            source_file_index: 42,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        assert_eq!(
            "SourceFile { name_index: 1, source_file_index: 42 }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_source_debug_extension() -> Result<()> {
        let attribute = Attribute::SourceDebugExtension {
            name_index: 1,
            debug_extension: "foo".to_string(),
        };
        let expected_bytes = [0, 1, 0, 0, 0, 3, 102, 111, 111];

        assert_eq!(
            "SourceDebugExtension { name_index: 1, debug_extension: \"foo\" }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_line_number_table() -> Result<()> {
        let attribute = Attribute::LineNumberTable {
            name_index: 1,
            line_numbers: vec![LineNumber {
                start_pc: 2,
                line_number: 42,
            }],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 6, 0, 1, 0, 2, 0, 42];
        let expected = "LineNumberTable { name_index: 1, line_numbers: [LineNumber { start_pc: 2, line_number: 42 }] }";

        assert_eq!(expected, attribute.to_string());
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_locale_variable_table() -> Result<()> {
        let variable = LocalVariableTable {
            start_pc: 1,
            length: 2,
            name_index: 3,
            descriptor_index: 4,
            index: 5,
        };
        let attribute = Attribute::LocalVariableTable {
            name_index: 1,
            variables: vec![variable],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 12, 0, 1, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

        assert_eq!(
            "LocalVariableTable { name_index: 1, variables: [LocalVariableTable { start_pc: 1, length: 2, name_index: 3, descriptor_index: 4, index: 5 }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_local_variable_type_table() -> Result<()> {
        let variable_type = LocalVariableTypeTable {
            start_pc: 1,
            length: 2,
            name_index: 3,
            signature_index: 4,
            index: 5,
        };
        let attribute = Attribute::LocalVariableTypeTable {
            name_index: 1,
            variable_types: vec![variable_type],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 12, 0, 1, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

        assert_eq!(
            "LocalVariableTypeTable { name_index: 1, variable_types: [LocalVariableTypeTable { start_pc: 1, length: 2, name_index: 3, signature_index: 4, index: 5 }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_deprecated_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("Deprecated")
    }

    #[test]
    fn test_deprecated() -> Result<()> {
        let attribute = Attribute::Deprecated { name_index: 1 };
        let expected_bytes = [0, 1, 0, 0, 0, 0];

        assert_eq!("Deprecated { name_index: 1 }", attribute.to_string());
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }

    #[test]
    fn test_runtime_visible_annotations() -> Result<()> {
        let attribute = Attribute::RuntimeVisibleAnnotations {
            name_index: 1,
            annotations: vec![Annotation {
                type_index: 1,
                elements: vec![AnnotationValuePair {
                    name_index: 3,
                    value: AnnotationElement::Byte {
                        const_value_index: 42,
                    },
                }],
            }],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 11, 0, 1, 0, 1, 0, 1, 0, 3, 66, 0, 42];

        assert_eq!(
            "RuntimeVisibleAnnotations { name_index: 1, annotations: [Annotation { type_index: 1, elements: [AnnotationValuePair { name_index: 3, value: Byte { const_value_index: 42 } }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_runtime_invisible_annotations() -> Result<()> {
        let attribute = Attribute::RuntimeInvisibleAnnotations {
            name_index: 1,
            annotations: vec![Annotation {
                type_index: 1,
                elements: vec![AnnotationValuePair {
                    name_index: 3,
                    value: AnnotationElement::Byte {
                        const_value_index: 42,
                    },
                }],
            }],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 11, 0, 1, 0, 1, 0, 1, 0, 3, 66, 0, 42];

        assert_eq!(
            "RuntimeInvisibleAnnotations { name_index: 1, annotations: [Annotation { type_index: 1, elements: [AnnotationValuePair { name_index: 3, value: Byte { const_value_index: 42 } }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_runtime_visible_parameter_annotations() -> Result<()> {
        let annotation_value_pair = AnnotationValuePair {
            name_index: 1,
            value: AnnotationElement::Byte {
                const_value_index: 42,
            },
        };
        let annotation = Annotation {
            type_index: 3,
            elements: vec![annotation_value_pair],
        };
        let parameter_annotation = ParameterAnnotation {
            annotations: vec![annotation],
        };
        let attribute = Attribute::RuntimeVisibleParameterAnnotations {
            name_index: 1,
            parameter_annotations: vec![parameter_annotation],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 12, 1, 0, 1, 0, 3, 0, 1, 0, 1, 66, 0, 42];

        assert_eq!(
            "RuntimeVisibleParameterAnnotations { name_index: 1, parameter_annotations: [ParameterAnnotation { annotations: [Annotation { type_index: 3, elements: [AnnotationValuePair { name_index: 1, value: Byte { const_value_index: 42 } }] }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_runtime_invisible_parameter_annotations() -> Result<()> {
        let annotation_value_pair = AnnotationValuePair {
            name_index: 1,
            value: AnnotationElement::Byte {
                const_value_index: 42,
            },
        };
        let annotation = Annotation {
            type_index: 3,
            elements: vec![annotation_value_pair],
        };
        let parameter_annotation = ParameterAnnotation {
            annotations: vec![annotation],
        };
        let attribute = Attribute::RuntimeInvisibleParameterAnnotations {
            name_index: 1,
            parameter_annotations: vec![parameter_annotation],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 12, 1, 0, 1, 0, 3, 0, 1, 0, 1, 66, 0, 42];

        assert_eq!(
            "RuntimeInvisibleParameterAnnotations { name_index: 1, parameter_annotations: [ParameterAnnotation { annotations: [Annotation { type_index: 3, elements: [AnnotationValuePair { name_index: 1, value: Byte { const_value_index: 42 } }] }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_runtime_visible_type_annotations() -> Result<()> {
        let element = AnnotationValuePair {
            name_index: 1,
            value: AnnotationElement::Byte {
                const_value_index: 42,
            },
        };
        let type_annotation = TypeAnnotation {
            target_type: TargetType::Empty { target_type: 19 },
            type_path: vec![TargetPath {
                type_path_kind: 1,
                type_argument_index: 2,
            }],
            type_index: 42,
            elements: vec![element],
        };
        let attribute = Attribute::RuntimeVisibleTypeAnnotations {
            name_index: 1,
            type_annotations: vec![type_annotation],
        };
        let expected_bytes = [
            0, 1, 0, 0, 0, 15, 0, 1, 19, 1, 1, 2, 0, 42, 0, 1, 0, 1, 66, 0, 42,
        ];

        assert_eq!(
            "RuntimeVisibleTypeAnnotations { name_index: 1, type_annotations: [TypeAnnotation { target_type: Empty { target_type: 19 }, type_path: [TargetPath { type_path_kind: 1, type_argument_index: 2 }], type_index: 42, elements: [AnnotationValuePair { name_index: 1, value: Byte { const_value_index: 42 } }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_52_0)
    }

    #[test]
    fn test_runtime_invisible_type_annotations() -> Result<()> {
        let element = AnnotationValuePair {
            name_index: 1,
            value: AnnotationElement::Byte {
                const_value_index: 42,
            },
        };
        let type_annotation = TypeAnnotation {
            target_type: TargetType::Empty { target_type: 19 },
            type_path: vec![TargetPath {
                type_path_kind: 1,
                type_argument_index: 2,
            }],
            type_index: 42,
            elements: vec![element],
        };
        let attribute = Attribute::RuntimeInvisibleTypeAnnotations {
            name_index: 1,
            type_annotations: vec![type_annotation],
        };
        let expected_bytes = [
            0, 1, 0, 0, 0, 15, 0, 1, 19, 1, 1, 2, 0, 42, 0, 1, 0, 1, 66, 0, 42,
        ];

        assert_eq!(
            "RuntimeInvisibleTypeAnnotations { name_index: 1, type_annotations: [TypeAnnotation { target_type: Empty { target_type: 19 }, type_path: [TargetPath { type_path_kind: 1, type_argument_index: 2 }], type_index: 42, elements: [AnnotationValuePair { name_index: 1, value: Byte { const_value_index: 42 } }] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_52_0)
    }

    #[test]
    fn test_annotation_default() -> Result<()> {
        let attribute = Attribute::AnnotationDefault {
            name_index: 1,
            element: AnnotationElement::Byte {
                const_value_index: 42,
            },
        };
        let expected_bytes = [0, 1, 0, 0, 0, 3, 66, 0, 42];

        assert_eq!(
            "AnnotationDefault { name_index: 1, element: Byte { const_value_index: 42 } }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_49_0)
    }

    #[test]
    fn test_bootstrap_methods() -> Result<()> {
        let method = BootstrapMethod {
            bootstrap_method_ref: 3,
            arguments: vec![42],
        };
        let attribute = Attribute::BootstrapMethods {
            name_index: 1,
            methods: vec![method],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 8, 0, 1, 0, 3, 0, 1, 0, 42];

        assert_eq!(
            "BootstrapMethods { name_index: 1, methods: [BootstrapMethod { bootstrap_method_ref: 3, arguments: [42] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_51_0)
    }

    #[test]
    fn test_method_parameters() -> Result<()> {
        let parameter = MethodParameter {
            name_index: 2,
            access_flags: MethodAccessFlags::PUBLIC,
        };
        let attribute = Attribute::MethodParameters {
            name_index: 1,
            parameters: vec![parameter],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 5, 1, 0, 2, 0, 1];

        assert_eq!(
            "MethodParameters { name_index: 1, parameters: [MethodParameter { name_index: 2, access_flags: MethodAccessFlags(PUBLIC) }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_52_0)
    }

    #[test]
    fn test_module() -> Result<()> {
        let attribute = Attribute::Module {
            name_index: 1,
            module_name_index: 2,
            flags: ModuleAccessFlags::OPEN,
            version_index: 4,
            requires: vec![Requires {
                index: 5,
                flags: RequiresFlags::MANDATED,
                version_index: 7,
            }],
            exports: vec![Exports {
                index: 8,
                flags: ExportsFlags::MANDATED,
                to_index: vec![10],
            }],
            opens: vec![Opens {
                index: 11,
                flags: OpensFlags::MANDATED,
                to_index: vec![13],
            }],
            uses: vec![14],
            provides: vec![Provides {
                index: 15,
                with_index: vec![16],
            }],
        };
        let expected_bytes = [
            0, 1, 0, 0, 0, 46, 0, 2, 0, 32, 0, 4, 0, 1, 0, 5, 128, 0, 0, 7, 0, 1, 0, 8, 128, 0, 0,
            1, 0, 10, 0, 1, 0, 11, 128, 0, 0, 1, 0, 13, 0, 1, 0, 14, 0, 1, 0, 15, 0, 1, 0, 16,
        ];

        assert_eq!(
            "Module { name_index: 1, module_name_index: 2, flags: ModuleAccessFlags(OPEN), version_index: 4, requires: [Requires { index: 5, flags: RequiresFlags(MANDATED), version_index: 7 }], exports: [Exports { index: 8, flags: ExportsFlags(MANDATED), to_index: [10] }], opens: [Opens { index: 11, flags: OpensFlags(MANDATED), to_index: [13] }], uses: [14], provides: [Provides { index: 15, with_index: [16] }] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_53_0)
    }

    #[test]
    fn test_module_packages() -> Result<()> {
        let attribute = Attribute::ModulePackages {
            name_index: 1,
            package_indexes: vec![42],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 4, 0, 1, 0, 42];

        assert_eq!(
            "ModulePackages { name_index: 1, package_indexes: [42] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_53_0)
    }

    #[test]
    fn test_module_main_class_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("ModuleMainClass")
    }

    #[test]
    fn test_module_main_class() -> Result<()> {
        let attribute = Attribute::ModuleMainClass {
            name_index: 1,
            main_class_index: 42,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        assert_eq!(
            "ModuleMainClass { name_index: 1, main_class_index: 42 }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_53_0)
    }

    #[test]
    fn test_nest_host_from_bytes_error() -> Result<()> {
        test_invalid_attribute_from_bytes_error("NestHost")
    }

    #[test]
    fn test_nest_host() -> Result<()> {
        let attribute = Attribute::NestHost {
            name_index: 1,
            host_class_index: 42,
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        assert_eq!(
            "NestHost { name_index: 1, host_class_index: 42 }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_55_0)
    }

    #[test]
    fn test_nest_members() -> Result<()> {
        let attribute = Attribute::NestMembers {
            name_index: 1,
            class_indexes: vec![42],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 4, 0, 1, 0, 42];

        assert_eq!(
            "NestMembers { name_index: 1, class_indexes: [42] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_55_0)
    }

    #[test]
    fn test_record() -> Result<()> {
        let constant = Attribute::ConstantValue {
            name_index: 1,
            constant_value_index: 42,
        };
        let record = Record {
            name_index: 2,
            descriptor_index: 3,
            attributes: vec![constant.clone()],
        };
        let attribute = Attribute::Record {
            name_index: 4,
            records: vec![record],
        };
        let expected_bytes = [
            0, 4, 0, 0, 0, 16, 0, 1, 0, 2, 0, 3, 0, 1, 0, 1, 0, 0, 0, 2, 0, 42,
        ];

        let mut constant_pool = ConstantPool::default();
        constant_pool.add_utf8(constant.name())?;
        constant_pool.add_utf8("bar")?;
        constant_pool.add_utf8("test")?;
        constant_pool.add_utf8(attribute.name())?;

        assert!(attribute.valid_for_version(&VERSION_60_0));
        assert!(!attribute.valid_for_version(&VERSION_45_0));

        assert_eq!(
            "Record { name_index: 4, records: [Record { name_index: 2, descriptor_index: 3, attributes: [ConstantValue { name_index: 1, constant_value_index: 42 }] }] }",
            attribute.to_string()
        );

        let mut bytes = Vec::new();
        attribute.to_bytes(&mut bytes)?;
        assert_eq!(expected_bytes, &bytes[..]);
        let mut reader = ByteReader::new(&expected_bytes);
        assert_eq!(
            attribute,
            Attribute::from_bytes(&constant_pool, &mut reader)?
        );
        Ok(())
    }

    #[test]
    fn test_permitted_subclasses() -> Result<()> {
        let attribute = Attribute::PermittedSubclasses {
            name_index: 1,
            class_indexes: vec![42],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 4, 0, 1, 0, 42];

        assert_eq!(
            "PermittedSubclasses { name_index: 1, class_indexes: [42] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_61_0)
    }

    #[test]
    fn test_unknown() -> Result<()> {
        let attribute = Attribute::Unknown {
            name_index: 1,
            info: vec![0, 42],
        };
        let expected_bytes = [0, 1, 0, 0, 0, 2, 0, 42];

        assert_eq!(
            "Unknown { name_index: 1, info: [0, 42] }",
            attribute.to_string()
        );
        test_attribute(&attribute, &expected_bytes, &VERSION_45_3)
    }
}