1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
//! Extensions available to token mints and accounts

#[cfg(feature = "serde-traits")]
use serde::{Deserialize, Serialize};
use {
    crate::{
        error::TokenError,
        extension::{
            confidential_transfer::{ConfidentialTransferAccount, ConfidentialTransferMint},
            confidential_transfer_fee::{
                ConfidentialTransferFeeAmount, ConfidentialTransferFeeConfig,
            },
            cpi_guard::CpiGuard,
            default_account_state::DefaultAccountState,
            group_member_pointer::GroupMemberPointer,
            group_pointer::GroupPointer,
            immutable_owner::ImmutableOwner,
            interest_bearing_mint::InterestBearingConfig,
            memo_transfer::MemoTransfer,
            metadata_pointer::MetadataPointer,
            mint_close_authority::MintCloseAuthority,
            non_transferable::{NonTransferable, NonTransferableAccount},
            permanent_delegate::PermanentDelegate,
            transfer_fee::{TransferFeeAmount, TransferFeeConfig},
            transfer_hook::{TransferHook, TransferHookAccount},
        },
        pod::{PodAccount, PodMint},
        state::{Account, Mint, Multisig, PackedSizeOf},
    },
    bytemuck::{Pod, Zeroable},
    num_enum::{IntoPrimitive, TryFromPrimitive},
    solana_program::{
        account_info::AccountInfo,
        program_error::ProgramError,
        program_pack::{IsInitialized, Pack},
    },
    spl_pod::{
        bytemuck::{pod_from_bytes, pod_from_bytes_mut, pod_get_packed_len},
        primitives::PodU16,
    },
    spl_token_group_interface::state::{TokenGroup, TokenGroupMember},
    spl_type_length_value::variable_len_pack::VariableLenPack,
    std::{
        cmp::Ordering,
        convert::{TryFrom, TryInto},
        mem::size_of,
    },
};

/// Confidential Transfer extension
pub mod confidential_transfer;
/// Confidential Transfer Fee extension
pub mod confidential_transfer_fee;
/// CPI Guard extension
pub mod cpi_guard;
/// Default Account State extension
pub mod default_account_state;
/// Group Member Pointer extension
pub mod group_member_pointer;
/// Group Pointer extension
pub mod group_pointer;
/// Immutable Owner extension
pub mod immutable_owner;
/// Interest-Bearing Mint extension
pub mod interest_bearing_mint;
/// Memo Transfer extension
pub mod memo_transfer;
/// Metadata Pointer extension
pub mod metadata_pointer;
/// Mint Close Authority extension
pub mod mint_close_authority;
/// Non Transferable extension
pub mod non_transferable;
/// Permanent Delegate extension
pub mod permanent_delegate;
/// Utility to reallocate token accounts
pub mod reallocate;
/// Token-group extension
pub mod token_group;
/// Token-metadata extension
pub mod token_metadata;
/// Transfer Fee extension
pub mod transfer_fee;
/// Transfer Hook extension
pub mod transfer_hook;

/// Length in TLV structure
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
#[repr(transparent)]
pub struct Length(PodU16);
impl From<Length> for usize {
    fn from(n: Length) -> Self {
        Self::from(u16::from(n.0))
    }
}
impl TryFrom<usize> for Length {
    type Error = ProgramError;
    fn try_from(n: usize) -> Result<Self, Self::Error> {
        u16::try_from(n)
            .map(|v| Self(PodU16::from(v)))
            .map_err(|_| ProgramError::AccountDataTooSmall)
    }
}

/// Helper function to get the current TlvIndices from the current spot
fn get_tlv_indices(type_start: usize) -> TlvIndices {
    let length_start = type_start.saturating_add(size_of::<ExtensionType>());
    let value_start = length_start.saturating_add(pod_get_packed_len::<Length>());
    TlvIndices {
        type_start,
        length_start,
        value_start,
    }
}

/// Helper function to tack on the size of an extension bytes if an account with
/// extensions is exactly the size of a multisig
const fn adjust_len_for_multisig(account_len: usize) -> usize {
    if account_len == Multisig::LEN {
        account_len.saturating_add(size_of::<ExtensionType>())
    } else {
        account_len
    }
}

/// Helper function to calculate exactly how many bytes a value will take up,
/// given the value's length
const fn add_type_and_length_to_len(value_len: usize) -> usize {
    value_len
        .saturating_add(size_of::<ExtensionType>())
        .saturating_add(pod_get_packed_len::<Length>())
}

/// Helper struct for returning the indices of the type, length, and value in
/// a TLV entry
#[derive(Debug)]
struct TlvIndices {
    pub type_start: usize,
    pub length_start: usize,
    pub value_start: usize,
}
fn get_extension_indices<V: Extension>(
    tlv_data: &[u8],
    init: bool,
) -> Result<TlvIndices, ProgramError> {
    let mut start_index = 0;
    let v_account_type = V::TYPE.get_account_type();
    while start_index < tlv_data.len() {
        let tlv_indices = get_tlv_indices(start_index);
        if tlv_data.len() < tlv_indices.value_start {
            return Err(ProgramError::InvalidAccountData);
        }
        let extension_type =
            ExtensionType::try_from(&tlv_data[tlv_indices.type_start..tlv_indices.length_start])?;
        let account_type = extension_type.get_account_type();
        if extension_type == V::TYPE {
            // found an instance of the extension that we're initializing, return!
            return Ok(tlv_indices);
        // got to an empty spot, init here, or error if we're searching, since
        // nothing is written after an Uninitialized spot
        } else if extension_type == ExtensionType::Uninitialized {
            if init {
                return Ok(tlv_indices);
            } else {
                return Err(TokenError::ExtensionNotFound.into());
            }
        } else if v_account_type != account_type {
            return Err(TokenError::ExtensionTypeMismatch.into());
        } else {
            let length = pod_from_bytes::<Length>(
                &tlv_data[tlv_indices.length_start..tlv_indices.value_start],
            )?;
            let value_end_index = tlv_indices.value_start.saturating_add(usize::from(*length));
            start_index = value_end_index;
        }
    }
    Err(ProgramError::InvalidAccountData)
}

/// Basic information about the TLV buffer, collected from iterating through all
/// entries
#[derive(Debug, PartialEq)]
struct TlvDataInfo {
    /// The extension types written in the TLV buffer
    extension_types: Vec<ExtensionType>,
    /// The total number bytes allocated for all TLV entries.
    ///
    /// Each TLV entry's allocated bytes comprises two bytes for the `type`, two
    /// bytes for the `length`, and `length` number of bytes for the `value`.
    used_len: usize,
}

/// Fetches basic information about the TLV buffer by iterating through all
/// TLV entries.
fn get_tlv_data_info(tlv_data: &[u8]) -> Result<TlvDataInfo, ProgramError> {
    let mut extension_types = vec![];
    let mut start_index = 0;
    while start_index < tlv_data.len() {
        let tlv_indices = get_tlv_indices(start_index);
        if tlv_data.len() < tlv_indices.length_start {
            // There aren't enough bytes to store the next type, which means we
            // got to the end. The last byte could be used during a realloc!
            return Ok(TlvDataInfo {
                extension_types,
                used_len: tlv_indices.type_start,
            });
        }
        let extension_type =
            ExtensionType::try_from(&tlv_data[tlv_indices.type_start..tlv_indices.length_start])?;
        if extension_type == ExtensionType::Uninitialized {
            return Ok(TlvDataInfo {
                extension_types,
                used_len: tlv_indices.type_start,
            });
        } else {
            if tlv_data.len() < tlv_indices.value_start {
                // not enough bytes to store the length, malformed
                return Err(ProgramError::InvalidAccountData);
            }
            extension_types.push(extension_type);
            let length = pod_from_bytes::<Length>(
                &tlv_data[tlv_indices.length_start..tlv_indices.value_start],
            )?;

            let value_end_index = tlv_indices.value_start.saturating_add(usize::from(*length));
            if value_end_index > tlv_data.len() {
                // value blows past the size of the slice, malformed
                return Err(ProgramError::InvalidAccountData);
            }
            start_index = value_end_index;
        }
    }
    Ok(TlvDataInfo {
        extension_types,
        used_len: start_index,
    })
}

fn get_first_extension_type(tlv_data: &[u8]) -> Result<Option<ExtensionType>, ProgramError> {
    if tlv_data.is_empty() {
        Ok(None)
    } else {
        let tlv_indices = get_tlv_indices(0);
        if tlv_data.len() <= tlv_indices.length_start {
            return Ok(None);
        }
        let extension_type =
            ExtensionType::try_from(&tlv_data[tlv_indices.type_start..tlv_indices.length_start])?;
        if extension_type == ExtensionType::Uninitialized {
            Ok(None)
        } else {
            Ok(Some(extension_type))
        }
    }
}

fn check_min_len_and_not_multisig(input: &[u8], minimum_len: usize) -> Result<(), ProgramError> {
    if input.len() == Multisig::LEN || input.len() < minimum_len {
        Err(ProgramError::InvalidAccountData)
    } else {
        Ok(())
    }
}

fn check_account_type<S: BaseState>(account_type: AccountType) -> Result<(), ProgramError> {
    if account_type != S::ACCOUNT_TYPE {
        Err(ProgramError::InvalidAccountData)
    } else {
        Ok(())
    }
}

/// Any account with extensions must be at least `Account::LEN`.  Both mints and
/// accounts can have extensions
/// A mint with extensions that takes it past 165 could be indiscernible from an
/// Account with an extension, even if we add the account type. For example,
/// let's say we have:
///
/// Account: 165 bytes... + [2, 0, 3, 0, 100, ....]
///                          ^     ^       ^     ^
///                     acct type  extension length data...
///
/// Mint: 82 bytes... + 83 bytes of other extension data
///     + [2, 0, 3, 0, 100, ....]
///      (data in extension just happens to look like this)
///
/// With this approach, we only start writing the TLV data after Account::LEN,
/// which means we always know that the account type is going to be right after
/// that. We do a special case checking for a Multisig length, because those
/// aren't extensible under any circumstances.
const BASE_ACCOUNT_LENGTH: usize = Account::LEN;
/// Helper that tacks on the AccountType length, which gives the minimum for any
/// account with extensions
const BASE_ACCOUNT_AND_TYPE_LENGTH: usize = BASE_ACCOUNT_LENGTH + size_of::<AccountType>();

fn type_and_tlv_indices<S: BaseState>(
    rest_input: &[u8],
) -> Result<Option<(usize, usize)>, ProgramError> {
    if rest_input.is_empty() {
        Ok(None)
    } else {
        let account_type_index = BASE_ACCOUNT_LENGTH.saturating_sub(S::SIZE_OF);
        // check padding is all zeroes
        let tlv_start_index = account_type_index.saturating_add(size_of::<AccountType>());
        if rest_input.len() <= tlv_start_index {
            return Err(ProgramError::InvalidAccountData);
        }
        if rest_input[..account_type_index] != vec![0; account_type_index] {
            Err(ProgramError::InvalidAccountData)
        } else {
            Ok(Some((account_type_index, tlv_start_index)))
        }
    }
}

/// Checks a base buffer to verify if it is an Account without having to
/// completely deserialize it
fn is_initialized_account(input: &[u8]) -> Result<bool, ProgramError> {
    const ACCOUNT_INITIALIZED_INDEX: usize = 108; // See state.rs#L99

    if input.len() != BASE_ACCOUNT_LENGTH {
        return Err(ProgramError::InvalidAccountData);
    }
    Ok(input[ACCOUNT_INITIALIZED_INDEX] != 0)
}

fn get_extension_bytes<S: BaseState, V: Extension>(tlv_data: &[u8]) -> Result<&[u8], ProgramError> {
    if V::TYPE.get_account_type() != S::ACCOUNT_TYPE {
        return Err(ProgramError::InvalidAccountData);
    }
    let TlvIndices {
        type_start: _,
        length_start,
        value_start,
    } = get_extension_indices::<V>(tlv_data, false)?;
    // get_extension_indices has checked that tlv_data is long enough to include
    // these indices
    let length = pod_from_bytes::<Length>(&tlv_data[length_start..value_start])?;
    let value_end = value_start.saturating_add(usize::from(*length));
    if tlv_data.len() < value_end {
        return Err(ProgramError::InvalidAccountData);
    }
    Ok(&tlv_data[value_start..value_end])
}

fn get_extension_bytes_mut<S: BaseState, V: Extension>(
    tlv_data: &mut [u8],
) -> Result<&mut [u8], ProgramError> {
    if V::TYPE.get_account_type() != S::ACCOUNT_TYPE {
        return Err(ProgramError::InvalidAccountData);
    }
    let TlvIndices {
        type_start: _,
        length_start,
        value_start,
    } = get_extension_indices::<V>(tlv_data, false)?;
    // get_extension_indices has checked that tlv_data is long enough to include
    // these indices
    let length = pod_from_bytes::<Length>(&tlv_data[length_start..value_start])?;
    let value_end = value_start.saturating_add(usize::from(*length));
    if tlv_data.len() < value_end {
        return Err(ProgramError::InvalidAccountData);
    }
    Ok(&mut tlv_data[value_start..value_end])
}

/// Calculate the new expected size if the state allocates the given number
/// of bytes for the given extension type.
///
/// Provides the correct answer regardless if the extension is already present
/// in the TLV data.
fn try_get_new_account_len_for_extension_len<S: BaseState, V: Extension>(
    tlv_data: &[u8],
    new_extension_len: usize,
) -> Result<usize, ProgramError> {
    // get the new length used by the extension
    let new_extension_tlv_len = add_type_and_length_to_len(new_extension_len);
    let tlv_info = get_tlv_data_info(tlv_data)?;
    // If we're adding an extension, then we must have at least BASE_ACCOUNT_LENGTH
    // and account type
    let current_len = tlv_info
        .used_len
        .saturating_add(BASE_ACCOUNT_AND_TYPE_LENGTH);
    // get the current length used by the extension
    let current_extension_len = get_extension_bytes::<S, V>(tlv_data)
        .map(|x| add_type_and_length_to_len(x.len()))
        .unwrap_or(0);
    let new_len = current_len
        .saturating_sub(current_extension_len)
        .saturating_add(new_extension_tlv_len);
    Ok(adjust_len_for_multisig(new_len))
}

/// Trait for base state with extension
pub trait BaseStateWithExtensions<S: BaseState> {
    /// Get the buffer containing all extension data
    fn get_tlv_data(&self) -> &[u8];

    /// Fetch the bytes for a TLV entry
    fn get_extension_bytes<V: Extension>(&self) -> Result<&[u8], ProgramError> {
        get_extension_bytes::<S, V>(self.get_tlv_data())
    }

    /// Unpack a portion of the TLV data as the desired type
    fn get_extension<V: Extension + Pod>(&self) -> Result<&V, ProgramError> {
        pod_from_bytes::<V>(self.get_extension_bytes::<V>()?)
    }

    /// Unpacks a portion of the TLV data as the desired variable-length type
    fn get_variable_len_extension<V: Extension + VariableLenPack>(
        &self,
    ) -> Result<V, ProgramError> {
        let data = get_extension_bytes::<S, V>(self.get_tlv_data())?;
        V::unpack_from_slice(data)
    }

    /// Iterates through the TLV entries, returning only the types
    fn get_extension_types(&self) -> Result<Vec<ExtensionType>, ProgramError> {
        get_tlv_data_info(self.get_tlv_data()).map(|x| x.extension_types)
    }

    /// Get just the first extension type, useful to track mixed initializations
    fn get_first_extension_type(&self) -> Result<Option<ExtensionType>, ProgramError> {
        get_first_extension_type(self.get_tlv_data())
    }

    /// Get the total number of bytes used by TLV entries and the base type
    fn try_get_account_len(&self) -> Result<usize, ProgramError> {
        let tlv_info = get_tlv_data_info(self.get_tlv_data())?;
        if tlv_info.extension_types.is_empty() {
            Ok(S::SIZE_OF)
        } else {
            let total_len = tlv_info
                .used_len
                .saturating_add(BASE_ACCOUNT_AND_TYPE_LENGTH);
            Ok(adjust_len_for_multisig(total_len))
        }
    }
    /// Calculate the new expected size if the state allocates the given
    /// fixed-length extension instance.
    /// If the state already has the extension, the resulting account length
    /// will be unchanged.
    fn try_get_new_account_len<V: Extension + Pod>(&self) -> Result<usize, ProgramError> {
        try_get_new_account_len_for_extension_len::<S, V>(
            self.get_tlv_data(),
            pod_get_packed_len::<V>(),
        )
    }

    /// Calculate the new expected size if the state allocates the given
    /// variable-length extension instance.
    fn try_get_new_account_len_for_variable_len_extension<V: Extension + VariableLenPack>(
        &self,
        new_extension: &V,
    ) -> Result<usize, ProgramError> {
        try_get_new_account_len_for_extension_len::<S, V>(
            self.get_tlv_data(),
            new_extension.get_packed_len()?,
        )
    }
}

/// Encapsulates owned immutable base state data (mint or account) with possible
/// extensions
#[derive(Clone, Debug, PartialEq)]
pub struct StateWithExtensionsOwned<S: BaseState> {
    /// Unpacked base data
    pub base: S,
    /// Raw TLV data, deserialized on demand
    tlv_data: Vec<u8>,
}
impl<S: BaseState + Pack> StateWithExtensionsOwned<S> {
    /// Unpack base state, leaving the extension data as a slice
    ///
    /// Fails if the base state is not initialized.
    pub fn unpack(mut input: Vec<u8>) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(&input, S::SIZE_OF)?;
        let mut rest = input.split_off(S::SIZE_OF);
        let base = S::unpack(&input)?;
        if let Some((account_type_index, tlv_start_index)) = type_and_tlv_indices::<S>(&rest)? {
            // type_and_tlv_indices() checks that returned indexes are within range
            let account_type = AccountType::try_from(rest[account_type_index])
                .map_err(|_| ProgramError::InvalidAccountData)?;
            check_account_type::<S>(account_type)?;
            let tlv_data = rest.split_off(tlv_start_index);
            Ok(Self { base, tlv_data })
        } else {
            Ok(Self {
                base,
                tlv_data: vec![],
            })
        }
    }
}

impl<S: BaseState> BaseStateWithExtensions<S> for StateWithExtensionsOwned<S> {
    fn get_tlv_data(&self) -> &[u8] {
        &self.tlv_data
    }
}

/// Encapsulates immutable base state data (mint or account) with possible
/// extensions
#[derive(Debug, PartialEq)]
pub struct StateWithExtensions<'data, S: BaseState + Pack> {
    /// Unpacked base data
    pub base: S,
    /// Slice of data containing all TLV data, deserialized on demand
    tlv_data: &'data [u8],
}
impl<'data, S: BaseState + Pack> StateWithExtensions<'data, S> {
    /// Unpack base state, leaving the extension data as a slice
    ///
    /// Fails if the base state is not initialized.
    pub fn unpack(input: &'data [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at(S::SIZE_OF);
        let base = S::unpack(base_data)?;
        let tlv_data = unpack_tlv_data::<S>(rest)?;
        Ok(Self { base, tlv_data })
    }
}
impl<'a, S: BaseState + Pack> BaseStateWithExtensions<S> for StateWithExtensions<'a, S> {
    fn get_tlv_data(&self) -> &[u8] {
        self.tlv_data
    }
}

/// Encapsulates immutable base state data (mint or account) with possible
/// extensions, where the base state is Pod for zero-copy serde.
#[derive(Debug, PartialEq)]
pub struct PodStateWithExtensions<'data, S: BaseState + Pod> {
    /// Unpacked base data
    pub base: &'data S,
    /// Slice of data containing all TLV data, deserialized on demand
    tlv_data: &'data [u8],
}
impl<'data, S: BaseState + Pod> PodStateWithExtensions<'data, S> {
    /// Unpack base state, leaving the extension data as a slice
    ///
    /// Fails if the base state is not initialized.
    pub fn unpack(input: &'data [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at(S::SIZE_OF);
        let base = pod_from_bytes::<S>(base_data)?;
        if !base.is_initialized() {
            Err(ProgramError::UninitializedAccount)
        } else {
            let tlv_data = unpack_tlv_data::<S>(rest)?;
            Ok(Self { base, tlv_data })
        }
    }
}
impl<'a, S: BaseState + Pod> BaseStateWithExtensions<S> for PodStateWithExtensions<'a, S> {
    fn get_tlv_data(&self) -> &[u8] {
        self.tlv_data
    }
}

/// Trait for mutable base state with extension
pub trait BaseStateWithExtensionsMut<S: BaseState>: BaseStateWithExtensions<S> {
    /// Get the underlying TLV data as mutable
    fn get_tlv_data_mut(&mut self) -> &mut [u8];

    /// Get the underlying account type as mutable
    fn get_account_type_mut(&mut self) -> &mut [u8];

    /// Unpack a portion of the TLV data as the base mutable bytes
    fn get_extension_bytes_mut<V: Extension>(&mut self) -> Result<&mut [u8], ProgramError> {
        get_extension_bytes_mut::<S, V>(self.get_tlv_data_mut())
    }

    /// Unpack a portion of the TLV data as the desired type that allows
    /// modifying the type
    fn get_extension_mut<V: Extension + Pod>(&mut self) -> Result<&mut V, ProgramError> {
        pod_from_bytes_mut::<V>(self.get_extension_bytes_mut::<V>()?)
    }

    /// Packs a variable-length extension into its appropriate data segment.
    /// Fails if space hasn't already been allocated for the given extension
    fn pack_variable_len_extension<V: Extension + VariableLenPack>(
        &mut self,
        extension: &V,
    ) -> Result<(), ProgramError> {
        let data = self.get_extension_bytes_mut::<V>()?;
        // NOTE: Do *not* use `pack`, since the length check will cause
        // reallocations to smaller sizes to fail
        extension.pack_into_slice(data)
    }

    /// Packs the default extension data into an open slot if not already found
    /// in the data buffer. If extension is already found in the buffer, it
    /// overwrites the existing extension with the default state if
    /// `overwrite` is set. If extension found, but `overwrite` is not set,
    /// it returns error.
    fn init_extension<V: Extension + Pod + Default>(
        &mut self,
        overwrite: bool,
    ) -> Result<&mut V, ProgramError> {
        let length = pod_get_packed_len::<V>();
        let buffer = self.alloc::<V>(length, overwrite)?;
        let extension_ref = pod_from_bytes_mut::<V>(buffer)?;
        *extension_ref = V::default();
        Ok(extension_ref)
    }

    /// Reallocate and overwite the TLV entry for the given variable-length
    /// extension.
    ///
    /// Returns an error if the extension is not present, or if there is not
    /// enough space in the buffer.
    fn realloc_variable_len_extension<V: Extension + VariableLenPack>(
        &mut self,
        new_extension: &V,
    ) -> Result<(), ProgramError> {
        let data = self.realloc::<V>(new_extension.get_packed_len()?)?;
        new_extension.pack_into_slice(data)
    }

    /// Reallocate the TLV entry for the given extension to the given number of
    /// bytes.
    ///
    /// If the new length is smaller, it will compact the rest of the buffer and
    /// zero out the difference at the end. If it's larger, it will move the
    /// rest of the buffer data and zero out the new data.
    ///
    /// Returns an error if the extension is not present, or if this is not
    /// enough space in the buffer.
    fn realloc<V: Extension + VariableLenPack>(
        &mut self,
        length: usize,
    ) -> Result<&mut [u8], ProgramError> {
        let tlv_data = self.get_tlv_data_mut();
        let TlvIndices {
            type_start: _,
            length_start,
            value_start,
        } = get_extension_indices::<V>(tlv_data, false)?;
        let tlv_len = get_tlv_data_info(tlv_data).map(|x| x.used_len)?;
        let data_len = tlv_data.len();

        let length_ref = pod_from_bytes_mut::<Length>(&mut tlv_data[length_start..value_start])?;
        let old_length = usize::from(*length_ref);

        // Length check to avoid a panic later in `copy_within`
        if old_length < length {
            let new_tlv_len = tlv_len.saturating_add(length.saturating_sub(old_length));
            if new_tlv_len > data_len {
                return Err(ProgramError::InvalidAccountData);
            }
        }

        // write new length after the check, to avoid getting into a bad situation
        // if trying to recover from an error
        *length_ref = Length::try_from(length)?;

        let old_value_end = value_start.saturating_add(old_length);
        let new_value_end = value_start.saturating_add(length);
        tlv_data.copy_within(old_value_end..tlv_len, new_value_end);
        match old_length.cmp(&length) {
            Ordering::Greater => {
                // realloc to smaller, zero out the end
                let new_tlv_len = tlv_len.saturating_sub(old_length.saturating_sub(length));
                tlv_data[new_tlv_len..tlv_len].fill(0);
            }
            Ordering::Less => {
                // realloc to bigger, zero out the new bytes
                tlv_data[old_value_end..new_value_end].fill(0);
            }
            Ordering::Equal => {} // nothing needed!
        }

        Ok(&mut tlv_data[value_start..new_value_end])
    }

    /// Allocate the given number of bytes for the given variable-length
    /// extension and write its contents into the TLV buffer.
    ///
    /// This can only be used for variable-sized types, such as `String` or
    /// `Vec`. `Pod` types must use `init_extension`
    fn init_variable_len_extension<V: Extension + VariableLenPack>(
        &mut self,
        extension: &V,
        overwrite: bool,
    ) -> Result<(), ProgramError> {
        let data = self.alloc::<V>(extension.get_packed_len()?, overwrite)?;
        extension.pack_into_slice(data)
    }

    /// Allocate some space for the extension in the TLV data
    fn alloc<V: Extension>(
        &mut self,
        length: usize,
        overwrite: bool,
    ) -> Result<&mut [u8], ProgramError> {
        if V::TYPE.get_account_type() != S::ACCOUNT_TYPE {
            return Err(ProgramError::InvalidAccountData);
        }
        let tlv_data = self.get_tlv_data_mut();
        let TlvIndices {
            type_start,
            length_start,
            value_start,
        } = get_extension_indices::<V>(tlv_data, true)?;

        if tlv_data[type_start..].len() < add_type_and_length_to_len(length) {
            return Err(ProgramError::InvalidAccountData);
        }
        let extension_type = ExtensionType::try_from(&tlv_data[type_start..length_start])?;

        if extension_type == ExtensionType::Uninitialized || overwrite {
            // write extension type
            let extension_type_array: [u8; 2] = V::TYPE.into();
            let extension_type_ref = &mut tlv_data[type_start..length_start];
            extension_type_ref.copy_from_slice(&extension_type_array);
            // write length
            let length_ref =
                pod_from_bytes_mut::<Length>(&mut tlv_data[length_start..value_start])?;

            // check that the length is the same if we're doing an alloc
            // with overwrite, otherwise a realloc should be done
            if overwrite && extension_type == V::TYPE && usize::from(*length_ref) != length {
                return Err(TokenError::InvalidLengthForAlloc.into());
            }

            *length_ref = Length::try_from(length)?;

            let value_end = value_start.saturating_add(length);
            Ok(&mut tlv_data[value_start..value_end])
        } else {
            // extension is already initialized, but no overwrite permission
            Err(TokenError::ExtensionAlreadyInitialized.into())
        }
    }

    /// If `extension_type` is an Account-associated ExtensionType that requires
    /// initialization on InitializeAccount, this method packs the default
    /// relevant Extension of an ExtensionType into an open slot if not
    /// already found in the data buffer, otherwise overwrites the
    /// existing extension with the default state. For all other ExtensionTypes,
    /// this is a no-op.
    fn init_account_extension_from_type(
        &mut self,
        extension_type: ExtensionType,
    ) -> Result<(), ProgramError> {
        if extension_type.get_account_type() != AccountType::Account {
            return Ok(());
        }
        match extension_type {
            ExtensionType::TransferFeeAmount => {
                self.init_extension::<TransferFeeAmount>(true).map(|_| ())
            }
            ExtensionType::ImmutableOwner => {
                self.init_extension::<ImmutableOwner>(true).map(|_| ())
            }
            ExtensionType::NonTransferableAccount => self
                .init_extension::<NonTransferableAccount>(true)
                .map(|_| ()),
            ExtensionType::TransferHookAccount => {
                self.init_extension::<TransferHookAccount>(true).map(|_| ())
            }
            // ConfidentialTransfers are currently opt-in only, so this is a no-op for extra safety
            // on InitializeAccount
            ExtensionType::ConfidentialTransferAccount => Ok(()),
            #[cfg(test)]
            ExtensionType::AccountPaddingTest => {
                self.init_extension::<AccountPaddingTest>(true).map(|_| ())
            }
            _ => unreachable!(),
        }
    }

    /// Write the account type into the buffer, done during the base
    /// state initialization
    /// Noops if there is no room for an extension in the account, needed for
    /// pure base mints / accounts.
    fn init_account_type(&mut self) -> Result<(), ProgramError> {
        let first_extension_type = self.get_first_extension_type()?;
        let account_type = self.get_account_type_mut();
        if !account_type.is_empty() {
            if let Some(extension_type) = first_extension_type {
                let account_type = extension_type.get_account_type();
                if account_type != S::ACCOUNT_TYPE {
                    return Err(TokenError::ExtensionBaseMismatch.into());
                }
            }
            account_type[0] = S::ACCOUNT_TYPE.into();
        }
        Ok(())
    }

    /// Check that the account type on the account (if initialized) matches the
    /// account type for any extensions initialized on the TLV data
    fn check_account_type_matches_extension_type(&self) -> Result<(), ProgramError> {
        if let Some(extension_type) = self.get_first_extension_type()? {
            let account_type = extension_type.get_account_type();
            if account_type != S::ACCOUNT_TYPE {
                return Err(TokenError::ExtensionBaseMismatch.into());
            }
        }
        Ok(())
    }
}

/// Encapsulates mutable base state data (mint or account) with possible
/// extensions
#[derive(Debug, PartialEq)]
pub struct StateWithExtensionsMut<'data, S: BaseState> {
    /// Unpacked base data
    pub base: S,
    /// Raw base data
    base_data: &'data mut [u8],
    /// Writable account type
    account_type: &'data mut [u8],
    /// Slice of data containing all TLV data, deserialized on demand
    tlv_data: &'data mut [u8],
}
impl<'data, S: BaseState + Pack> StateWithExtensionsMut<'data, S> {
    /// Unpack base state, leaving the extension data as a mutable slice
    ///
    /// Fails if the base state is not initialized.
    pub fn unpack(input: &'data mut [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at_mut(S::SIZE_OF);
        let base = S::unpack(base_data)?;
        let (account_type, tlv_data) = unpack_type_and_tlv_data_mut::<S>(rest)?;
        Ok(Self {
            base,
            base_data,
            account_type,
            tlv_data,
        })
    }

    /// Unpack an uninitialized base state, leaving the extension data as a
    /// mutable slice
    ///
    /// Fails if the base state has already been initialized.
    pub fn unpack_uninitialized(input: &'data mut [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at_mut(S::SIZE_OF);
        let base = S::unpack_unchecked(base_data)?;
        if base.is_initialized() {
            return Err(TokenError::AlreadyInUse.into());
        }
        let (account_type, tlv_data) = unpack_uninitialized_type_and_tlv_data_mut::<S>(rest)?;
        let state = Self {
            base,
            base_data,
            account_type,
            tlv_data,
        };
        state.check_account_type_matches_extension_type()?;
        Ok(state)
    }

    /// Packs base state data into the base data portion
    pub fn pack_base(&mut self) {
        S::pack_into_slice(&self.base, self.base_data);
    }
}
impl<'a, S: BaseState> BaseStateWithExtensions<S> for StateWithExtensionsMut<'a, S> {
    fn get_tlv_data(&self) -> &[u8] {
        self.tlv_data
    }
}
impl<'a, S: BaseState> BaseStateWithExtensionsMut<S> for StateWithExtensionsMut<'a, S> {
    fn get_tlv_data_mut(&mut self) -> &mut [u8] {
        self.tlv_data
    }
    fn get_account_type_mut(&mut self) -> &mut [u8] {
        self.account_type
    }
}

/// Encapsulates mutable base state data (mint or account) with possible
/// extensions, where the base state is Pod for zero-copy serde.
#[derive(Debug, PartialEq)]
pub struct PodStateWithExtensionsMut<'data, S: BaseState> {
    /// Unpacked base data
    pub base: &'data mut S,
    /// Writable account type
    account_type: &'data mut [u8],
    /// Slice of data containing all TLV data, deserialized on demand
    tlv_data: &'data mut [u8],
}
impl<'data, S: BaseState + Pod> PodStateWithExtensionsMut<'data, S> {
    /// Unpack base state, leaving the extension data as a mutable slice
    ///
    /// Fails if the base state is not initialized.
    pub fn unpack(input: &'data mut [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at_mut(S::SIZE_OF);
        let base = pod_from_bytes_mut::<S>(base_data)?;
        if !base.is_initialized() {
            Err(ProgramError::UninitializedAccount)
        } else {
            let (account_type, tlv_data) = unpack_type_and_tlv_data_mut::<S>(rest)?;
            Ok(Self {
                base,
                account_type,
                tlv_data,
            })
        }
    }

    /// Unpack an uninitialized base state, leaving the extension data as a
    /// mutable slice
    ///
    /// Fails if the base state has already been initialized.
    pub fn unpack_uninitialized(input: &'data mut [u8]) -> Result<Self, ProgramError> {
        check_min_len_and_not_multisig(input, S::SIZE_OF)?;
        let (base_data, rest) = input.split_at_mut(S::SIZE_OF);
        let base = pod_from_bytes_mut::<S>(base_data)?;
        if base.is_initialized() {
            return Err(TokenError::AlreadyInUse.into());
        }
        let (account_type, tlv_data) = unpack_uninitialized_type_and_tlv_data_mut::<S>(rest)?;
        let state = Self {
            base,
            account_type,
            tlv_data,
        };
        state.check_account_type_matches_extension_type()?;
        Ok(state)
    }
}

impl<'a, S: BaseState> BaseStateWithExtensions<S> for PodStateWithExtensionsMut<'a, S> {
    fn get_tlv_data(&self) -> &[u8] {
        self.tlv_data
    }
}
impl<'a, S: BaseState> BaseStateWithExtensionsMut<S> for PodStateWithExtensionsMut<'a, S> {
    fn get_tlv_data_mut(&mut self) -> &mut [u8] {
        self.tlv_data
    }
    fn get_account_type_mut(&mut self) -> &mut [u8] {
        self.account_type
    }
}

fn unpack_tlv_data<S: BaseState>(rest: &[u8]) -> Result<&[u8], ProgramError> {
    if let Some((account_type_index, tlv_start_index)) = type_and_tlv_indices::<S>(rest)? {
        // type_and_tlv_indices() checks that returned indexes are within range
        let account_type = AccountType::try_from(rest[account_type_index])
            .map_err(|_| ProgramError::InvalidAccountData)?;
        check_account_type::<S>(account_type)?;
        Ok(&rest[tlv_start_index..])
    } else {
        Ok(&[])
    }
}

fn unpack_type_and_tlv_data_with_check_mut<
    S: BaseState,
    F: Fn(AccountType) -> Result<(), ProgramError>,
>(
    rest: &mut [u8],
    check_fn: F,
) -> Result<(&mut [u8], &mut [u8]), ProgramError> {
    if let Some((account_type_index, tlv_start_index)) = type_and_tlv_indices::<S>(rest)? {
        // type_and_tlv_indices() checks that returned indexes are within range
        let account_type = AccountType::try_from(rest[account_type_index])
            .map_err(|_| ProgramError::InvalidAccountData)?;
        check_fn(account_type)?;
        let (account_type, tlv_data) = rest.split_at_mut(tlv_start_index);
        Ok((
            &mut account_type[account_type_index..tlv_start_index],
            tlv_data,
        ))
    } else {
        Ok((&mut [], &mut []))
    }
}

fn unpack_type_and_tlv_data_mut<S: BaseState>(
    rest: &mut [u8],
) -> Result<(&mut [u8], &mut [u8]), ProgramError> {
    unpack_type_and_tlv_data_with_check_mut::<S, _>(rest, check_account_type::<S>)
}

fn unpack_uninitialized_type_and_tlv_data_mut<S: BaseState>(
    rest: &mut [u8],
) -> Result<(&mut [u8], &mut [u8]), ProgramError> {
    unpack_type_and_tlv_data_with_check_mut::<S, _>(rest, |account_type| {
        if account_type != AccountType::Uninitialized {
            Err(ProgramError::InvalidAccountData)
        } else {
            Ok(())
        }
    })
}

/// If AccountType is uninitialized, set it to the BaseState's ACCOUNT_TYPE;
/// if AccountType is already set, check is set correctly for BaseState
/// This method assumes that the `base_data` has already been packed with data
/// of the desired type.
pub fn set_account_type<S: BaseState>(input: &mut [u8]) -> Result<(), ProgramError> {
    check_min_len_and_not_multisig(input, S::SIZE_OF)?;
    let (base_data, rest) = input.split_at_mut(S::SIZE_OF);
    if S::ACCOUNT_TYPE == AccountType::Account && !is_initialized_account(base_data)? {
        return Err(ProgramError::InvalidAccountData);
    }
    if let Some((account_type_index, _tlv_start_index)) = type_and_tlv_indices::<S>(rest)? {
        let mut account_type = AccountType::try_from(rest[account_type_index])
            .map_err(|_| ProgramError::InvalidAccountData)?;
        if account_type == AccountType::Uninitialized {
            rest[account_type_index] = S::ACCOUNT_TYPE.into();
            account_type = S::ACCOUNT_TYPE;
        }
        check_account_type::<S>(account_type)?;
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

/// Different kinds of accounts. Note that `Mint`, `Account`, and `Multisig`
/// types are determined exclusively by the size of the account, and are not
/// included in the account data. `AccountType` is only included if extensions
/// have been initialized.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, TryFromPrimitive, IntoPrimitive)]
pub enum AccountType {
    /// Marker for 0 data
    Uninitialized,
    /// Mint account with additional extensions
    Mint,
    /// Token holding account with additional extensions
    Account,
}
impl Default for AccountType {
    fn default() -> Self {
        Self::Uninitialized
    }
}

/// Extensions that can be applied to mints or accounts.  Mint extensions must
/// only be applied to mint accounts, and account extensions must only be
/// applied to token holding accounts.
#[repr(u16)]
#[cfg_attr(feature = "serde-traits", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde-traits", serde(rename_all = "camelCase"))]
#[derive(Clone, Copy, Debug, PartialEq, TryFromPrimitive, IntoPrimitive)]
pub enum ExtensionType {
    /// Used as padding if the account size would otherwise be 355, same as a
    /// multisig
    Uninitialized,
    /// Includes transfer fee rate info and accompanying authorities to withdraw
    /// and set the fee
    TransferFeeConfig,
    /// Includes withheld transfer fees
    TransferFeeAmount,
    /// Includes an optional mint close authority
    MintCloseAuthority,
    /// Auditor configuration for confidential transfers
    ConfidentialTransferMint,
    /// State for confidential transfers
    ConfidentialTransferAccount,
    /// Specifies the default Account::state for new Accounts
    DefaultAccountState,
    /// Indicates that the Account owner authority cannot be changed
    ImmutableOwner,
    /// Require inbound transfers to have memo
    MemoTransfer,
    /// Indicates that the tokens from this mint can't be transferred
    NonTransferable,
    /// Tokens accrue interest over time,
    InterestBearingConfig,
    /// Locks privileged token operations from happening via CPI
    CpiGuard,
    /// Includes an optional permanent delegate
    PermanentDelegate,
    /// Indicates that the tokens in this account belong to a non-transferable
    /// mint
    NonTransferableAccount,
    /// Mint requires a CPI to a program implementing the "transfer hook"
    /// interface
    TransferHook,
    /// Indicates that the tokens in this account belong to a mint with a
    /// transfer hook
    TransferHookAccount,
    /// Includes encrypted withheld fees and the encryption public that they are
    /// encrypted under
    ConfidentialTransferFeeConfig,
    /// Includes confidential withheld transfer fees
    ConfidentialTransferFeeAmount,
    /// Mint contains a pointer to another account (or the same account) that
    /// holds metadata
    MetadataPointer,
    /// Mint contains token-metadata
    TokenMetadata,
    /// Mint contains a pointer to another account (or the same account) that
    /// holds group configurations
    GroupPointer,
    /// Mint contains token group configurations
    TokenGroup,
    /// Mint contains a pointer to another account (or the same account) that
    /// holds group member configurations
    GroupMemberPointer,
    /// Mint contains token group member configurations
    TokenGroupMember,
    /// Test variable-length mint extension
    #[cfg(test)]
    VariableLenMintTest = u16::MAX - 2,
    /// Padding extension used to make an account exactly Multisig::LEN, used
    /// for testing
    #[cfg(test)]
    AccountPaddingTest,
    /// Padding extension used to make a mint exactly Multisig::LEN, used for
    /// testing
    #[cfg(test)]
    MintPaddingTest,
}
impl TryFrom<&[u8]> for ExtensionType {
    type Error = ProgramError;
    fn try_from(a: &[u8]) -> Result<Self, Self::Error> {
        Self::try_from(u16::from_le_bytes(
            a.try_into().map_err(|_| ProgramError::InvalidAccountData)?,
        ))
        .map_err(|_| ProgramError::InvalidAccountData)
    }
}
impl From<ExtensionType> for [u8; 2] {
    fn from(a: ExtensionType) -> Self {
        u16::from(a).to_le_bytes()
    }
}
impl ExtensionType {
    /// Returns true if the given extension type is sized
    ///
    /// Most extension types should be sized, so any variable-length extension
    /// types should be added here by hand
    const fn sized(&self) -> bool {
        match self {
            ExtensionType::TokenMetadata => false,
            #[cfg(test)]
            ExtensionType::VariableLenMintTest => false,
            _ => true,
        }
    }

    /// Get the data length of the type associated with the enum
    ///
    /// Fails if the extension type has a variable length
    fn try_get_type_len(&self) -> Result<usize, ProgramError> {
        if !self.sized() {
            return Err(ProgramError::InvalidArgument);
        }
        Ok(match self {
            ExtensionType::Uninitialized => 0,
            ExtensionType::TransferFeeConfig => pod_get_packed_len::<TransferFeeConfig>(),
            ExtensionType::TransferFeeAmount => pod_get_packed_len::<TransferFeeAmount>(),
            ExtensionType::MintCloseAuthority => pod_get_packed_len::<MintCloseAuthority>(),
            ExtensionType::ImmutableOwner => pod_get_packed_len::<ImmutableOwner>(),
            ExtensionType::ConfidentialTransferMint => {
                pod_get_packed_len::<ConfidentialTransferMint>()
            }
            ExtensionType::ConfidentialTransferAccount => {
                pod_get_packed_len::<ConfidentialTransferAccount>()
            }
            ExtensionType::DefaultAccountState => pod_get_packed_len::<DefaultAccountState>(),
            ExtensionType::MemoTransfer => pod_get_packed_len::<MemoTransfer>(),
            ExtensionType::NonTransferable => pod_get_packed_len::<NonTransferable>(),
            ExtensionType::InterestBearingConfig => pod_get_packed_len::<InterestBearingConfig>(),
            ExtensionType::CpiGuard => pod_get_packed_len::<CpiGuard>(),
            ExtensionType::PermanentDelegate => pod_get_packed_len::<PermanentDelegate>(),
            ExtensionType::NonTransferableAccount => pod_get_packed_len::<NonTransferableAccount>(),
            ExtensionType::TransferHook => pod_get_packed_len::<TransferHook>(),
            ExtensionType::TransferHookAccount => pod_get_packed_len::<TransferHookAccount>(),
            ExtensionType::ConfidentialTransferFeeConfig => {
                pod_get_packed_len::<ConfidentialTransferFeeConfig>()
            }
            ExtensionType::ConfidentialTransferFeeAmount => {
                pod_get_packed_len::<ConfidentialTransferFeeAmount>()
            }
            ExtensionType::MetadataPointer => pod_get_packed_len::<MetadataPointer>(),
            ExtensionType::TokenMetadata => unreachable!(),
            ExtensionType::GroupPointer => pod_get_packed_len::<GroupPointer>(),
            ExtensionType::TokenGroup => pod_get_packed_len::<TokenGroup>(),
            ExtensionType::GroupMemberPointer => pod_get_packed_len::<GroupMemberPointer>(),
            ExtensionType::TokenGroupMember => pod_get_packed_len::<TokenGroupMember>(),
            #[cfg(test)]
            ExtensionType::AccountPaddingTest => pod_get_packed_len::<AccountPaddingTest>(),
            #[cfg(test)]
            ExtensionType::MintPaddingTest => pod_get_packed_len::<MintPaddingTest>(),
            #[cfg(test)]
            ExtensionType::VariableLenMintTest => unreachable!(),
        })
    }

    /// Get the TLV length for an ExtensionType
    ///
    /// Fails if the extension type has a variable length
    fn try_get_tlv_len(&self) -> Result<usize, ProgramError> {
        Ok(add_type_and_length_to_len(self.try_get_type_len()?))
    }

    /// Get the TLV length for a set of ExtensionTypes
    ///
    /// Fails if any of the extension types has a variable length
    fn try_get_total_tlv_len(extension_types: &[Self]) -> Result<usize, ProgramError> {
        // dedupe extensions
        let mut extensions = vec![];
        for extension_type in extension_types {
            if !extensions.contains(&extension_type) {
                extensions.push(extension_type);
            }
        }
        extensions.iter().map(|e| e.try_get_tlv_len()).sum()
    }

    /// Get the required account data length for the given ExtensionTypes
    ///
    /// Fails if any of the extension types has a variable length
    pub fn try_calculate_account_len<S: BaseState>(
        extension_types: &[Self],
    ) -> Result<usize, ProgramError> {
        if extension_types.is_empty() {
            Ok(S::SIZE_OF)
        } else {
            let extension_size = Self::try_get_total_tlv_len(extension_types)?;
            let total_len = extension_size.saturating_add(BASE_ACCOUNT_AND_TYPE_LENGTH);
            Ok(adjust_len_for_multisig(total_len))
        }
    }

    /// Get the associated account type
    pub fn get_account_type(&self) -> AccountType {
        match self {
            ExtensionType::Uninitialized => AccountType::Uninitialized,
            ExtensionType::TransferFeeConfig
            | ExtensionType::MintCloseAuthority
            | ExtensionType::ConfidentialTransferMint
            | ExtensionType::DefaultAccountState
            | ExtensionType::NonTransferable
            | ExtensionType::InterestBearingConfig
            | ExtensionType::PermanentDelegate
            | ExtensionType::TransferHook
            | ExtensionType::ConfidentialTransferFeeConfig
            | ExtensionType::MetadataPointer
            | ExtensionType::TokenMetadata
            | ExtensionType::GroupPointer
            | ExtensionType::TokenGroup
            | ExtensionType::GroupMemberPointer
            | ExtensionType::TokenGroupMember => AccountType::Mint,
            ExtensionType::ImmutableOwner
            | ExtensionType::TransferFeeAmount
            | ExtensionType::ConfidentialTransferAccount
            | ExtensionType::MemoTransfer
            | ExtensionType::NonTransferableAccount
            | ExtensionType::TransferHookAccount
            | ExtensionType::CpiGuard
            | ExtensionType::ConfidentialTransferFeeAmount => AccountType::Account,
            #[cfg(test)]
            ExtensionType::VariableLenMintTest => AccountType::Mint,
            #[cfg(test)]
            ExtensionType::AccountPaddingTest => AccountType::Account,
            #[cfg(test)]
            ExtensionType::MintPaddingTest => AccountType::Mint,
        }
    }

    /// Based on a set of AccountType::Mint ExtensionTypes, get the list of
    /// AccountType::Account ExtensionTypes required on InitializeAccount
    pub fn get_required_init_account_extensions(mint_extension_types: &[Self]) -> Vec<Self> {
        let mut account_extension_types = vec![];
        for extension_type in mint_extension_types {
            match extension_type {
                ExtensionType::TransferFeeConfig => {
                    account_extension_types.push(ExtensionType::TransferFeeAmount);
                }
                ExtensionType::NonTransferable => {
                    account_extension_types.push(ExtensionType::NonTransferableAccount);
                    account_extension_types.push(ExtensionType::ImmutableOwner);
                }
                ExtensionType::TransferHook => {
                    account_extension_types.push(ExtensionType::TransferHookAccount);
                }
                #[cfg(test)]
                ExtensionType::MintPaddingTest => {
                    account_extension_types.push(ExtensionType::AccountPaddingTest);
                }
                _ => {}
            }
        }
        account_extension_types
    }

    /// Check for invalid combination of mint extensions
    pub fn check_for_invalid_mint_extension_combinations(
        mint_extension_types: &[Self],
    ) -> Result<(), TokenError> {
        let mut transfer_fee_config = false;
        let mut confidential_transfer_mint = false;
        let mut confidential_transfer_fee_config = false;

        for extension_type in mint_extension_types {
            match extension_type {
                ExtensionType::TransferFeeConfig => transfer_fee_config = true,
                ExtensionType::ConfidentialTransferMint => confidential_transfer_mint = true,
                ExtensionType::ConfidentialTransferFeeConfig => {
                    confidential_transfer_fee_config = true
                }
                _ => (),
            }
        }

        if confidential_transfer_fee_config && !(transfer_fee_config && confidential_transfer_mint)
        {
            return Err(TokenError::InvalidExtensionCombination);
        }

        if transfer_fee_config && confidential_transfer_mint && !confidential_transfer_fee_config {
            return Err(TokenError::InvalidExtensionCombination);
        }

        Ok(())
    }
}

/// Trait for base states, specifying the associated enum
pub trait BaseState: PackedSizeOf + IsInitialized {
    /// Associated extension type enum, checked at the start of TLV entries
    const ACCOUNT_TYPE: AccountType;
}
impl BaseState for Account {
    const ACCOUNT_TYPE: AccountType = AccountType::Account;
}
impl BaseState for Mint {
    const ACCOUNT_TYPE: AccountType = AccountType::Mint;
}
impl BaseState for PodAccount {
    const ACCOUNT_TYPE: AccountType = AccountType::Account;
}
impl BaseState for PodMint {
    const ACCOUNT_TYPE: AccountType = AccountType::Mint;
}

/// Trait to be implemented by all extension states, specifying which extension
/// and account type they are associated with
pub trait Extension {
    /// Associated extension type enum, checked at the start of TLV entries
    const TYPE: ExtensionType;
}

/// Padding a mint account to be exactly Multisig::LEN.
/// We need to pad 185 bytes, since Multisig::LEN = 355, Account::LEN = 165,
/// size_of AccountType = 1, size_of ExtensionType = 2, size_of Length = 2.
/// 355 - 165 - 1 - 2 - 2 = 185
#[cfg(test)]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct MintPaddingTest {
    /// Largest value under 185 that implements Pod
    pub padding1: [u8; 128],
    /// Largest value under 57 that implements Pod
    pub padding2: [u8; 48],
    /// Exact value needed to finish the padding
    pub padding3: [u8; 9],
}
#[cfg(test)]
impl Extension for MintPaddingTest {
    const TYPE: ExtensionType = ExtensionType::MintPaddingTest;
}
#[cfg(test)]
impl Default for MintPaddingTest {
    fn default() -> Self {
        Self {
            padding1: [1; 128],
            padding2: [2; 48],
            padding3: [3; 9],
        }
    }
}
/// Account version of the MintPadding
#[cfg(test)]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
pub struct AccountPaddingTest(MintPaddingTest);
#[cfg(test)]
impl Extension for AccountPaddingTest {
    const TYPE: ExtensionType = ExtensionType::AccountPaddingTest;
}

/// Packs a fixed-length extension into a TLV space
///
/// This function reallocates the account as needed to accommodate for the
/// change in space.
///
/// If the extension already exists, it will overwrite the existing extension
/// if `overwrite` is `true`, otherwise it will return an error.
///
/// If the extension does not exist, it will reallocate the account and write
/// the extension into the TLV buffer.
///
/// NOTE: Since this function deals with fixed-size extensions, it does not
/// handle _decreasing_ the size of an account's data buffer, like the function
/// `alloc_and_serialize_variable_len_extension` does.
pub(crate) fn alloc_and_serialize<S: BaseState + Pod, V: Default + Extension + Pod>(
    account_info: &AccountInfo,
    new_extension: &V,
    overwrite: bool,
) -> Result<(), ProgramError> {
    let previous_account_len = account_info.try_data_len()?;
    let new_account_len = {
        let data = account_info.try_borrow_data()?;
        let state = PodStateWithExtensions::<S>::unpack(&data)?;
        state.try_get_new_account_len::<V>()?
    };

    // Realloc the account first, if needed
    if new_account_len > previous_account_len {
        account_info.realloc(new_account_len, false)?;
    }
    let mut buffer = account_info.try_borrow_mut_data()?;
    if previous_account_len <= BASE_ACCOUNT_LENGTH {
        set_account_type::<S>(*buffer)?;
    }
    let mut state = PodStateWithExtensionsMut::<S>::unpack(&mut buffer)?;

    // Write the extension
    let extension = state.init_extension::<V>(overwrite)?;
    *extension = *new_extension;

    Ok(())
}

/// Packs a variable-length extension into a TLV space
///
/// This function reallocates the account as needed to accommodate for the
/// change in space, then reallocates in the TLV buffer, and finally writes the
/// bytes.
///
/// NOTE: Unlike the `reallocate` instruction, this function will reduce the
/// size of an account if it has too many bytes allocated for the given value.
pub(crate) fn alloc_and_serialize_variable_len_extension<
    S: BaseState + Pod,
    V: Extension + VariableLenPack,
>(
    account_info: &AccountInfo,
    new_extension: &V,
    overwrite: bool,
) -> Result<(), ProgramError> {
    let previous_account_len = account_info.try_data_len()?;
    let (new_account_len, extension_already_exists) = {
        let data = account_info.try_borrow_data()?;
        let state = PodStateWithExtensions::<S>::unpack(&data)?;
        let new_account_len =
            state.try_get_new_account_len_for_variable_len_extension(new_extension)?;
        let extension_already_exists = state.get_extension_bytes::<V>().is_ok();
        (new_account_len, extension_already_exists)
    };

    if extension_already_exists && !overwrite {
        return Err(TokenError::ExtensionAlreadyInitialized.into());
    }

    if previous_account_len < new_account_len {
        // account size increased, so realloc the account, then the TLV entry, then
        // write data
        account_info.realloc(new_account_len, false)?;
        let mut buffer = account_info.try_borrow_mut_data()?;
        if extension_already_exists {
            let mut state = PodStateWithExtensionsMut::<S>::unpack(&mut buffer)?;
            state.realloc_variable_len_extension(new_extension)?;
        } else {
            if previous_account_len <= BASE_ACCOUNT_LENGTH {
                set_account_type::<S>(*buffer)?;
            }
            // now alloc in the TLV buffer and write the data
            let mut state = PodStateWithExtensionsMut::<S>::unpack(&mut buffer)?;
            state.init_variable_len_extension(new_extension, false)?;
        }
    } else {
        // do it backwards otherwise, write the state, realloc TLV, then the account
        let mut buffer = account_info.try_borrow_mut_data()?;
        let mut state = PodStateWithExtensionsMut::<S>::unpack(&mut buffer)?;
        if extension_already_exists {
            state.realloc_variable_len_extension(new_extension)?;
        } else {
            // this situation can happen if we have an overallocated buffer
            state.init_variable_len_extension(new_extension, false)?;
        }

        let removed_bytes = previous_account_len
            .checked_sub(new_account_len)
            .ok_or(ProgramError::AccountDataTooSmall)?;
        if removed_bytes > 0 {
            // this is probably fine, but be safe and avoid invalidating references
            drop(buffer);
            account_info.realloc(new_account_len, false)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod test {
    use {
        super::*,
        crate::{
            pod::test::{TEST_POD_ACCOUNT, TEST_POD_MINT},
            state::test::{TEST_ACCOUNT_SLICE, TEST_MINT_SLICE},
        },
        bytemuck::Pod,
        solana_program::{
            account_info::{Account as GetAccount, IntoAccountInfo},
            clock::Epoch,
            entrypoint::MAX_PERMITTED_DATA_INCREASE,
            pubkey::Pubkey,
        },
        spl_pod::{
            bytemuck::pod_bytes_of, optional_keys::OptionalNonZeroPubkey, primitives::PodU64,
        },
        transfer_fee::test::test_transfer_fee_config,
    };

    /// Test fixed-length struct
    #[repr(C)]
    #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
    struct FixedLenMintTest {
        data: [u8; 8],
    }
    impl Extension for FixedLenMintTest {
        const TYPE: ExtensionType = ExtensionType::MintPaddingTest;
    }

    /// Test variable-length struct
    #[derive(Clone, Debug, PartialEq)]
    struct VariableLenMintTest {
        data: Vec<u8>,
    }
    impl Extension for VariableLenMintTest {
        const TYPE: ExtensionType = ExtensionType::VariableLenMintTest;
    }
    impl VariableLenPack for VariableLenMintTest {
        fn pack_into_slice(&self, dst: &mut [u8]) -> Result<(), ProgramError> {
            let data_start = size_of::<u64>();
            let end = data_start + self.data.len();
            if dst.len() < end {
                Err(ProgramError::InvalidAccountData)
            } else {
                dst[..data_start].copy_from_slice(&self.data.len().to_le_bytes());
                dst[data_start..end].copy_from_slice(&self.data);
                Ok(())
            }
        }
        fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError> {
            let data_start = size_of::<u64>();
            let length = u64::from_le_bytes(src[..data_start].try_into().unwrap()) as usize;
            if src[data_start..data_start + length].len() != length {
                return Err(ProgramError::InvalidAccountData);
            }
            let data = Vec::from(&src[data_start..data_start + length]);
            Ok(Self { data })
        }
        fn get_packed_len(&self) -> Result<usize, ProgramError> {
            Ok(size_of::<u64>().saturating_add(self.data.len()))
        }
    }

    const MINT_WITH_EXTENSION: &[u8] = &[
        1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 42, 0, 0, 0, 0, 0, 0, 0, 7, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // base mint
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // padding
        1, // account type
        3, 0, // extension type
        32, 0, // length
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, // data
    ];

    #[test]
    fn unpack_opaque_buffer() {
        let state = PodStateWithExtensions::<PodMint>::unpack(MINT_WITH_EXTENSION).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);
        let extension = state.get_extension::<MintCloseAuthority>().unwrap();
        let close_authority =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([1; 32]))).unwrap();
        assert_eq!(extension.close_authority, close_authority);
        assert_eq!(
            state.get_extension::<TransferFeeConfig>(),
            Err(ProgramError::InvalidAccountData)
        );
        assert_eq!(
            PodStateWithExtensions::<PodAccount>::unpack(MINT_WITH_EXTENSION),
            Err(ProgramError::UninitializedAccount)
        );

        let state = PodStateWithExtensions::<PodMint>::unpack(TEST_MINT_SLICE).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);

        let mut test_mint = TEST_MINT_SLICE.to_vec();
        let state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut test_mint).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);
    }

    #[test]
    fn fail_unpack_opaque_buffer() {
        // input buffer too small
        let mut buffer = vec![0, 3];
        assert_eq!(
            PodStateWithExtensions::<PodMint>::unpack(&buffer),
            Err(ProgramError::InvalidAccountData)
        );
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer),
            Err(ProgramError::InvalidAccountData)
        );
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer),
            Err(ProgramError::InvalidAccountData)
        );

        // tweak the account type
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[BASE_ACCOUNT_LENGTH] = 3;
        assert_eq!(
            PodStateWithExtensions::<PodMint>::unpack(&buffer),
            Err(ProgramError::InvalidAccountData)
        );

        // clear the mint initialized byte
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[45] = 0;
        assert_eq!(
            PodStateWithExtensions::<PodMint>::unpack(&buffer),
            Err(ProgramError::UninitializedAccount)
        );

        // tweak the padding
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[PodMint::SIZE_OF] = 100;
        assert_eq!(
            PodStateWithExtensions::<PodMint>::unpack(&buffer),
            Err(ProgramError::InvalidAccountData)
        );

        // tweak the extension type
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[BASE_ACCOUNT_LENGTH + 1] = 2;
        let state = PodStateWithExtensions::<PodMint>::unpack(&buffer).unwrap();
        assert_eq!(
            state.get_extension::<TransferFeeConfig>(),
            Err(ProgramError::Custom(
                TokenError::ExtensionTypeMismatch as u32
            ))
        );

        // tweak the length, too big
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[BASE_ACCOUNT_LENGTH + 3] = 100;
        let state = PodStateWithExtensions::<PodMint>::unpack(&buffer).unwrap();
        assert_eq!(
            state.get_extension::<TransferFeeConfig>(),
            Err(ProgramError::InvalidAccountData)
        );

        // tweak the length, too small
        let mut buffer = MINT_WITH_EXTENSION.to_vec();
        buffer[BASE_ACCOUNT_LENGTH + 3] = 10;
        let state = PodStateWithExtensions::<PodMint>::unpack(&buffer).unwrap();
        assert_eq!(
            state.get_extension::<TransferFeeConfig>(),
            Err(ProgramError::InvalidAccountData)
        );

        // data buffer is too small
        let buffer = &MINT_WITH_EXTENSION[..MINT_WITH_EXTENSION.len() - 1];
        let state = PodStateWithExtensions::<PodMint>::unpack(buffer).unwrap();
        assert_eq!(
            state.get_extension::<MintCloseAuthority>(),
            Err(ProgramError::InvalidAccountData)
        );
    }

    #[test]
    fn get_extension_types_with_opaque_buffer() {
        // incorrect due to the length
        assert_eq!(
            get_tlv_data_info(&[1, 0, 1, 1]).unwrap_err(),
            ProgramError::InvalidAccountData,
        );
        // incorrect due to the huge enum number
        assert_eq!(
            get_tlv_data_info(&[0, 1, 0, 0]).unwrap_err(),
            ProgramError::InvalidAccountData,
        );
        // correct due to the good enum number and zero length
        assert_eq!(
            get_tlv_data_info(&[1, 0, 0, 0]).unwrap(),
            TlvDataInfo {
                extension_types: vec![ExtensionType::try_from(1).unwrap()],
                used_len: add_type_and_length_to_len(0),
            }
        );
        // correct since it's just uninitialized data at the end
        assert_eq!(
            get_tlv_data_info(&[0, 0]).unwrap(),
            TlvDataInfo {
                extension_types: vec![],
                used_len: 0
            }
        );
    }

    #[test]
    fn mint_with_extension_pack_unpack() {
        let mint_size = ExtensionType::try_calculate_account_len::<PodMint>(&[
            ExtensionType::MintCloseAuthority,
            ExtensionType::TransferFeeConfig,
        ])
        .unwrap();
        let mut buffer = vec![0; mint_size];

        // fail unpack
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer),
            Err(ProgramError::UninitializedAccount),
        );

        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        // fail init account extension
        assert_eq!(
            state.init_extension::<TransferFeeAmount>(true),
            Err(ProgramError::InvalidAccountData),
        );

        // success write extension
        let close_authority =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([1; 32]))).unwrap();
        let extension = state.init_extension::<MintCloseAuthority>(true).unwrap();
        extension.close_authority = close_authority;
        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[ExtensionType::MintCloseAuthority]
        );

        // fail init extension when already initialized
        assert_eq!(
            state.init_extension::<MintCloseAuthority>(false),
            Err(ProgramError::Custom(
                TokenError::ExtensionAlreadyInitialized as u32
            ))
        );

        // fail unpack as account, a mint extension was written
        assert_eq!(
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer),
            Err(ProgramError::Custom(
                TokenError::ExtensionBaseMismatch as u32
            ))
        );

        // fail unpack again, still no base data
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer.clone()),
            Err(ProgramError::UninitializedAccount),
        );

        // write base mint
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        // check raw buffer
        let mut expect = TEST_MINT_SLICE.to_vec();
        expect.extend_from_slice(&[0; BASE_ACCOUNT_LENGTH - PodMint::SIZE_OF]); // padding
        expect.push(AccountType::Mint.into());
        expect.extend_from_slice(&(ExtensionType::MintCloseAuthority as u16).to_le_bytes());
        expect
            .extend_from_slice(&(pod_get_packed_len::<MintCloseAuthority>() as u16).to_le_bytes());
        expect.extend_from_slice(&[1; 32]); // data
        expect.extend_from_slice(&[0; size_of::<ExtensionType>()]);
        expect.extend_from_slice(&[0; size_of::<Length>()]);
        expect.extend_from_slice(&[0; size_of::<TransferFeeConfig>()]);
        assert_eq!(expect, buffer);

        // unpack uninitialized will now fail because the PodMint is now initialized
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer.clone()),
            Err(TokenError::AlreadyInUse.into()),
        );

        // check unpacking
        let mut state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();

        // update base
        *state.base = TEST_POD_MINT;
        state.base.supply = (u64::from(state.base.supply) + 100).into();

        // check unpacking
        let unpacked_extension = state.get_extension_mut::<MintCloseAuthority>().unwrap();
        assert_eq!(*unpacked_extension, MintCloseAuthority { close_authority });

        // update extension
        let close_authority = OptionalNonZeroPubkey::try_from(None).unwrap();
        unpacked_extension.close_authority = close_authority;

        // check updates are propagated
        let base = *state.base;
        let state = PodStateWithExtensions::<PodMint>::unpack(&buffer).unwrap();
        assert_eq!(state.base, &base);
        let unpacked_extension = state.get_extension::<MintCloseAuthority>().unwrap();
        assert_eq!(*unpacked_extension, MintCloseAuthority { close_authority });

        // check raw buffer
        let mut expect = vec![];
        expect.extend_from_slice(bytemuck::bytes_of(&base));
        expect.extend_from_slice(&[0; BASE_ACCOUNT_LENGTH - PodMint::SIZE_OF]); // padding
        expect.push(AccountType::Mint.into());
        expect.extend_from_slice(&(ExtensionType::MintCloseAuthority as u16).to_le_bytes());
        expect
            .extend_from_slice(&(pod_get_packed_len::<MintCloseAuthority>() as u16).to_le_bytes());
        expect.extend_from_slice(&[0; 32]);
        expect.extend_from_slice(&[0; size_of::<ExtensionType>()]);
        expect.extend_from_slice(&[0; size_of::<Length>()]);
        expect.extend_from_slice(&[0; size_of::<TransferFeeConfig>()]);
        assert_eq!(expect, buffer);

        // fail unpack as an account
        assert_eq!(
            PodStateWithExtensions::<PodAccount>::unpack(&buffer),
            Err(ProgramError::UninitializedAccount),
        );

        let mut state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();
        // init one more extension
        let mint_transfer_fee = test_transfer_fee_config();
        let new_extension = state.init_extension::<TransferFeeConfig>(true).unwrap();
        new_extension.transfer_fee_config_authority =
            mint_transfer_fee.transfer_fee_config_authority;
        new_extension.withdraw_withheld_authority = mint_transfer_fee.withdraw_withheld_authority;
        new_extension.withheld_amount = mint_transfer_fee.withheld_amount;
        new_extension.older_transfer_fee = mint_transfer_fee.older_transfer_fee;
        new_extension.newer_transfer_fee = mint_transfer_fee.newer_transfer_fee;

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[
                ExtensionType::MintCloseAuthority,
                ExtensionType::TransferFeeConfig
            ]
        );

        // check raw buffer
        let mut expect = vec![];
        expect.extend_from_slice(pod_bytes_of(&base));
        expect.extend_from_slice(&[0; BASE_ACCOUNT_LENGTH - PodMint::SIZE_OF]); // padding
        expect.push(AccountType::Mint.into());
        expect.extend_from_slice(&(ExtensionType::MintCloseAuthority as u16).to_le_bytes());
        expect
            .extend_from_slice(&(pod_get_packed_len::<MintCloseAuthority>() as u16).to_le_bytes());
        expect.extend_from_slice(&[0; 32]); // data
        expect.extend_from_slice(&(ExtensionType::TransferFeeConfig as u16).to_le_bytes());
        expect.extend_from_slice(&(pod_get_packed_len::<TransferFeeConfig>() as u16).to_le_bytes());
        expect.extend_from_slice(pod_bytes_of(&mint_transfer_fee));
        assert_eq!(expect, buffer);

        // fail to init one more extension that does not fit
        let mut state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();
        assert_eq!(
            state.init_extension::<MintPaddingTest>(true),
            Err(ProgramError::InvalidAccountData),
        );
    }

    #[test]
    fn mint_extension_any_order() {
        let mint_size = ExtensionType::try_calculate_account_len::<PodMint>(&[
            ExtensionType::MintCloseAuthority,
            ExtensionType::TransferFeeConfig,
        ])
        .unwrap();
        let mut buffer = vec![0; mint_size];

        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        // write extensions
        let close_authority =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([1; 32]))).unwrap();
        let extension = state.init_extension::<MintCloseAuthority>(true).unwrap();
        extension.close_authority = close_authority;

        let mint_transfer_fee = test_transfer_fee_config();
        let extension = state.init_extension::<TransferFeeConfig>(true).unwrap();
        extension.transfer_fee_config_authority = mint_transfer_fee.transfer_fee_config_authority;
        extension.withdraw_withheld_authority = mint_transfer_fee.withdraw_withheld_authority;
        extension.withheld_amount = mint_transfer_fee.withheld_amount;
        extension.older_transfer_fee = mint_transfer_fee.older_transfer_fee;
        extension.newer_transfer_fee = mint_transfer_fee.newer_transfer_fee;

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[
                ExtensionType::MintCloseAuthority,
                ExtensionType::TransferFeeConfig
            ]
        );

        // write base mint
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        let mut other_buffer = vec![0; mint_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut other_buffer).unwrap();

        // write base mint
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        // write extensions in a different order
        let mint_transfer_fee = test_transfer_fee_config();
        let extension = state.init_extension::<TransferFeeConfig>(true).unwrap();
        extension.transfer_fee_config_authority = mint_transfer_fee.transfer_fee_config_authority;
        extension.withdraw_withheld_authority = mint_transfer_fee.withdraw_withheld_authority;
        extension.withheld_amount = mint_transfer_fee.withheld_amount;
        extension.older_transfer_fee = mint_transfer_fee.older_transfer_fee;
        extension.newer_transfer_fee = mint_transfer_fee.newer_transfer_fee;

        let close_authority =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([1; 32]))).unwrap();
        let extension = state.init_extension::<MintCloseAuthority>(true).unwrap();
        extension.close_authority = close_authority;

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[
                ExtensionType::TransferFeeConfig,
                ExtensionType::MintCloseAuthority
            ]
        );

        // buffers are NOT the same because written in a different order
        assert_ne!(buffer, other_buffer);
        let state = PodStateWithExtensions::<PodMint>::unpack(&buffer).unwrap();
        let other_state = PodStateWithExtensions::<PodMint>::unpack(&other_buffer).unwrap();

        // BUT mint and extensions are the same
        assert_eq!(
            state.get_extension::<TransferFeeConfig>().unwrap(),
            other_state.get_extension::<TransferFeeConfig>().unwrap()
        );
        assert_eq!(
            state.get_extension::<MintCloseAuthority>().unwrap(),
            other_state.get_extension::<MintCloseAuthority>().unwrap()
        );
        assert_eq!(state.base, other_state.base);
    }

    #[test]
    fn mint_with_multisig_len() {
        let mut buffer = vec![0; Multisig::LEN];
        assert_eq!(
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer),
            Err(ProgramError::InvalidAccountData),
        );
        let mint_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MintPaddingTest])
                .unwrap();
        assert_eq!(mint_size, Multisig::LEN + size_of::<ExtensionType>());
        let mut buffer = vec![0; mint_size];

        // write base mint
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        // write padding
        let extension = state.init_extension::<MintPaddingTest>(true).unwrap();
        extension.padding1 = [1; 128];
        extension.padding2 = [1; 48];
        extension.padding3 = [1; 9];

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[ExtensionType::MintPaddingTest]
        );

        // check raw buffer
        let mut expect = TEST_MINT_SLICE.to_vec();
        expect.extend_from_slice(&[0; BASE_ACCOUNT_LENGTH - PodMint::SIZE_OF]); // padding
        expect.push(AccountType::Mint.into());
        expect.extend_from_slice(&(ExtensionType::MintPaddingTest as u16).to_le_bytes());
        expect.extend_from_slice(&(pod_get_packed_len::<MintPaddingTest>() as u16).to_le_bytes());
        expect.extend_from_slice(&vec![1; pod_get_packed_len::<MintPaddingTest>()]);
        expect.extend_from_slice(&(ExtensionType::Uninitialized as u16).to_le_bytes());
        assert_eq!(expect, buffer);
    }

    #[test]
    fn account_with_extension_pack_unpack() {
        let account_size = ExtensionType::try_calculate_account_len::<PodAccount>(&[
            ExtensionType::TransferFeeAmount,
        ])
        .unwrap();
        let mut buffer = vec![0; account_size];

        // fail unpack
        assert_eq!(
            PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer),
            Err(ProgramError::UninitializedAccount),
        );

        let mut state =
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer).unwrap();
        // fail init mint extension
        assert_eq!(
            state.init_extension::<TransferFeeConfig>(true),
            Err(ProgramError::InvalidAccountData),
        );
        // success write extension
        let withheld_amount = PodU64::from(u64::MAX);
        let extension = state.init_extension::<TransferFeeAmount>(true).unwrap();
        extension.withheld_amount = withheld_amount;

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[ExtensionType::TransferFeeAmount]
        );

        // fail unpack again, still no base data
        assert_eq!(
            PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer.clone()),
            Err(ProgramError::UninitializedAccount),
        );

        // write base account
        let mut state =
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_ACCOUNT;
        state.init_account_type().unwrap();
        let base = *state.base;

        // check raw buffer
        let mut expect = TEST_ACCOUNT_SLICE.to_vec();
        expect.push(AccountType::Account.into());
        expect.extend_from_slice(&(ExtensionType::TransferFeeAmount as u16).to_le_bytes());
        expect.extend_from_slice(&(pod_get_packed_len::<TransferFeeAmount>() as u16).to_le_bytes());
        expect.extend_from_slice(&u64::from(withheld_amount).to_le_bytes());
        assert_eq!(expect, buffer);

        // check unpacking
        let mut state = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &base);
        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[ExtensionType::TransferFeeAmount]
        );

        // update base
        *state.base = TEST_POD_ACCOUNT;
        state.base.amount = (u64::from(state.base.amount) + 100).into();

        // check unpacking
        let unpacked_extension = state.get_extension_mut::<TransferFeeAmount>().unwrap();
        assert_eq!(*unpacked_extension, TransferFeeAmount { withheld_amount });

        // update extension
        let withheld_amount = PodU64::from(u32::MAX as u64);
        unpacked_extension.withheld_amount = withheld_amount;

        // check updates are propagated
        let base = *state.base;
        let state = PodStateWithExtensions::<PodAccount>::unpack(&buffer).unwrap();
        assert_eq!(state.base, &base);
        let unpacked_extension = state.get_extension::<TransferFeeAmount>().unwrap();
        assert_eq!(*unpacked_extension, TransferFeeAmount { withheld_amount });

        // check raw buffer
        let mut expect = vec![];
        expect.extend_from_slice(pod_bytes_of(&base));
        expect.push(AccountType::Account.into());
        expect.extend_from_slice(&(ExtensionType::TransferFeeAmount as u16).to_le_bytes());
        expect.extend_from_slice(&(pod_get_packed_len::<TransferFeeAmount>() as u16).to_le_bytes());
        expect.extend_from_slice(&u64::from(withheld_amount).to_le_bytes());
        assert_eq!(expect, buffer);

        // fail unpack as a mint
        assert_eq!(
            PodStateWithExtensions::<PodMint>::unpack(&buffer),
            Err(ProgramError::InvalidAccountData),
        );
    }

    #[test]
    fn account_with_multisig_len() {
        let mut buffer = vec![0; Multisig::LEN];
        assert_eq!(
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer),
            Err(ProgramError::InvalidAccountData),
        );
        let account_size = ExtensionType::try_calculate_account_len::<PodAccount>(&[
            ExtensionType::AccountPaddingTest,
        ])
        .unwrap();
        assert_eq!(account_size, Multisig::LEN + size_of::<ExtensionType>());
        let mut buffer = vec![0; account_size];

        // write base account
        let mut state =
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_ACCOUNT;
        state.init_account_type().unwrap();

        // write padding
        let extension = state.init_extension::<AccountPaddingTest>(true).unwrap();
        extension.0.padding1 = [2; 128];
        extension.0.padding2 = [2; 48];
        extension.0.padding3 = [2; 9];

        assert_eq!(
            &state.get_extension_types().unwrap(),
            &[ExtensionType::AccountPaddingTest]
        );

        // check raw buffer
        let mut expect = TEST_ACCOUNT_SLICE.to_vec();
        expect.push(AccountType::Account.into());
        expect.extend_from_slice(&(ExtensionType::AccountPaddingTest as u16).to_le_bytes());
        expect
            .extend_from_slice(&(pod_get_packed_len::<AccountPaddingTest>() as u16).to_le_bytes());
        expect.extend_from_slice(&vec![2; pod_get_packed_len::<AccountPaddingTest>()]);
        expect.extend_from_slice(&(ExtensionType::Uninitialized as u16).to_le_bytes());
        assert_eq!(expect, buffer);
    }

    #[test]
    fn test_set_account_type() {
        // account with buffer big enough for AccountType and Extension
        let mut buffer = TEST_ACCOUNT_SLICE.to_vec();
        let needed_len = ExtensionType::try_calculate_account_len::<PodAccount>(&[
            ExtensionType::ImmutableOwner,
        ])
        .unwrap()
            - buffer.len();
        buffer.append(&mut vec![0; needed_len]);
        let err = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        set_account_type::<PodAccount>(&mut buffer).unwrap();
        // unpack is viable after manual set_account_type
        let mut state = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_ACCOUNT);
        assert_eq!(state.account_type[0], AccountType::Account as u8);
        state.init_extension::<ImmutableOwner>(true).unwrap(); // just confirming initialization works

        // account with buffer big enough for AccountType only
        let mut buffer = TEST_ACCOUNT_SLICE.to_vec();
        buffer.append(&mut vec![0; 2]);
        let err = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        set_account_type::<PodAccount>(&mut buffer).unwrap();
        // unpack is viable after manual set_account_type
        let state = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_ACCOUNT);
        assert_eq!(state.account_type[0], AccountType::Account as u8);

        // account with AccountType already set => noop
        let mut buffer = TEST_ACCOUNT_SLICE.to_vec();
        buffer.append(&mut vec![2, 0]);
        let _ = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap();
        set_account_type::<PodAccount>(&mut buffer).unwrap();
        let state = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_ACCOUNT);
        assert_eq!(state.account_type[0], AccountType::Account as u8);

        // account with wrong AccountType fails
        let mut buffer = TEST_ACCOUNT_SLICE.to_vec();
        buffer.append(&mut vec![1, 0]);
        let err = PodStateWithExtensionsMut::<PodAccount>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        let err = set_account_type::<PodAccount>(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        // mint with buffer big enough for AccountType and Extension
        let mut buffer = TEST_MINT_SLICE.to_vec();
        let needed_len = ExtensionType::try_calculate_account_len::<PodMint>(&[
            ExtensionType::MintCloseAuthority,
        ])
        .unwrap()
            - buffer.len();
        buffer.append(&mut vec![0; needed_len]);
        let err = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        set_account_type::<PodMint>(&mut buffer).unwrap();
        // unpack is viable after manual set_account_type
        let mut state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);
        assert_eq!(state.account_type[0], AccountType::Mint as u8);
        state.init_extension::<MintCloseAuthority>(true).unwrap();

        // mint with buffer big enough for AccountType only
        let mut buffer = TEST_MINT_SLICE.to_vec();
        buffer.append(&mut vec![0; PodAccount::SIZE_OF - PodMint::SIZE_OF]);
        buffer.append(&mut vec![0; 2]);
        let err = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        set_account_type::<PodMint>(&mut buffer).unwrap();
        // unpack is viable after manual set_account_type
        let state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);
        assert_eq!(state.account_type[0], AccountType::Mint as u8);

        // mint with AccountType already set => noop
        let mut buffer = TEST_MINT_SLICE.to_vec();
        buffer.append(&mut vec![0; PodAccount::SIZE_OF - PodMint::SIZE_OF]);
        buffer.append(&mut vec![1, 0]);
        set_account_type::<PodMint>(&mut buffer).unwrap();
        let state = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap();
        assert_eq!(state.base, &TEST_POD_MINT);
        assert_eq!(state.account_type[0], AccountType::Mint as u8);

        // mint with wrong AccountType fails
        let mut buffer = TEST_MINT_SLICE.to_vec();
        buffer.append(&mut vec![0; PodAccount::SIZE_OF - PodMint::SIZE_OF]);
        buffer.append(&mut vec![2, 0]);
        let err = PodStateWithExtensionsMut::<PodMint>::unpack(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
        let err = set_account_type::<PodMint>(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
    }

    #[test]
    fn test_set_account_type_wrongly() {
        // try to set PodAccount account_type to PodMint
        let mut buffer = TEST_ACCOUNT_SLICE.to_vec();
        buffer.append(&mut vec![0; 2]);
        let err = set_account_type::<PodMint>(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        // try to set PodMint account_type to PodAccount
        let mut buffer = TEST_MINT_SLICE.to_vec();
        buffer.append(&mut vec![0; PodAccount::SIZE_OF - PodMint::SIZE_OF]);
        buffer.append(&mut vec![0; 2]);
        let err = set_account_type::<PodAccount>(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);
    }

    #[test]
    fn test_get_required_init_account_extensions() {
        // Some mint extensions with no required account extensions
        let mint_extensions = vec![
            ExtensionType::MintCloseAuthority,
            ExtensionType::Uninitialized,
        ];
        assert_eq!(
            ExtensionType::get_required_init_account_extensions(&mint_extensions),
            vec![]
        );

        // One mint extension with required account extension, one without
        let mint_extensions = vec![
            ExtensionType::TransferFeeConfig,
            ExtensionType::MintCloseAuthority,
        ];
        assert_eq!(
            ExtensionType::get_required_init_account_extensions(&mint_extensions),
            vec![ExtensionType::TransferFeeAmount]
        );

        // Some mint extensions both with required account extensions
        let mint_extensions = vec![
            ExtensionType::TransferFeeConfig,
            ExtensionType::MintPaddingTest,
        ];
        assert_eq!(
            ExtensionType::get_required_init_account_extensions(&mint_extensions),
            vec![
                ExtensionType::TransferFeeAmount,
                ExtensionType::AccountPaddingTest
            ]
        );

        // Demonstrate that method does not dedupe inputs or outputs
        let mint_extensions = vec![
            ExtensionType::TransferFeeConfig,
            ExtensionType::TransferFeeConfig,
        ];
        assert_eq!(
            ExtensionType::get_required_init_account_extensions(&mint_extensions),
            vec![
                ExtensionType::TransferFeeAmount,
                ExtensionType::TransferFeeAmount
            ]
        );
    }

    #[test]
    fn mint_without_extensions() {
        let space = ExtensionType::try_calculate_account_len::<PodMint>(&[]).unwrap();
        let mut buffer = vec![0; space];
        assert_eq!(
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer),
            Err(ProgramError::InvalidAccountData),
        );

        // write base account
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        // fail init extension
        assert_eq!(
            state.init_extension::<TransferFeeConfig>(true),
            Err(ProgramError::InvalidAccountData),
        );

        assert_eq!(TEST_MINT_SLICE, buffer);
    }

    #[test]
    fn test_init_nonzero_default() {
        let mint_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MintPaddingTest])
                .unwrap();
        let mut buffer = vec![0; mint_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();
        let extension = state.init_extension::<MintPaddingTest>(true).unwrap();
        assert_eq!(extension.padding1, [1; 128]);
        assert_eq!(extension.padding2, [2; 48]);
        assert_eq!(extension.padding3, [3; 9]);
    }

    #[test]
    fn test_init_buffer_too_small() {
        let mint_size = ExtensionType::try_calculate_account_len::<PodMint>(&[
            ExtensionType::MintCloseAuthority,
        ])
        .unwrap();
        let mut buffer = vec![0; mint_size - 1];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        let err = state
            .init_extension::<MintCloseAuthority>(true)
            .unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        state.tlv_data[0] = 3;
        state.tlv_data[2] = 32;
        let err = state.get_extension_mut::<MintCloseAuthority>().unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        let mut buffer = vec![0; PodMint::SIZE_OF + 2];
        let err =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        // OK since there are two bytes for the type, which is `Uninitialized`
        let mut buffer = vec![0; BASE_ACCOUNT_LENGTH + 3];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        let err = state.get_extension_mut::<MintCloseAuthority>().unwrap_err();
        assert_eq!(err, ProgramError::InvalidAccountData);

        assert_eq!(state.get_extension_types().unwrap(), vec![]);

        // OK, there aren't two bytes for the type, but that's fine
        let mut buffer = vec![0; BASE_ACCOUNT_LENGTH + 2];
        let state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        assert_eq!(state.get_extension_types().unwrap(), []);
    }

    #[test]
    fn test_extension_with_no_data() {
        let account_size = ExtensionType::try_calculate_account_len::<PodAccount>(&[
            ExtensionType::ImmutableOwner,
        ])
        .unwrap();
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodAccount>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_ACCOUNT;
        state.init_account_type().unwrap();

        let err = state.get_extension::<ImmutableOwner>().unwrap_err();
        assert_eq!(
            err,
            ProgramError::Custom(TokenError::ExtensionNotFound as u32)
        );

        state.init_extension::<ImmutableOwner>(true).unwrap();
        assert_eq!(
            get_first_extension_type(state.tlv_data).unwrap(),
            Some(ExtensionType::ImmutableOwner)
        );
        assert_eq!(
            get_tlv_data_info(state.tlv_data).unwrap(),
            TlvDataInfo {
                extension_types: vec![ExtensionType::ImmutableOwner],
                used_len: add_type_and_length_to_len(0)
            }
        );
    }

    #[test]
    fn fail_account_len_with_metadata() {
        assert_eq!(
            ExtensionType::try_calculate_account_len::<PodMint>(&[
                ExtensionType::MintCloseAuthority,
                ExtensionType::VariableLenMintTest,
                ExtensionType::TransferFeeConfig,
            ])
            .unwrap_err(),
            ProgramError::InvalidArgument
        );
    }

    #[test]
    fn alloc() {
        let variable_len = VariableLenMintTest { data: vec![1] };
        let alloc_size = variable_len.get_packed_len().unwrap();
        let account_size =
            BASE_ACCOUNT_LENGTH + size_of::<AccountType>() + add_type_and_length_to_len(alloc_size);
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        state
            .init_variable_len_extension(&variable_len, false)
            .unwrap();

        // can't double alloc
        assert_eq!(
            state
                .init_variable_len_extension(&variable_len, false)
                .unwrap_err(),
            TokenError::ExtensionAlreadyInitialized.into()
        );

        // unless overwrite is set
        state
            .init_variable_len_extension(&variable_len, true)
            .unwrap();

        // can't change the size during overwrite though
        assert_eq!(
            state
                .init_variable_len_extension(&VariableLenMintTest { data: vec![] }, true)
                .unwrap_err(),
            TokenError::InvalidLengthForAlloc.into()
        );

        // try to write too far, fail earlier
        assert_eq!(
            state
                .init_variable_len_extension(&VariableLenMintTest { data: vec![1, 2] }, true)
                .unwrap_err(),
            ProgramError::InvalidAccountData
        );
    }

    #[test]
    fn realloc() {
        let small_variable_len = VariableLenMintTest {
            data: vec![1, 2, 3],
        };
        let base_variable_len = VariableLenMintTest {
            data: vec![1, 2, 3, 4],
        };
        let big_variable_len = VariableLenMintTest {
            data: vec![1, 2, 3, 4, 5],
        };
        let too_big_variable_len = VariableLenMintTest {
            data: vec![1, 2, 3, 4, 5, 6],
        };
        let account_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MetadataPointer])
                .unwrap()
                + add_type_and_length_to_len(big_variable_len.get_packed_len().unwrap());
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();

        // alloc both types
        state
            .init_variable_len_extension(&base_variable_len, false)
            .unwrap();
        let max_pubkey =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([255; 32]))).unwrap();
        let extension = state.init_extension::<MetadataPointer>(false).unwrap();
        extension.authority = max_pubkey;
        extension.metadata_address = max_pubkey;

        // realloc first entry to larger
        state
            .realloc_variable_len_extension(&big_variable_len)
            .unwrap();
        let extension = state
            .get_variable_len_extension::<VariableLenMintTest>()
            .unwrap();
        assert_eq!(extension, big_variable_len);
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, max_pubkey);
        assert_eq!(extension.metadata_address, max_pubkey);

        // realloc to smaller
        state
            .realloc_variable_len_extension(&small_variable_len)
            .unwrap();
        let extension = state
            .get_variable_len_extension::<VariableLenMintTest>()
            .unwrap();
        assert_eq!(extension, small_variable_len);
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, max_pubkey);
        assert_eq!(extension.metadata_address, max_pubkey);
        let diff = big_variable_len.get_packed_len().unwrap()
            - small_variable_len.get_packed_len().unwrap();
        assert_eq!(&buffer[account_size - diff..account_size], vec![0; diff]);

        // unpack again since we dropped the last `state`
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        // realloc too much, fails
        assert_eq!(
            state
                .realloc_variable_len_extension(&too_big_variable_len)
                .unwrap_err(),
            ProgramError::InvalidAccountData,
        );
    }

    #[test]
    fn account_len() {
        let small_variable_len = VariableLenMintTest {
            data: vec![20, 30, 40],
        };
        let variable_len = VariableLenMintTest {
            data: vec![20, 30, 40, 50],
        };
        let big_variable_len = VariableLenMintTest {
            data: vec![20, 30, 40, 50, 60],
        };
        let value_len = variable_len.get_packed_len().unwrap();
        let account_size =
            BASE_ACCOUNT_LENGTH + size_of::<AccountType>() + add_type_and_length_to_len(value_len);
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();

        // With a new extension, new length must include padding, 1 byte for
        // account type, 2 bytes for type, 2 for length
        let current_len = state.try_get_account_len().unwrap();
        assert_eq!(current_len, PodMint::SIZE_OF);
        let new_len = state
            .try_get_new_account_len_for_variable_len_extension::<VariableLenMintTest>(
                &variable_len,
            )
            .unwrap();
        assert_eq!(
            new_len,
            BASE_ACCOUNT_AND_TYPE_LENGTH.saturating_add(add_type_and_length_to_len(value_len))
        );

        state
            .init_variable_len_extension::<VariableLenMintTest>(&variable_len, false)
            .unwrap();
        let current_len = state.try_get_account_len().unwrap();
        assert_eq!(current_len, new_len);

        // Reduce the extension size
        let new_len = state
            .try_get_new_account_len_for_variable_len_extension::<VariableLenMintTest>(
                &small_variable_len,
            )
            .unwrap();
        assert_eq!(current_len.checked_sub(new_len).unwrap(), 1);

        // Increase the extension size
        let new_len = state
            .try_get_new_account_len_for_variable_len_extension::<VariableLenMintTest>(
                &big_variable_len,
            )
            .unwrap();
        assert_eq!(new_len.checked_sub(current_len).unwrap(), 1);

        // Maintain the extension size
        let new_len = state
            .try_get_new_account_len_for_variable_len_extension::<VariableLenMintTest>(
                &variable_len,
            )
            .unwrap();
        assert_eq!(new_len, current_len);
    }

    /// Test helper for mimicking the data layout an on-chain `AccountInfo`,
    /// which permits "reallocs" as the Solana runtime does it
    struct SolanaAccountData {
        data: Vec<u8>,
        lamports: u64,
        owner: Pubkey,
    }
    impl SolanaAccountData {
        /// Create a new fake solana account data. The underlying vector is
        /// overallocated to mimic the runtime
        fn new(account_data: &[u8]) -> Self {
            let mut data = vec![];
            data.extend_from_slice(&(account_data.len() as u64).to_le_bytes());
            data.extend_from_slice(account_data);
            data.extend_from_slice(&[0; MAX_PERMITTED_DATA_INCREASE]);
            Self {
                data,
                lamports: 10,
                owner: Pubkey::new_unique(),
            }
        }

        /// Data lops off the first 8 bytes, since those store the size of the
        /// account for the Solana runtime
        fn data(&self) -> &[u8] {
            let start = size_of::<u64>();
            let len = self.len();
            &self.data[start..start + len]
        }

        /// Gets the runtime length of the account data
        fn len(&self) -> usize {
            self.data
                .get(..size_of::<u64>())
                .and_then(|slice| slice.try_into().ok())
                .map(u64::from_le_bytes)
                .unwrap() as usize
        }
    }
    impl GetAccount for SolanaAccountData {
        fn get(&mut self) -> (&mut u64, &mut [u8], &Pubkey, bool, Epoch) {
            // need to pull out the data here to avoid a double-mutable borrow
            let start = size_of::<u64>();
            let len = self.len();
            (
                &mut self.lamports,
                &mut self.data[start..start + len],
                &self.owner,
                false,
                Epoch::default(),
            )
        }
    }

    #[test]
    fn alloc_new_fixed_len_tlv_in_account_info_from_base_size() {
        let fixed_len = FixedLenMintTest {
            data: [1, 2, 3, 4, 5, 6, 7, 8],
        };
        let value_len = pod_get_packed_len::<FixedLenMintTest>();
        let base_account_size = PodMint::SIZE_OF;
        let mut buffer = vec![0; base_account_size];
        let state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;

        let mut data = SolanaAccountData::new(&buffer);
        let key = Pubkey::new_unique();
        let account_info = (&key, &mut data).into_account_info();

        alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, false).unwrap();
        let new_account_len = BASE_ACCOUNT_AND_TYPE_LENGTH + add_type_and_length_to_len(value_len);
        assert_eq!(data.len(), new_account_len);
        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        assert_eq!(
            state.get_extension::<FixedLenMintTest>().unwrap(),
            &fixed_len,
        );

        // alloc again succeeds with "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, true).unwrap();

        // alloc again fails without "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        assert_eq!(
            alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, false).unwrap_err(),
            TokenError::ExtensionAlreadyInitialized.into()
        );
    }

    #[test]
    fn alloc_new_variable_len_tlv_in_account_info_from_base_size() {
        let variable_len = VariableLenMintTest { data: vec![20, 99] };
        let value_len = variable_len.get_packed_len().unwrap();
        let base_account_size = PodMint::SIZE_OF;
        let mut buffer = vec![0; base_account_size];
        let state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;

        let mut data = SolanaAccountData::new(&buffer);
        let key = Pubkey::new_unique();
        let account_info = (&key, &mut data).into_account_info();

        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            false,
        )
        .unwrap();
        let new_account_len = BASE_ACCOUNT_AND_TYPE_LENGTH + add_type_and_length_to_len(value_len);
        assert_eq!(data.len(), new_account_len);
        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        assert_eq!(
            state
                .get_variable_len_extension::<VariableLenMintTest>()
                .unwrap(),
            variable_len
        );

        // alloc again succeeds with "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            true,
        )
        .unwrap();

        // alloc again fails without "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        assert_eq!(
            alloc_and_serialize_variable_len_extension::<PodMint, _>(
                &account_info,
                &variable_len,
                false,
            )
            .unwrap_err(),
            TokenError::ExtensionAlreadyInitialized.into()
        );
    }

    #[test]
    fn alloc_new_fixed_len_tlv_in_account_info_from_extended_size() {
        let fixed_len = FixedLenMintTest {
            data: [1, 2, 3, 4, 5, 6, 7, 8],
        };
        let value_len = pod_get_packed_len::<FixedLenMintTest>();
        let account_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::GroupPointer])
                .unwrap()
                + add_type_and_length_to_len(value_len);
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        let test_key =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([20; 32]))).unwrap();
        let extension = state.init_extension::<GroupPointer>(false).unwrap();
        extension.authority = test_key;
        extension.group_address = test_key;

        let mut data = SolanaAccountData::new(&buffer);
        let key = Pubkey::new_unique();
        let account_info = (&key, &mut data).into_account_info();

        alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, false).unwrap();
        let new_account_len = BASE_ACCOUNT_AND_TYPE_LENGTH
            + add_type_and_length_to_len(value_len)
            + add_type_and_length_to_len(size_of::<GroupPointer>());
        assert_eq!(data.len(), new_account_len);
        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        assert_eq!(
            state.get_extension::<FixedLenMintTest>().unwrap(),
            &fixed_len,
        );
        let extension = state.get_extension::<GroupPointer>().unwrap();
        assert_eq!(extension.authority, test_key);
        assert_eq!(extension.group_address, test_key);

        // alloc again succeeds with "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, true).unwrap();

        // alloc again fails without "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        assert_eq!(
            alloc_and_serialize::<PodMint, _>(&account_info, &fixed_len, false).unwrap_err(),
            TokenError::ExtensionAlreadyInitialized.into()
        );
    }

    #[test]
    fn alloc_new_variable_len_tlv_in_account_info_from_extended_size() {
        let variable_len = VariableLenMintTest { data: vec![42, 6] };
        let value_len = variable_len.get_packed_len().unwrap();
        let account_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MetadataPointer])
                .unwrap()
                + add_type_and_length_to_len(value_len);
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        let test_key =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([20; 32]))).unwrap();
        let extension = state.init_extension::<MetadataPointer>(false).unwrap();
        extension.authority = test_key;
        extension.metadata_address = test_key;

        let mut data = SolanaAccountData::new(&buffer);
        let key = Pubkey::new_unique();
        let account_info = (&key, &mut data).into_account_info();

        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            false,
        )
        .unwrap();
        let new_account_len = BASE_ACCOUNT_AND_TYPE_LENGTH
            + add_type_and_length_to_len(value_len)
            + add_type_and_length_to_len(size_of::<MetadataPointer>());
        assert_eq!(data.len(), new_account_len);
        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        assert_eq!(
            state
                .get_variable_len_extension::<VariableLenMintTest>()
                .unwrap(),
            variable_len
        );
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, test_key);
        assert_eq!(extension.metadata_address, test_key);

        // alloc again succeeds with "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            true,
        )
        .unwrap();

        // alloc again fails without "overwrite"
        let account_info = (&key, &mut data).into_account_info();
        assert_eq!(
            alloc_and_serialize_variable_len_extension::<PodMint, _>(
                &account_info,
                &variable_len,
                false,
            )
            .unwrap_err(),
            TokenError::ExtensionAlreadyInitialized.into()
        );
    }

    #[test]
    fn realloc_variable_len_tlv_in_account_info() {
        let variable_len = VariableLenMintTest {
            data: vec![1, 2, 3, 4, 5],
        };
        let alloc_size = variable_len.get_packed_len().unwrap();
        let account_size =
            ExtensionType::try_calculate_account_len::<PodMint>(&[ExtensionType::MetadataPointer])
                .unwrap()
                + add_type_and_length_to_len(alloc_size);
        let mut buffer = vec![0; account_size];
        let mut state =
            PodStateWithExtensionsMut::<PodMint>::unpack_uninitialized(&mut buffer).unwrap();
        *state.base = TEST_POD_MINT;
        state.init_account_type().unwrap();

        // alloc both types
        state
            .init_variable_len_extension(&variable_len, false)
            .unwrap();
        let max_pubkey =
            OptionalNonZeroPubkey::try_from(Some(Pubkey::new_from_array([255; 32]))).unwrap();
        let extension = state.init_extension::<MetadataPointer>(false).unwrap();
        extension.authority = max_pubkey;
        extension.metadata_address = max_pubkey;

        // reallocate to smaller, make sure existing extension is fine
        let mut data = SolanaAccountData::new(&buffer);
        let key = Pubkey::new_unique();
        let account_info = (&key, &mut data).into_account_info();
        let variable_len = VariableLenMintTest { data: vec![1, 2] };
        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            true,
        )
        .unwrap();

        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, max_pubkey);
        assert_eq!(extension.metadata_address, max_pubkey);
        let extension = state
            .get_variable_len_extension::<VariableLenMintTest>()
            .unwrap();
        assert_eq!(extension, variable_len);
        assert_eq!(data.len(), state.try_get_account_len().unwrap());

        // reallocate to larger
        let account_info = (&key, &mut data).into_account_info();
        let variable_len = VariableLenMintTest {
            data: vec![1, 2, 3, 4, 5, 6, 7],
        };
        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            true,
        )
        .unwrap();

        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, max_pubkey);
        assert_eq!(extension.metadata_address, max_pubkey);
        let extension = state
            .get_variable_len_extension::<VariableLenMintTest>()
            .unwrap();
        assert_eq!(extension, variable_len);
        assert_eq!(data.len(), state.try_get_account_len().unwrap());

        // reallocate to same
        let account_info = (&key, &mut data).into_account_info();
        let variable_len = VariableLenMintTest {
            data: vec![7, 6, 5, 4, 3, 2, 1],
        };
        alloc_and_serialize_variable_len_extension::<PodMint, _>(
            &account_info,
            &variable_len,
            true,
        )
        .unwrap();

        let state = PodStateWithExtensions::<PodMint>::unpack(data.data()).unwrap();
        let extension = state.get_extension::<MetadataPointer>().unwrap();
        assert_eq!(extension.authority, max_pubkey);
        assert_eq!(extension.metadata_address, max_pubkey);
        let extension = state
            .get_variable_len_extension::<VariableLenMintTest>()
            .unwrap();
        assert_eq!(extension, variable_len);
        assert_eq!(data.len(), state.try_get_account_len().unwrap());
    }
}