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

OpenType fonts with PostScript outlines contain a completely independent
font file, Adobe's *Compact Font Format*. So dealing with OpenType fonts
requires also dealing with CFF. This module allows you to read and write
fonts written in the CFF format.

In 2016, OpenType 1.8 introduced the `CFF2 <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2>`_
format which, along with other changes, extended the CFF format to deal with
the demands of variable fonts. This module parses both original CFF and CFF2.

"""

from fontTools.misc import sstruct
from fontTools.misc import psCharStrings
from fontTools.misc.arrayTools import unionRect, intRect
from fontTools.misc.textTools import (
    bytechr,
    byteord,
    bytesjoin,
    tobytes,
    tostr,
    safeEval,
)
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables.otBase import OTTableWriter
from fontTools.ttLib.tables.otBase import OTTableReader
from fontTools.ttLib.tables import otTables as ot
from io import BytesIO
import struct
import logging
import re

# mute cffLib debug messages when running ttx in verbose mode
DEBUG = logging.DEBUG - 1
log = logging.getLogger(__name__)

cffHeaderFormat = """
	major:   B
	minor:   B
	hdrSize: B
"""

maxStackLimit = 513
# maxstack operator has been deprecated. max stack is now always 513.


class CFFFontSet(object):
    """A CFF font "file" can contain more than one font, although this is
    extremely rare (and not allowed within OpenType fonts).

    This class is the entry point for parsing a CFF table. To actually
    manipulate the data inside the CFF font, you will want to access the
    ``CFFFontSet``'s :class:`TopDict` object. To do this, a ``CFFFontSet``
    object can either be treated as a dictionary (with appropriate
    ``keys()`` and ``values()`` methods) mapping font names to :class:`TopDict`
    objects, or as a list.

    .. code:: python

            from fontTools import ttLib
            tt = ttLib.TTFont("Tests/cffLib/data/LinLibertine_RBI.otf")
            tt["CFF "].cff
            # <fontTools.cffLib.CFFFontSet object at 0x101e24c90>
            tt["CFF "].cff[0] # Here's your actual font data
            # <fontTools.cffLib.TopDict object at 0x1020f1fd0>

    """

    def decompile(self, file, otFont, isCFF2=None):
        """Parse a binary CFF file into an internal representation. ``file``
        should be a file handle object. ``otFont`` is the top-level
        :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file.

        If ``isCFF2`` is passed and set to ``True`` or ``False``, then the
        library makes an assertion that the CFF header is of the appropriate
        version.
        """

        self.otFont = otFont
        sstruct.unpack(cffHeaderFormat, file.read(3), self)
        if isCFF2 is not None:
            # called from ttLib: assert 'major' as read from file matches the
            # expected version
            expected_major = 2 if isCFF2 else 1
            if self.major != expected_major:
                raise ValueError(
                    "Invalid CFF 'major' version: expected %d, found %d"
                    % (expected_major, self.major)
                )
        else:
            # use 'major' version from file to determine if isCFF2
            assert self.major in (1, 2), "Unknown CFF format"
            isCFF2 = self.major == 2
        if not isCFF2:
            self.offSize = struct.unpack("B", file.read(1))[0]
            file.seek(self.hdrSize)
            self.fontNames = list(tostr(s) for s in Index(file, isCFF2=isCFF2))
            self.topDictIndex = TopDictIndex(file, isCFF2=isCFF2)
            self.strings = IndexedStrings(file)
        else:  # isCFF2
            self.topDictSize = struct.unpack(">H", file.read(2))[0]
            file.seek(self.hdrSize)
            self.fontNames = ["CFF2Font"]
            cff2GetGlyphOrder = otFont.getGlyphOrder
            # in CFF2, offsetSize is the size of the TopDict data.
            self.topDictIndex = TopDictIndex(
                file, cff2GetGlyphOrder, self.topDictSize, isCFF2=isCFF2
            )
            self.strings = None
        self.GlobalSubrs = GlobalSubrsIndex(file, isCFF2=isCFF2)
        self.topDictIndex.strings = self.strings
        self.topDictIndex.GlobalSubrs = self.GlobalSubrs

    def __len__(self):
        return len(self.fontNames)

    def keys(self):
        return list(self.fontNames)

    def values(self):
        return self.topDictIndex

    def __getitem__(self, nameOrIndex):
        """Return TopDict instance identified by name (str) or index (int
        or any object that implements `__index__`).
        """
        if hasattr(nameOrIndex, "__index__"):
            index = nameOrIndex.__index__()
        elif isinstance(nameOrIndex, str):
            name = nameOrIndex
            try:
                index = self.fontNames.index(name)
            except ValueError:
                raise KeyError(nameOrIndex)
        else:
            raise TypeError(nameOrIndex)
        return self.topDictIndex[index]

    def compile(self, file, otFont, isCFF2=None):
        """Write the object back into binary representation onto the given file.
        ``file`` should be a file handle object. ``otFont`` is the top-level
        :py:class:`fontTools.ttLib.ttFont.TTFont` object containing this CFF file.

        If ``isCFF2`` is passed and set to ``True`` or ``False``, then the
        library makes an assertion that the CFF header is of the appropriate
        version.
        """
        self.otFont = otFont
        if isCFF2 is not None:
            # called from ttLib: assert 'major' value matches expected version
            expected_major = 2 if isCFF2 else 1
            if self.major != expected_major:
                raise ValueError(
                    "Invalid CFF 'major' version: expected %d, found %d"
                    % (expected_major, self.major)
                )
        else:
            # use current 'major' value to determine output format
            assert self.major in (1, 2), "Unknown CFF format"
            isCFF2 = self.major == 2

        if otFont.recalcBBoxes and not isCFF2:
            for topDict in self.topDictIndex:
                topDict.recalcFontBBox()

        if not isCFF2:
            strings = IndexedStrings()
        else:
            strings = None
        writer = CFFWriter(isCFF2)
        topCompiler = self.topDictIndex.getCompiler(strings, self, isCFF2=isCFF2)
        if isCFF2:
            self.hdrSize = 5
            writer.add(sstruct.pack(cffHeaderFormat, self))
            # Note: topDictSize will most likely change in CFFWriter.toFile().
            self.topDictSize = topCompiler.getDataLength()
            writer.add(struct.pack(">H", self.topDictSize))
        else:
            self.hdrSize = 4
            self.offSize = 4  # will most likely change in CFFWriter.toFile().
            writer.add(sstruct.pack(cffHeaderFormat, self))
            writer.add(struct.pack("B", self.offSize))
        if not isCFF2:
            fontNames = Index()
            for name in self.fontNames:
                fontNames.append(name)
            writer.add(fontNames.getCompiler(strings, self, isCFF2=isCFF2))
        writer.add(topCompiler)
        if not isCFF2:
            writer.add(strings.getCompiler())
        writer.add(self.GlobalSubrs.getCompiler(strings, self, isCFF2=isCFF2))

        for topDict in self.topDictIndex:
            if not hasattr(topDict, "charset") or topDict.charset is None:
                charset = otFont.getGlyphOrder()
                topDict.charset = charset
        children = topCompiler.getChildren(strings)
        for child in children:
            writer.add(child)

        writer.toFile(file)

    def toXML(self, xmlWriter):
        """Write the object into XML representation onto the given
        :class:`fontTools.misc.xmlWriter.XMLWriter`.

        .. code:: python

                writer = xmlWriter.XMLWriter(sys.stdout)
                tt["CFF "].cff.toXML(writer)

        """

        xmlWriter.simpletag("major", value=self.major)
        xmlWriter.newline()
        xmlWriter.simpletag("minor", value=self.minor)
        xmlWriter.newline()
        for fontName in self.fontNames:
            xmlWriter.begintag("CFFFont", name=tostr(fontName))
            xmlWriter.newline()
            font = self[fontName]
            font.toXML(xmlWriter)
            xmlWriter.endtag("CFFFont")
            xmlWriter.newline()
        xmlWriter.newline()
        xmlWriter.begintag("GlobalSubrs")
        xmlWriter.newline()
        self.GlobalSubrs.toXML(xmlWriter)
        xmlWriter.endtag("GlobalSubrs")
        xmlWriter.newline()

    def fromXML(self, name, attrs, content, otFont=None):
        """Reads data from the XML element into the ``CFFFontSet`` object."""
        self.otFont = otFont

        # set defaults. These will be replaced if there are entries for them
        # in the XML file.
        if not hasattr(self, "major"):
            self.major = 1
        if not hasattr(self, "minor"):
            self.minor = 0

        if name == "CFFFont":
            if self.major == 1:
                if not hasattr(self, "offSize"):
                    # this will be recalculated when the cff is compiled.
                    self.offSize = 4
                if not hasattr(self, "hdrSize"):
                    self.hdrSize = 4
                if not hasattr(self, "GlobalSubrs"):
                    self.GlobalSubrs = GlobalSubrsIndex()
                if not hasattr(self, "fontNames"):
                    self.fontNames = []
                    self.topDictIndex = TopDictIndex()
                fontName = attrs["name"]
                self.fontNames.append(fontName)
                topDict = TopDict(GlobalSubrs=self.GlobalSubrs)
                topDict.charset = None  # gets filled in later
            elif self.major == 2:
                if not hasattr(self, "hdrSize"):
                    self.hdrSize = 5
                if not hasattr(self, "GlobalSubrs"):
                    self.GlobalSubrs = GlobalSubrsIndex()
                if not hasattr(self, "fontNames"):
                    self.fontNames = ["CFF2Font"]
                cff2GetGlyphOrder = self.otFont.getGlyphOrder
                topDict = TopDict(
                    GlobalSubrs=self.GlobalSubrs, cff2GetGlyphOrder=cff2GetGlyphOrder
                )
                self.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder)
            self.topDictIndex.append(topDict)
            for element in content:
                if isinstance(element, str):
                    continue
                name, attrs, content = element
                topDict.fromXML(name, attrs, content)

            if hasattr(topDict, "VarStore") and topDict.FDArray[0].vstore is None:
                fdArray = topDict.FDArray
                for fontDict in fdArray:
                    if hasattr(fontDict, "Private"):
                        fontDict.Private.vstore = topDict.VarStore

        elif name == "GlobalSubrs":
            subrCharStringClass = psCharStrings.T2CharString
            if not hasattr(self, "GlobalSubrs"):
                self.GlobalSubrs = GlobalSubrsIndex()
            for element in content:
                if isinstance(element, str):
                    continue
                name, attrs, content = element
                subr = subrCharStringClass()
                subr.fromXML(name, attrs, content)
                self.GlobalSubrs.append(subr)
        elif name == "major":
            self.major = int(attrs["value"])
        elif name == "minor":
            self.minor = int(attrs["value"])

    def convertCFFToCFF2(self, otFont):
        from .CFFToCFF2 import _convertCFFToCFF2

        _convertCFFToCFF2(self, otFont)

    def convertCFF2ToCFF(self, otFont):
        from .CFF2ToCFF import _convertCFF2ToCFF

        _convertCFF2ToCFF(self, otFont)

    def desubroutinize(self):
        from .transforms import desubroutinize

        desubroutinize(self)

    def remove_hints(self):
        from .transforms import remove_hints

        remove_hints(self)

    def remove_unused_subroutines(self):
        from .transforms import remove_unused_subroutines

        remove_unused_subroutines(self)


class CFFWriter(object):
    """Helper class for serializing CFF data to binary. Used by
    :meth:`CFFFontSet.compile`."""

    def __init__(self, isCFF2):
        self.data = []
        self.isCFF2 = isCFF2

    def add(self, table):
        self.data.append(table)

    def toFile(self, file):
        lastPosList = None
        count = 1
        while True:
            log.log(DEBUG, "CFFWriter.toFile() iteration: %d", count)
            count = count + 1
            pos = 0
            posList = [pos]
            for item in self.data:
                if hasattr(item, "getDataLength"):
                    endPos = pos + item.getDataLength()
                    if isinstance(item, TopDictIndexCompiler) and item.isCFF2:
                        self.topDictSize = item.getDataLength()
                else:
                    endPos = pos + len(item)
                if hasattr(item, "setPos"):
                    item.setPos(pos, endPos)
                pos = endPos
                posList.append(pos)
            if posList == lastPosList:
                break
            lastPosList = posList
        log.log(DEBUG, "CFFWriter.toFile() writing to file.")
        begin = file.tell()
        if self.isCFF2:
            self.data[1] = struct.pack(">H", self.topDictSize)
        else:
            self.offSize = calcOffSize(lastPosList[-1])
            self.data[1] = struct.pack("B", self.offSize)
        posList = [0]
        for item in self.data:
            if hasattr(item, "toFile"):
                item.toFile(file)
            else:
                file.write(item)
            posList.append(file.tell() - begin)
        assert posList == lastPosList


def calcOffSize(largestOffset):
    if largestOffset < 0x100:
        offSize = 1
    elif largestOffset < 0x10000:
        offSize = 2
    elif largestOffset < 0x1000000:
        offSize = 3
    else:
        offSize = 4
    return offSize


class IndexCompiler(object):
    """Base class for writing CFF `INDEX data <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#5-index-data>`_
    to binary."""

    def __init__(self, items, strings, parent, isCFF2=None):
        if isCFF2 is None and hasattr(parent, "isCFF2"):
            isCFF2 = parent.isCFF2
            assert isCFF2 is not None
        self.isCFF2 = isCFF2
        self.items = self.getItems(items, strings)
        self.parent = parent

    def getItems(self, items, strings):
        return items

    def getOffsets(self):
        # An empty INDEX contains only the count field.
        if self.items:
            pos = 1
            offsets = [pos]
            for item in self.items:
                if hasattr(item, "getDataLength"):
                    pos = pos + item.getDataLength()
                else:
                    pos = pos + len(item)
                offsets.append(pos)
        else:
            offsets = []
        return offsets

    def getDataLength(self):
        if self.isCFF2:
            countSize = 4
        else:
            countSize = 2

        if self.items:
            lastOffset = self.getOffsets()[-1]
            offSize = calcOffSize(lastOffset)
            dataLength = (
                countSize
                + 1  # count
                + (len(self.items) + 1) * offSize  # offSize
                + lastOffset  # the offsets
                - 1  # size of object data
            )
        else:
            # count. For empty INDEX tables, this is the only entry.
            dataLength = countSize

        return dataLength

    def toFile(self, file):
        offsets = self.getOffsets()
        if self.isCFF2:
            writeCard32(file, len(self.items))
        else:
            writeCard16(file, len(self.items))
        # An empty INDEX contains only the count field.
        if self.items:
            offSize = calcOffSize(offsets[-1])
            writeCard8(file, offSize)
            offSize = -offSize
            pack = struct.pack
            for offset in offsets:
                binOffset = pack(">l", offset)[offSize:]
                assert len(binOffset) == -offSize
                file.write(binOffset)
            for item in self.items:
                if hasattr(item, "toFile"):
                    item.toFile(file)
                else:
                    data = tobytes(item, encoding="latin1")
                    file.write(data)


class IndexedStringsCompiler(IndexCompiler):
    def getItems(self, items, strings):
        return items.strings


class TopDictIndexCompiler(IndexCompiler):
    """Helper class for writing the TopDict to binary."""

    def getItems(self, items, strings):
        out = []
        for item in items:
            out.append(item.getCompiler(strings, self))
        return out

    def getChildren(self, strings):
        children = []
        for topDict in self.items:
            children.extend(topDict.getChildren(strings))
        return children

    def getOffsets(self):
        if self.isCFF2:
            offsets = [0, self.items[0].getDataLength()]
            return offsets
        else:
            return super(TopDictIndexCompiler, self).getOffsets()

    def getDataLength(self):
        if self.isCFF2:
            dataLength = self.items[0].getDataLength()
            return dataLength
        else:
            return super(TopDictIndexCompiler, self).getDataLength()

    def toFile(self, file):
        if self.isCFF2:
            self.items[0].toFile(file)
        else:
            super(TopDictIndexCompiler, self).toFile(file)


class FDArrayIndexCompiler(IndexCompiler):
    """Helper class for writing the
    `Font DICT INDEX <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#10-font-dict-index-font-dicts-and-fdselect>`_
    to binary."""

    def getItems(self, items, strings):
        out = []
        for item in items:
            out.append(item.getCompiler(strings, self))
        return out

    def getChildren(self, strings):
        children = []
        for fontDict in self.items:
            children.extend(fontDict.getChildren(strings))
        return children

    def toFile(self, file):
        offsets = self.getOffsets()
        if self.isCFF2:
            writeCard32(file, len(self.items))
        else:
            writeCard16(file, len(self.items))
        offSize = calcOffSize(offsets[-1])
        writeCard8(file, offSize)
        offSize = -offSize
        pack = struct.pack
        for offset in offsets:
            binOffset = pack(">l", offset)[offSize:]
            assert len(binOffset) == -offSize
            file.write(binOffset)
        for item in self.items:
            if hasattr(item, "toFile"):
                item.toFile(file)
            else:
                file.write(item)

    def setPos(self, pos, endPos):
        self.parent.rawDict["FDArray"] = pos


class GlobalSubrsCompiler(IndexCompiler):
    """Helper class for writing the `global subroutine INDEX <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#9-local-and-global-subr-indexes>`_
    to binary."""

    def getItems(self, items, strings):
        out = []
        for cs in items:
            cs.compile(self.isCFF2)
            out.append(cs.bytecode)
        return out


class SubrsCompiler(GlobalSubrsCompiler):
    """Helper class for writing the `local subroutine INDEX <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#9-local-and-global-subr-indexes>`_
    to binary."""

    def setPos(self, pos, endPos):
        offset = pos - self.parent.pos
        self.parent.rawDict["Subrs"] = offset


class CharStringsCompiler(GlobalSubrsCompiler):
    """Helper class for writing the `CharStrings INDEX <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#9-local-and-global-subr-indexes>`_
    to binary."""

    def getItems(self, items, strings):
        out = []
        for cs in items:
            cs.compile(self.isCFF2)
            out.append(cs.bytecode)
        return out

    def setPos(self, pos, endPos):
        self.parent.rawDict["CharStrings"] = pos


class Index(object):
    """This class represents what the CFF spec calls an INDEX (an array of
    variable-sized objects). `Index` items can be addressed and set using
    Python list indexing."""

    compilerClass = IndexCompiler

    def __init__(self, file=None, isCFF2=None):
        self.items = []
        self.offsets = offsets = []
        name = self.__class__.__name__
        if file is None:
            return
        self._isCFF2 = isCFF2
        log.log(DEBUG, "loading %s at %s", name, file.tell())
        self.file = file
        if isCFF2:
            count = readCard32(file)
        else:
            count = readCard16(file)
        if count == 0:
            return
        self.items = [None] * count
        offSize = readCard8(file)
        log.log(DEBUG, "    index count: %s offSize: %s", count, offSize)
        assert offSize <= 4, "offSize too large: %s" % offSize
        pad = b"\0" * (4 - offSize)
        for index in range(count + 1):
            chunk = file.read(offSize)
            chunk = pad + chunk
            (offset,) = struct.unpack(">L", chunk)
            offsets.append(int(offset))
        self.offsetBase = file.tell() - 1
        file.seek(self.offsetBase + offsets[-1])  # pretend we've read the whole lot
        log.log(DEBUG, "    end of %s at %s", name, file.tell())

    def __len__(self):
        return len(self.items)

    def __getitem__(self, index):
        item = self.items[index]
        if item is not None:
            return item
        offset = self.offsets[index] + self.offsetBase
        size = self.offsets[index + 1] - self.offsets[index]
        file = self.file
        file.seek(offset)
        data = file.read(size)
        assert len(data) == size
        item = self.produceItem(index, data, file, offset)
        self.items[index] = item
        return item

    def __setitem__(self, index, item):
        self.items[index] = item

    def produceItem(self, index, data, file, offset):
        return data

    def append(self, item):
        """Add an item to an INDEX."""
        self.items.append(item)

    def getCompiler(self, strings, parent, isCFF2=None):
        return self.compilerClass(self, strings, parent, isCFF2=isCFF2)

    def clear(self):
        """Empty the INDEX."""
        del self.items[:]


class GlobalSubrsIndex(Index):
    """This index contains all the global subroutines in the font. A global
    subroutine is a set of ``CharString`` data which is accessible to any
    glyph in the font, and are used to store repeated instructions - for
    example, components may be encoded as global subroutines, but so could
    hinting instructions.

    Remember that when interpreting a ``callgsubr`` instruction (or indeed
    a ``callsubr`` instruction) that you will need to add the "subroutine
    number bias" to number given:

    .. code:: python

            tt = ttLib.TTFont("Almendra-Bold.otf")
            u = tt["CFF "].cff[0].CharStrings["udieresis"]
            u.decompile()

            u.toXML(XMLWriter(sys.stdout))
            # <some stuff>
            # -64 callgsubr <-- Subroutine which implements the dieresis mark
            # <other stuff>

            tt["CFF "].cff[0].GlobalSubrs[-64] # <-- WRONG
            # <T2CharString (bytecode) at 103451d10>

            tt["CFF "].cff[0].GlobalSubrs[-64 + 107] # <-- RIGHT
            # <T2CharString (source) at 103451390>

    ("The bias applied depends on the number of subrs (gsubrs). If the number of
    subrs (gsubrs) is less than 1240, the bias is 107. Otherwise if it is less
    than 33900, it is 1131; otherwise it is 32768.",
    `Subroutine Operators <https://docs.microsoft.com/en-us/typography/opentype/otspec180/cff2charstr#section4.4>`)
    """

    compilerClass = GlobalSubrsCompiler
    subrClass = psCharStrings.T2CharString
    charStringClass = psCharStrings.T2CharString

    def __init__(
        self,
        file=None,
        globalSubrs=None,
        private=None,
        fdSelect=None,
        fdArray=None,
        isCFF2=None,
    ):
        super(GlobalSubrsIndex, self).__init__(file, isCFF2=isCFF2)
        self.globalSubrs = globalSubrs
        self.private = private
        if fdSelect:
            self.fdSelect = fdSelect
        if fdArray:
            self.fdArray = fdArray

    def produceItem(self, index, data, file, offset):
        if self.private is not None:
            private = self.private
        elif hasattr(self, "fdArray") and self.fdArray is not None:
            if hasattr(self, "fdSelect") and self.fdSelect is not None:
                fdIndex = self.fdSelect[index]
            else:
                fdIndex = 0
            private = self.fdArray[fdIndex].Private
        else:
            private = None
        return self.subrClass(data, private=private, globalSubrs=self.globalSubrs)

    def toXML(self, xmlWriter):
        """Write the subroutines index into XML representation onto the given
        :class:`fontTools.misc.xmlWriter.XMLWriter`.

        .. code:: python

                writer = xmlWriter.XMLWriter(sys.stdout)
                tt["CFF "].cff[0].GlobalSubrs.toXML(writer)

        """
        xmlWriter.comment(
            "The 'index' attribute is only for humans; " "it is ignored when parsed."
        )
        xmlWriter.newline()
        for i in range(len(self)):
            subr = self[i]
            if subr.needsDecompilation():
                xmlWriter.begintag("CharString", index=i, raw=1)
            else:
                xmlWriter.begintag("CharString", index=i)
            xmlWriter.newline()
            subr.toXML(xmlWriter)
            xmlWriter.endtag("CharString")
            xmlWriter.newline()

    def fromXML(self, name, attrs, content):
        if name != "CharString":
            return
        subr = self.subrClass()
        subr.fromXML(name, attrs, content)
        self.append(subr)

    def getItemAndSelector(self, index):
        sel = None
        if hasattr(self, "fdSelect"):
            sel = self.fdSelect[index]
        return self[index], sel


class SubrsIndex(GlobalSubrsIndex):
    """This index contains a glyph's local subroutines. A local subroutine is a
    private set of ``CharString`` data which is accessible only to the glyph to
    which the index is attached."""

    compilerClass = SubrsCompiler


class TopDictIndex(Index):
    """This index represents the array of ``TopDict`` structures in the font
    (again, usually only one entry is present). Hence the following calls are
    equivalent:

    .. code:: python

            tt["CFF "].cff[0]
            # <fontTools.cffLib.TopDict object at 0x102ed6e50>
            tt["CFF "].cff.topDictIndex[0]
            # <fontTools.cffLib.TopDict object at 0x102ed6e50>

    """

    compilerClass = TopDictIndexCompiler

    def __init__(self, file=None, cff2GetGlyphOrder=None, topSize=0, isCFF2=None):
        self.cff2GetGlyphOrder = cff2GetGlyphOrder
        if file is not None and isCFF2:
            self._isCFF2 = isCFF2
            self.items = []
            name = self.__class__.__name__
            log.log(DEBUG, "loading %s at %s", name, file.tell())
            self.file = file
            count = 1
            self.items = [None] * count
            self.offsets = [0, topSize]
            self.offsetBase = file.tell()
            # pretend we've read the whole lot
            file.seek(self.offsetBase + topSize)
            log.log(DEBUG, "    end of %s at %s", name, file.tell())
        else:
            super(TopDictIndex, self).__init__(file, isCFF2=isCFF2)

    def produceItem(self, index, data, file, offset):
        top = TopDict(
            self.strings,
            file,
            offset,
            self.GlobalSubrs,
            self.cff2GetGlyphOrder,
            isCFF2=self._isCFF2,
        )
        top.decompile(data)
        return top

    def toXML(self, xmlWriter):
        for i in range(len(self)):
            xmlWriter.begintag("FontDict", index=i)
            xmlWriter.newline()
            self[i].toXML(xmlWriter)
            xmlWriter.endtag("FontDict")
            xmlWriter.newline()


class FDArrayIndex(Index):
    compilerClass = FDArrayIndexCompiler

    def toXML(self, xmlWriter):
        for i in range(len(self)):
            xmlWriter.begintag("FontDict", index=i)
            xmlWriter.newline()
            self[i].toXML(xmlWriter)
            xmlWriter.endtag("FontDict")
            xmlWriter.newline()

    def produceItem(self, index, data, file, offset):
        fontDict = FontDict(
            self.strings,
            file,
            offset,
            self.GlobalSubrs,
            isCFF2=self._isCFF2,
            vstore=self.vstore,
        )
        fontDict.decompile(data)
        return fontDict

    def fromXML(self, name, attrs, content):
        if name != "FontDict":
            return
        fontDict = FontDict()
        for element in content:
            if isinstance(element, str):
                continue
            name, attrs, content = element
            fontDict.fromXML(name, attrs, content)
        self.append(fontDict)


class VarStoreData(object):
    def __init__(self, file=None, otVarStore=None):
        self.file = file
        self.data = None
        self.otVarStore = otVarStore
        self.font = TTFont()  # dummy font for the decompile function.

    def decompile(self):
        if self.file:
            # read data in from file. Assume position is correct.
            length = readCard16(self.file)
            self.data = self.file.read(length)
            globalState = {}
            reader = OTTableReader(self.data, globalState)
            self.otVarStore = ot.VarStore()
            self.otVarStore.decompile(reader, self.font)
            self.data = None
        return self

    def compile(self):
        writer = OTTableWriter()
        self.otVarStore.compile(writer, self.font)
        # Note that this omits the initial Card16 length from the CFF2
        # VarStore data block
        self.data = writer.getAllData()

    def writeXML(self, xmlWriter, name):
        self.otVarStore.toXML(xmlWriter, self.font)

    def xmlRead(self, name, attrs, content, parent):
        self.otVarStore = ot.VarStore()
        for element in content:
            if isinstance(element, tuple):
                name, attrs, content = element
                self.otVarStore.fromXML(name, attrs, content, self.font)
            else:
                pass
        return None

    def __len__(self):
        return len(self.data)

    def getNumRegions(self, vsIndex):
        if vsIndex is None:
            vsIndex = 0
        varData = self.otVarStore.VarData[vsIndex]
        numRegions = varData.VarRegionCount
        return numRegions


class FDSelect(object):
    def __init__(self, file=None, numGlyphs=None, format=None):
        if file:
            # read data in from file
            self.format = readCard8(file)
            if self.format == 0:
                from array import array

                self.gidArray = array("B", file.read(numGlyphs)).tolist()
            elif self.format == 3:
                gidArray = [None] * numGlyphs
                nRanges = readCard16(file)
                fd = None
                prev = None
                for i in range(nRanges):
                    first = readCard16(file)
                    if prev is not None:
                        for glyphID in range(prev, first):
                            gidArray[glyphID] = fd
                    prev = first
                    fd = readCard8(file)
                if prev is not None:
                    first = readCard16(file)
                    for glyphID in range(prev, first):
                        gidArray[glyphID] = fd
                self.gidArray = gidArray
            elif self.format == 4:
                gidArray = [None] * numGlyphs
                nRanges = readCard32(file)
                fd = None
                prev = None
                for i in range(nRanges):
                    first = readCard32(file)
                    if prev is not None:
                        for glyphID in range(prev, first):
                            gidArray[glyphID] = fd
                    prev = first
                    fd = readCard16(file)
                if prev is not None:
                    first = readCard32(file)
                    for glyphID in range(prev, first):
                        gidArray[glyphID] = fd
                self.gidArray = gidArray
            else:
                assert False, "unsupported FDSelect format: %s" % format
        else:
            # reading from XML. Make empty gidArray, and leave format as passed in.
            # format is None will result in the smallest representation being used.
            self.format = format
            self.gidArray = []

    def __len__(self):
        return len(self.gidArray)

    def __getitem__(self, index):
        return self.gidArray[index]

    def __setitem__(self, index, fdSelectValue):
        self.gidArray[index] = fdSelectValue

    def append(self, fdSelectValue):
        self.gidArray.append(fdSelectValue)


class CharStrings(object):
    """The ``CharStrings`` in the font represent the instructions for drawing
    each glyph. This object presents a dictionary interface to the font's
    CharStrings, indexed by glyph name:

    .. code:: python

            tt["CFF "].cff[0].CharStrings["a"]
            # <T2CharString (bytecode) at 103451e90>

    See :class:`fontTools.misc.psCharStrings.T1CharString` and
    :class:`fontTools.misc.psCharStrings.T2CharString` for how to decompile,
    compile and interpret the glyph drawing instructions in the returned objects.

    """

    def __init__(
        self,
        file,
        charset,
        globalSubrs,
        private,
        fdSelect,
        fdArray,
        isCFF2=None,
        varStore=None,
    ):
        self.globalSubrs = globalSubrs
        self.varStore = varStore
        if file is not None:
            self.charStringsIndex = SubrsIndex(
                file, globalSubrs, private, fdSelect, fdArray, isCFF2=isCFF2
            )
            self.charStrings = charStrings = {}
            for i in range(len(charset)):
                charStrings[charset[i]] = i
            # read from OTF file: charStrings.values() are indices into
            # charStringsIndex.
            self.charStringsAreIndexed = 1
        else:
            self.charStrings = {}
            # read from ttx file: charStrings.values() are actual charstrings
            self.charStringsAreIndexed = 0
            self.private = private
            if fdSelect is not None:
                self.fdSelect = fdSelect
            if fdArray is not None:
                self.fdArray = fdArray

    def keys(self):
        return list(self.charStrings.keys())

    def values(self):
        if self.charStringsAreIndexed:
            return self.charStringsIndex
        else:
            return list(self.charStrings.values())

    def has_key(self, name):
        return name in self.charStrings

    __contains__ = has_key

    def __len__(self):
        return len(self.charStrings)

    def __getitem__(self, name):
        charString = self.charStrings[name]
        if self.charStringsAreIndexed:
            charString = self.charStringsIndex[charString]
        return charString

    def __setitem__(self, name, charString):
        if self.charStringsAreIndexed:
            index = self.charStrings[name]
            self.charStringsIndex[index] = charString
        else:
            self.charStrings[name] = charString

    def getItemAndSelector(self, name):
        if self.charStringsAreIndexed:
            index = self.charStrings[name]
            return self.charStringsIndex.getItemAndSelector(index)
        else:
            if hasattr(self, "fdArray"):
                if hasattr(self, "fdSelect"):
                    sel = self.charStrings[name].fdSelectIndex
                else:
                    sel = 0
            else:
                sel = None
            return self.charStrings[name], sel

    def toXML(self, xmlWriter):
        names = sorted(self.keys())
        for name in names:
            charStr, fdSelectIndex = self.getItemAndSelector(name)
            if charStr.needsDecompilation():
                raw = [("raw", 1)]
            else:
                raw = []
            if fdSelectIndex is None:
                xmlWriter.begintag("CharString", [("name", name)] + raw)
            else:
                xmlWriter.begintag(
                    "CharString",
                    [("name", name), ("fdSelectIndex", fdSelectIndex)] + raw,
                )
            xmlWriter.newline()
            charStr.toXML(xmlWriter)
            xmlWriter.endtag("CharString")
            xmlWriter.newline()

    def fromXML(self, name, attrs, content):
        for element in content:
            if isinstance(element, str):
                continue
            name, attrs, content = element
            if name != "CharString":
                continue
            fdID = -1
            if hasattr(self, "fdArray"):
                try:
                    fdID = safeEval(attrs["fdSelectIndex"])
                except KeyError:
                    fdID = 0
                private = self.fdArray[fdID].Private
            else:
                private = self.private

            glyphName = attrs["name"]
            charStringClass = psCharStrings.T2CharString
            charString = charStringClass(private=private, globalSubrs=self.globalSubrs)
            charString.fromXML(name, attrs, content)
            if fdID >= 0:
                charString.fdSelectIndex = fdID
            self[glyphName] = charString


def readCard8(file):
    return byteord(file.read(1))


def readCard16(file):
    (value,) = struct.unpack(">H", file.read(2))
    return value


def readCard32(file):
    (value,) = struct.unpack(">L", file.read(4))
    return value


def writeCard8(file, value):
    file.write(bytechr(value))


def writeCard16(file, value):
    file.write(struct.pack(">H", value))


def writeCard32(file, value):
    file.write(struct.pack(">L", value))


def packCard8(value):
    return bytechr(value)


def packCard16(value):
    return struct.pack(">H", value)


def packCard32(value):
    return struct.pack(">L", value)


def buildOperatorDict(table):
    d = {}
    for op, name, arg, default, conv in table:
        d[op] = (name, arg)
    return d


def buildOpcodeDict(table):
    d = {}
    for op, name, arg, default, conv in table:
        if isinstance(op, tuple):
            op = bytechr(op[0]) + bytechr(op[1])
        else:
            op = bytechr(op)
        d[name] = (op, arg)
    return d


def buildOrder(table):
    l = []
    for op, name, arg, default, conv in table:
        l.append(name)
    return l


def buildDefaults(table):
    d = {}
    for op, name, arg, default, conv in table:
        if default is not None:
            d[name] = default
    return d


def buildConverters(table):
    d = {}
    for op, name, arg, default, conv in table:
        d[name] = conv
    return d


class SimpleConverter(object):
    def read(self, parent, value):
        if not hasattr(parent, "file"):
            return self._read(parent, value)
        file = parent.file
        pos = file.tell()
        try:
            return self._read(parent, value)
        finally:
            file.seek(pos)

    def _read(self, parent, value):
        return value

    def write(self, parent, value):
        return value

    def xmlWrite(self, xmlWriter, name, value):
        xmlWriter.simpletag(name, value=value)
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        return attrs["value"]


class ASCIIConverter(SimpleConverter):
    def _read(self, parent, value):
        return tostr(value, encoding="ascii")

    def write(self, parent, value):
        return tobytes(value, encoding="ascii")

    def xmlWrite(self, xmlWriter, name, value):
        xmlWriter.simpletag(name, value=tostr(value, encoding="ascii"))
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        return tobytes(attrs["value"], encoding=("ascii"))


class Latin1Converter(SimpleConverter):
    def _read(self, parent, value):
        return tostr(value, encoding="latin1")

    def write(self, parent, value):
        return tobytes(value, encoding="latin1")

    def xmlWrite(self, xmlWriter, name, value):
        value = tostr(value, encoding="latin1")
        if name in ["Notice", "Copyright"]:
            value = re.sub(r"[\r\n]\s+", " ", value)
        xmlWriter.simpletag(name, value=value)
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        return tobytes(attrs["value"], encoding=("latin1"))


def parseNum(s):
    try:
        value = int(s)
    except:
        value = float(s)
    return value


def parseBlendList(s):
    valueList = []
    for element in s:
        if isinstance(element, str):
            continue
        name, attrs, content = element
        blendList = attrs["value"].split()
        blendList = [eval(val) for val in blendList]
        valueList.append(blendList)
    if len(valueList) == 1:
        valueList = valueList[0]
    return valueList


class NumberConverter(SimpleConverter):
    def xmlWrite(self, xmlWriter, name, value):
        if isinstance(value, list):
            xmlWriter.begintag(name)
            xmlWriter.newline()
            xmlWriter.indent()
            blendValue = " ".join([str(val) for val in value])
            xmlWriter.simpletag(kBlendDictOpName, value=blendValue)
            xmlWriter.newline()
            xmlWriter.dedent()
            xmlWriter.endtag(name)
            xmlWriter.newline()
        else:
            xmlWriter.simpletag(name, value=value)
            xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        valueString = attrs.get("value", None)
        if valueString is None:
            value = parseBlendList(content)
        else:
            value = parseNum(attrs["value"])
        return value


class ArrayConverter(SimpleConverter):
    def xmlWrite(self, xmlWriter, name, value):
        if value and isinstance(value[0], list):
            xmlWriter.begintag(name)
            xmlWriter.newline()
            xmlWriter.indent()
            for valueList in value:
                blendValue = " ".join([str(val) for val in valueList])
                xmlWriter.simpletag(kBlendDictOpName, value=blendValue)
                xmlWriter.newline()
            xmlWriter.dedent()
            xmlWriter.endtag(name)
            xmlWriter.newline()
        else:
            value = " ".join([str(val) for val in value])
            xmlWriter.simpletag(name, value=value)
            xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        valueString = attrs.get("value", None)
        if valueString is None:
            valueList = parseBlendList(content)
        else:
            values = valueString.split()
            valueList = [parseNum(value) for value in values]
        return valueList


class TableConverter(SimpleConverter):
    def xmlWrite(self, xmlWriter, name, value):
        xmlWriter.begintag(name)
        xmlWriter.newline()
        value.toXML(xmlWriter)
        xmlWriter.endtag(name)
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        ob = self.getClass()()
        for element in content:
            if isinstance(element, str):
                continue
            name, attrs, content = element
            ob.fromXML(name, attrs, content)
        return ob


class PrivateDictConverter(TableConverter):
    def getClass(self):
        return PrivateDict

    def _read(self, parent, value):
        size, offset = value
        file = parent.file
        isCFF2 = parent._isCFF2
        try:
            vstore = parent.vstore
        except AttributeError:
            vstore = None
        priv = PrivateDict(parent.strings, file, offset, isCFF2=isCFF2, vstore=vstore)
        file.seek(offset)
        data = file.read(size)
        assert len(data) == size
        priv.decompile(data)
        return priv

    def write(self, parent, value):
        return (0, 0)  # dummy value


class SubrsConverter(TableConverter):
    def getClass(self):
        return SubrsIndex

    def _read(self, parent, value):
        file = parent.file
        isCFF2 = parent._isCFF2
        file.seek(parent.offset + value)  # Offset(self)
        return SubrsIndex(file, isCFF2=isCFF2)

    def write(self, parent, value):
        return 0  # dummy value


class CharStringsConverter(TableConverter):
    def _read(self, parent, value):
        file = parent.file
        isCFF2 = parent._isCFF2
        charset = parent.charset
        varStore = getattr(parent, "VarStore", None)
        globalSubrs = parent.GlobalSubrs
        if hasattr(parent, "FDArray"):
            fdArray = parent.FDArray
            if hasattr(parent, "FDSelect"):
                fdSelect = parent.FDSelect
            else:
                fdSelect = None
            private = None
        else:
            fdSelect, fdArray = None, None
            private = parent.Private
        file.seek(value)  # Offset(0)
        charStrings = CharStrings(
            file,
            charset,
            globalSubrs,
            private,
            fdSelect,
            fdArray,
            isCFF2=isCFF2,
            varStore=varStore,
        )
        return charStrings

    def write(self, parent, value):
        return 0  # dummy value

    def xmlRead(self, name, attrs, content, parent):
        if hasattr(parent, "FDArray"):
            # if it is a CID-keyed font, then the private Dict is extracted from the
            # parent.FDArray
            fdArray = parent.FDArray
            if hasattr(parent, "FDSelect"):
                fdSelect = parent.FDSelect
            else:
                fdSelect = None
            private = None
        else:
            # if it is a name-keyed font, then the private dict is in the top dict,
            # and
            # there is no fdArray.
            private, fdSelect, fdArray = parent.Private, None, None
        charStrings = CharStrings(
            None,
            None,
            parent.GlobalSubrs,
            private,
            fdSelect,
            fdArray,
            varStore=getattr(parent, "VarStore", None),
        )
        charStrings.fromXML(name, attrs, content)
        return charStrings


class CharsetConverter(SimpleConverter):
    def _read(self, parent, value):
        isCID = hasattr(parent, "ROS")
        if value > 2:
            numGlyphs = parent.numGlyphs
            file = parent.file
            file.seek(value)
            log.log(DEBUG, "loading charset at %s", value)
            format = readCard8(file)
            if format == 0:
                charset = parseCharset0(numGlyphs, file, parent.strings, isCID)
            elif format == 1 or format == 2:
                charset = parseCharset(numGlyphs, file, parent.strings, isCID, format)
            else:
                raise NotImplementedError
            assert len(charset) == numGlyphs
            log.log(DEBUG, "    charset end at %s", file.tell())
            # make sure glyph names are unique
            allNames = {}
            newCharset = []
            for glyphName in charset:
                if glyphName in allNames:
                    # make up a new glyphName that's unique
                    n = allNames[glyphName]
                    while (glyphName + "#" + str(n)) in allNames:
                        n += 1
                    allNames[glyphName] = n + 1
                    glyphName = glyphName + "#" + str(n)
                allNames[glyphName] = 1
                newCharset.append(glyphName)
            charset = newCharset
        else:  # offset == 0 -> no charset data.
            if isCID or "CharStrings" not in parent.rawDict:
                # We get here only when processing fontDicts from the FDArray of
                # CFF-CID fonts. Only the real topDict references the chrset.
                assert value == 0
                charset = None
            elif value == 0:
                charset = cffISOAdobeStrings
            elif value == 1:
                charset = cffIExpertStrings
            elif value == 2:
                charset = cffExpertSubsetStrings
        if charset and (len(charset) != parent.numGlyphs):
            charset = charset[: parent.numGlyphs]
        return charset

    def write(self, parent, value):
        return 0  # dummy value

    def xmlWrite(self, xmlWriter, name, value):
        # XXX only write charset when not in OT/TTX context, where we
        # dump charset as a separate "GlyphOrder" table.
        # # xmlWriter.simpletag("charset")
        xmlWriter.comment("charset is dumped separately as the 'GlyphOrder' element")
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        pass


class CharsetCompiler(object):
    def __init__(self, strings, charset, parent):
        assert charset[0] == ".notdef"
        isCID = hasattr(parent.dictObj, "ROS")
        data0 = packCharset0(charset, isCID, strings)
        data = packCharset(charset, isCID, strings)
        if len(data) < len(data0):
            self.data = data
        else:
            self.data = data0
        self.parent = parent

    def setPos(self, pos, endPos):
        self.parent.rawDict["charset"] = pos

    def getDataLength(self):
        return len(self.data)

    def toFile(self, file):
        file.write(self.data)


def getStdCharSet(charset):
    # check to see if we can use a predefined charset value.
    predefinedCharSetVal = None
    predefinedCharSets = [
        (cffISOAdobeStringCount, cffISOAdobeStrings, 0),
        (cffExpertStringCount, cffIExpertStrings, 1),
        (cffExpertSubsetStringCount, cffExpertSubsetStrings, 2),
    ]
    lcs = len(charset)
    for cnt, pcs, csv in predefinedCharSets:
        if predefinedCharSetVal is not None:
            break
        if lcs > cnt:
            continue
        predefinedCharSetVal = csv
        for i in range(lcs):
            if charset[i] != pcs[i]:
                predefinedCharSetVal = None
                break
    return predefinedCharSetVal


def getCIDfromName(name, strings):
    return int(name[3:])


def getSIDfromName(name, strings):
    return strings.getSID(name)


def packCharset0(charset, isCID, strings):
    fmt = 0
    data = [packCard8(fmt)]
    if isCID:
        getNameID = getCIDfromName
    else:
        getNameID = getSIDfromName

    for name in charset[1:]:
        data.append(packCard16(getNameID(name, strings)))
    return bytesjoin(data)


def packCharset(charset, isCID, strings):
    fmt = 1
    ranges = []
    first = None
    end = 0
    if isCID:
        getNameID = getCIDfromName
    else:
        getNameID = getSIDfromName

    for name in charset[1:]:
        SID = getNameID(name, strings)
        if first is None:
            first = SID
        elif end + 1 != SID:
            nLeft = end - first
            if nLeft > 255:
                fmt = 2
            ranges.append((first, nLeft))
            first = SID
        end = SID
    if end:
        nLeft = end - first
        if nLeft > 255:
            fmt = 2
        ranges.append((first, nLeft))

    data = [packCard8(fmt)]
    if fmt == 1:
        nLeftFunc = packCard8
    else:
        nLeftFunc = packCard16
    for first, nLeft in ranges:
        data.append(packCard16(first) + nLeftFunc(nLeft))
    return bytesjoin(data)


def parseCharset0(numGlyphs, file, strings, isCID):
    charset = [".notdef"]
    if isCID:
        for i in range(numGlyphs - 1):
            CID = readCard16(file)
            charset.append("cid" + str(CID).zfill(5))
    else:
        for i in range(numGlyphs - 1):
            SID = readCard16(file)
            charset.append(strings[SID])
    return charset


def parseCharset(numGlyphs, file, strings, isCID, fmt):
    charset = [".notdef"]
    count = 1
    if fmt == 1:
        nLeftFunc = readCard8
    else:
        nLeftFunc = readCard16
    while count < numGlyphs:
        first = readCard16(file)
        nLeft = nLeftFunc(file)
        if isCID:
            for CID in range(first, first + nLeft + 1):
                charset.append("cid" + str(CID).zfill(5))
        else:
            for SID in range(first, first + nLeft + 1):
                charset.append(strings[SID])
        count = count + nLeft + 1
    return charset


class EncodingCompiler(object):
    def __init__(self, strings, encoding, parent):
        assert not isinstance(encoding, str)
        data0 = packEncoding0(parent.dictObj.charset, encoding, parent.strings)
        data1 = packEncoding1(parent.dictObj.charset, encoding, parent.strings)
        if len(data0) < len(data1):
            self.data = data0
        else:
            self.data = data1
        self.parent = parent

    def setPos(self, pos, endPos):
        self.parent.rawDict["Encoding"] = pos

    def getDataLength(self):
        return len(self.data)

    def toFile(self, file):
        file.write(self.data)


class EncodingConverter(SimpleConverter):
    def _read(self, parent, value):
        if value == 0:
            return "StandardEncoding"
        elif value == 1:
            return "ExpertEncoding"
        else:
            assert value > 1
            file = parent.file
            file.seek(value)
            log.log(DEBUG, "loading Encoding at %s", value)
            fmt = readCard8(file)
            haveSupplement = fmt & 0x80
            if haveSupplement:
                raise NotImplementedError("Encoding supplements are not yet supported")
            fmt = fmt & 0x7F
            if fmt == 0:
                encoding = parseEncoding0(
                    parent.charset, file, haveSupplement, parent.strings
                )
            elif fmt == 1:
                encoding = parseEncoding1(
                    parent.charset, file, haveSupplement, parent.strings
                )
            return encoding

    def write(self, parent, value):
        if value == "StandardEncoding":
            return 0
        elif value == "ExpertEncoding":
            return 1
        return 0  # dummy value

    def xmlWrite(self, xmlWriter, name, value):
        if value in ("StandardEncoding", "ExpertEncoding"):
            xmlWriter.simpletag(name, name=value)
            xmlWriter.newline()
            return
        xmlWriter.begintag(name)
        xmlWriter.newline()
        for code in range(len(value)):
            glyphName = value[code]
            if glyphName != ".notdef":
                xmlWriter.simpletag("map", code=hex(code), name=glyphName)
                xmlWriter.newline()
        xmlWriter.endtag(name)
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        if "name" in attrs:
            return attrs["name"]
        encoding = [".notdef"] * 256
        for element in content:
            if isinstance(element, str):
                continue
            name, attrs, content = element
            code = safeEval(attrs["code"])
            glyphName = attrs["name"]
            encoding[code] = glyphName
        return encoding


def parseEncoding0(charset, file, haveSupplement, strings):
    nCodes = readCard8(file)
    encoding = [".notdef"] * 256
    for glyphID in range(1, nCodes + 1):
        code = readCard8(file)
        if code != 0:
            encoding[code] = charset[glyphID]
    return encoding


def parseEncoding1(charset, file, haveSupplement, strings):
    nRanges = readCard8(file)
    encoding = [".notdef"] * 256
    glyphID = 1
    for i in range(nRanges):
        code = readCard8(file)
        nLeft = readCard8(file)
        for glyphID in range(glyphID, glyphID + nLeft + 1):
            encoding[code] = charset[glyphID]
            code = code + 1
        glyphID = glyphID + 1
    return encoding


def packEncoding0(charset, encoding, strings):
    fmt = 0
    m = {}
    for code in range(len(encoding)):
        name = encoding[code]
        if name != ".notdef":
            m[name] = code
    codes = []
    for name in charset[1:]:
        code = m.get(name)
        codes.append(code)

    while codes and codes[-1] is None:
        codes.pop()

    data = [packCard8(fmt), packCard8(len(codes))]
    for code in codes:
        if code is None:
            code = 0
        data.append(packCard8(code))
    return bytesjoin(data)


def packEncoding1(charset, encoding, strings):
    fmt = 1
    m = {}
    for code in range(len(encoding)):
        name = encoding[code]
        if name != ".notdef":
            m[name] = code
    ranges = []
    first = None
    end = 0
    for name in charset[1:]:
        code = m.get(name, -1)
        if first is None:
            first = code
        elif end + 1 != code:
            nLeft = end - first
            ranges.append((first, nLeft))
            first = code
        end = code
    nLeft = end - first
    ranges.append((first, nLeft))

    # remove unencoded glyphs at the end.
    while ranges and ranges[-1][0] == -1:
        ranges.pop()

    data = [packCard8(fmt), packCard8(len(ranges))]
    for first, nLeft in ranges:
        if first == -1:  # unencoded
            first = 0
        data.append(packCard8(first) + packCard8(nLeft))
    return bytesjoin(data)


class FDArrayConverter(TableConverter):
    def _read(self, parent, value):
        try:
            vstore = parent.VarStore
        except AttributeError:
            vstore = None
        file = parent.file
        isCFF2 = parent._isCFF2
        file.seek(value)
        fdArray = FDArrayIndex(file, isCFF2=isCFF2)
        fdArray.vstore = vstore
        fdArray.strings = parent.strings
        fdArray.GlobalSubrs = parent.GlobalSubrs
        return fdArray

    def write(self, parent, value):
        return 0  # dummy value

    def xmlRead(self, name, attrs, content, parent):
        fdArray = FDArrayIndex()
        for element in content:
            if isinstance(element, str):
                continue
            name, attrs, content = element
            fdArray.fromXML(name, attrs, content)
        return fdArray


class FDSelectConverter(SimpleConverter):
    def _read(self, parent, value):
        file = parent.file
        file.seek(value)
        fdSelect = FDSelect(file, parent.numGlyphs)
        return fdSelect

    def write(self, parent, value):
        return 0  # dummy value

    # The FDSelect glyph data is written out to XML in the charstring keys,
    # so we write out only the format selector
    def xmlWrite(self, xmlWriter, name, value):
        xmlWriter.simpletag(name, [("format", value.format)])
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        fmt = safeEval(attrs["format"])
        file = None
        numGlyphs = None
        fdSelect = FDSelect(file, numGlyphs, fmt)
        return fdSelect


class VarStoreConverter(SimpleConverter):
    def _read(self, parent, value):
        file = parent.file
        file.seek(value)
        varStore = VarStoreData(file)
        varStore.decompile()
        return varStore

    def write(self, parent, value):
        return 0  # dummy value

    def xmlWrite(self, xmlWriter, name, value):
        value.writeXML(xmlWriter, name)

    def xmlRead(self, name, attrs, content, parent):
        varStore = VarStoreData()
        varStore.xmlRead(name, attrs, content, parent)
        return varStore


def packFDSelect0(fdSelectArray):
    fmt = 0
    data = [packCard8(fmt)]
    for index in fdSelectArray:
        data.append(packCard8(index))
    return bytesjoin(data)


def packFDSelect3(fdSelectArray):
    fmt = 3
    fdRanges = []
    lenArray = len(fdSelectArray)
    lastFDIndex = -1
    for i in range(lenArray):
        fdIndex = fdSelectArray[i]
        if lastFDIndex != fdIndex:
            fdRanges.append([i, fdIndex])
            lastFDIndex = fdIndex
    sentinelGID = i + 1

    data = [packCard8(fmt)]
    data.append(packCard16(len(fdRanges)))
    for fdRange in fdRanges:
        data.append(packCard16(fdRange[0]))
        data.append(packCard8(fdRange[1]))
    data.append(packCard16(sentinelGID))
    return bytesjoin(data)


def packFDSelect4(fdSelectArray):
    fmt = 4
    fdRanges = []
    lenArray = len(fdSelectArray)
    lastFDIndex = -1
    for i in range(lenArray):
        fdIndex = fdSelectArray[i]
        if lastFDIndex != fdIndex:
            fdRanges.append([i, fdIndex])
            lastFDIndex = fdIndex
    sentinelGID = i + 1

    data = [packCard8(fmt)]
    data.append(packCard32(len(fdRanges)))
    for fdRange in fdRanges:
        data.append(packCard32(fdRange[0]))
        data.append(packCard16(fdRange[1]))
    data.append(packCard32(sentinelGID))
    return bytesjoin(data)


class FDSelectCompiler(object):
    def __init__(self, fdSelect, parent):
        fmt = fdSelect.format
        fdSelectArray = fdSelect.gidArray
        if fmt == 0:
            self.data = packFDSelect0(fdSelectArray)
        elif fmt == 3:
            self.data = packFDSelect3(fdSelectArray)
        elif fmt == 4:
            self.data = packFDSelect4(fdSelectArray)
        else:
            # choose smaller of the two formats
            data0 = packFDSelect0(fdSelectArray)
            data3 = packFDSelect3(fdSelectArray)
            if len(data0) < len(data3):
                self.data = data0
                fdSelect.format = 0
            else:
                self.data = data3
                fdSelect.format = 3

        self.parent = parent

    def setPos(self, pos, endPos):
        self.parent.rawDict["FDSelect"] = pos

    def getDataLength(self):
        return len(self.data)

    def toFile(self, file):
        file.write(self.data)


class VarStoreCompiler(object):
    def __init__(self, varStoreData, parent):
        self.parent = parent
        if not varStoreData.data:
            varStoreData.compile()
        data = [packCard16(len(varStoreData.data)), varStoreData.data]
        self.data = bytesjoin(data)

    def setPos(self, pos, endPos):
        self.parent.rawDict["VarStore"] = pos

    def getDataLength(self):
        return len(self.data)

    def toFile(self, file):
        file.write(self.data)


class ROSConverter(SimpleConverter):
    def xmlWrite(self, xmlWriter, name, value):
        registry, order, supplement = value
        xmlWriter.simpletag(
            name,
            [
                ("Registry", tostr(registry)),
                ("Order", tostr(order)),
                ("Supplement", supplement),
            ],
        )
        xmlWriter.newline()

    def xmlRead(self, name, attrs, content, parent):
        return (attrs["Registry"], attrs["Order"], safeEval(attrs["Supplement"]))


topDictOperators = [
    # 	opcode		name			argument type	default	converter
    (25, "maxstack", "number", None, None),
    ((12, 30), "ROS", ("SID", "SID", "number"), None, ROSConverter()),
    ((12, 20), "SyntheticBase", "number", None, None),
    (0, "version", "SID", None, None),
    (1, "Notice", "SID", None, Latin1Converter()),
    ((12, 0), "Copyright", "SID", None, Latin1Converter()),
    (2, "FullName", "SID", None, Latin1Converter()),
    ((12, 38), "FontName", "SID", None, Latin1Converter()),
    (3, "FamilyName", "SID", None, Latin1Converter()),
    (4, "Weight", "SID", None, None),
    ((12, 1), "isFixedPitch", "number", 0, None),
    ((12, 2), "ItalicAngle", "number", 0, None),
    ((12, 3), "UnderlinePosition", "number", -100, None),
    ((12, 4), "UnderlineThickness", "number", 50, None),
    ((12, 5), "PaintType", "number", 0, None),
    ((12, 6), "CharstringType", "number", 2, None),
    ((12, 7), "FontMatrix", "array", [0.001, 0, 0, 0.001, 0, 0], None),
    (13, "UniqueID", "number", None, None),
    (5, "FontBBox", "array", [0, 0, 0, 0], None),
    ((12, 8), "StrokeWidth", "number", 0, None),
    (14, "XUID", "array", None, None),
    ((12, 21), "PostScript", "SID", None, None),
    ((12, 22), "BaseFontName", "SID", None, None),
    ((12, 23), "BaseFontBlend", "delta", None, None),
    ((12, 31), "CIDFontVersion", "number", 0, None),
    ((12, 32), "CIDFontRevision", "number", 0, None),
    ((12, 33), "CIDFontType", "number", 0, None),
    ((12, 34), "CIDCount", "number", 8720, None),
    (15, "charset", "number", None, CharsetConverter()),
    ((12, 35), "UIDBase", "number", None, None),
    (16, "Encoding", "number", 0, EncodingConverter()),
    (18, "Private", ("number", "number"), None, PrivateDictConverter()),
    ((12, 37), "FDSelect", "number", None, FDSelectConverter()),
    ((12, 36), "FDArray", "number", None, FDArrayConverter()),
    (17, "CharStrings", "number", None, CharStringsConverter()),
    (24, "VarStore", "number", None, VarStoreConverter()),
]

topDictOperators2 = [
    # 	opcode		name			argument type	default	converter
    (25, "maxstack", "number", None, None),
    ((12, 7), "FontMatrix", "array", [0.001, 0, 0, 0.001, 0, 0], None),
    ((12, 37), "FDSelect", "number", None, FDSelectConverter()),
    ((12, 36), "FDArray", "number", None, FDArrayConverter()),
    (17, "CharStrings", "number", None, CharStringsConverter()),
    (24, "VarStore", "number", None, VarStoreConverter()),
]

# Note! FDSelect and FDArray must both preceed CharStrings in the output XML build order,
# in order for the font to compile back from xml.

kBlendDictOpName = "blend"
blendOp = 23

privateDictOperators = [
    # 	opcode		name			argument type	default	converter
    (22, "vsindex", "number", None, None),
    (
        blendOp,
        kBlendDictOpName,
        "blendList",
        None,
        None,
    ),  # This is for reading to/from XML: it not written to CFF.
    (6, "BlueValues", "delta", None, None),
    (7, "OtherBlues", "delta", None, None),
    (8, "FamilyBlues", "delta", None, None),
    (9, "FamilyOtherBlues", "delta", None, None),
    ((12, 9), "BlueScale", "number", 0.039625, None),
    ((12, 10), "BlueShift", "number", 7, None),
    ((12, 11), "BlueFuzz", "number", 1, None),
    (10, "StdHW", "number", None, None),
    (11, "StdVW", "number", None, None),
    ((12, 12), "StemSnapH", "delta", None, None),
    ((12, 13), "StemSnapV", "delta", None, None),
    ((12, 14), "ForceBold", "number", 0, None),
    ((12, 15), "ForceBoldThreshold", "number", None, None),  # deprecated
    ((12, 16), "lenIV", "number", None, None),  # deprecated
    ((12, 17), "LanguageGroup", "number", 0, None),
    ((12, 18), "ExpansionFactor", "number", 0.06, None),
    ((12, 19), "initialRandomSeed", "number", 0, None),
    (20, "defaultWidthX", "number", 0, None),
    (21, "nominalWidthX", "number", 0, None),
    (19, "Subrs", "number", None, SubrsConverter()),
]

privateDictOperators2 = [
    # 	opcode		name			argument type	default	converter
    (22, "vsindex", "number", None, None),
    (
        blendOp,
        kBlendDictOpName,
        "blendList",
        None,
        None,
    ),  # This is for reading to/from XML: it not written to CFF.
    (6, "BlueValues", "delta", None, None),
    (7, "OtherBlues", "delta", None, None),
    (8, "FamilyBlues", "delta", None, None),
    (9, "FamilyOtherBlues", "delta", None, None),
    ((12, 9), "BlueScale", "number", 0.039625, None),
    ((12, 10), "BlueShift", "number", 7, None),
    ((12, 11), "BlueFuzz", "number", 1, None),
    (10, "StdHW", "number", None, None),
    (11, "StdVW", "number", None, None),
    ((12, 12), "StemSnapH", "delta", None, None),
    ((12, 13), "StemSnapV", "delta", None, None),
    ((12, 17), "LanguageGroup", "number", 0, None),
    ((12, 18), "ExpansionFactor", "number", 0.06, None),
    (19, "Subrs", "number", None, SubrsConverter()),
]


def addConverters(table):
    for i in range(len(table)):
        op, name, arg, default, conv = table[i]
        if conv is not None:
            continue
        if arg in ("delta", "array"):
            conv = ArrayConverter()
        elif arg == "number":
            conv = NumberConverter()
        elif arg == "SID":
            conv = ASCIIConverter()
        elif arg == "blendList":
            conv = None
        else:
            assert False
        table[i] = op, name, arg, default, conv


addConverters(privateDictOperators)
addConverters(topDictOperators)


class TopDictDecompiler(psCharStrings.DictDecompiler):
    operators = buildOperatorDict(topDictOperators)


class PrivateDictDecompiler(psCharStrings.DictDecompiler):
    operators = buildOperatorDict(privateDictOperators)


class DictCompiler(object):
    maxBlendStack = 0

    def __init__(self, dictObj, strings, parent, isCFF2=None):
        if strings:
            assert isinstance(strings, IndexedStrings)
        if isCFF2 is None and hasattr(parent, "isCFF2"):
            isCFF2 = parent.isCFF2
            assert isCFF2 is not None
        self.isCFF2 = isCFF2
        self.dictObj = dictObj
        self.strings = strings
        self.parent = parent
        rawDict = {}
        for name in dictObj.order:
            value = getattr(dictObj, name, None)
            if value is None:
                continue
            conv = dictObj.converters[name]
            value = conv.write(dictObj, value)
            if value == dictObj.defaults.get(name):
                continue
            rawDict[name] = value
        self.rawDict = rawDict

    def setPos(self, pos, endPos):
        pass

    def getDataLength(self):
        return len(self.compile("getDataLength"))

    def compile(self, reason):
        log.log(DEBUG, "-- compiling %s for %s", self.__class__.__name__, reason)
        rawDict = self.rawDict
        data = []
        for name in self.dictObj.order:
            value = rawDict.get(name)
            if value is None:
                continue
            op, argType = self.opcodes[name]
            if isinstance(argType, tuple):
                l = len(argType)
                assert len(value) == l, "value doesn't match arg type"
                for i in range(l):
                    arg = argType[i]
                    v = value[i]
                    arghandler = getattr(self, "arg_" + arg)
                    data.append(arghandler(v))
            else:
                arghandler = getattr(self, "arg_" + argType)
                data.append(arghandler(value))
            data.append(op)
        data = bytesjoin(data)
        return data

    def toFile(self, file):
        data = self.compile("toFile")
        file.write(data)

    def arg_number(self, num):
        if isinstance(num, list):
            data = [encodeNumber(val) for val in num]
            data.append(encodeNumber(1))
            data.append(bytechr(blendOp))
            datum = bytesjoin(data)
        else:
            datum = encodeNumber(num)
        return datum

    def arg_SID(self, s):
        return psCharStrings.encodeIntCFF(self.strings.getSID(s))

    def arg_array(self, value):
        data = []
        for num in value:
            data.append(self.arg_number(num))
        return bytesjoin(data)

    def arg_delta(self, value):
        if not value:
            return b""
        val0 = value[0]
        if isinstance(val0, list):
            data = self.arg_delta_blend(value)
        else:
            out = []
            last = 0
            for v in value:
                out.append(v - last)
                last = v
            data = []
            for num in out:
                data.append(encodeNumber(num))
        return bytesjoin(data)

    def arg_delta_blend(self, value):
        """A delta list with blend lists has to be *all* blend lists.

        The value is a list is arranged as follows::

                [
                        [V0, d0..dn]
                        [V1, d0..dn]
                        ...
                        [Vm, d0..dn]
                ]

        ``V`` is the absolute coordinate value from the default font, and ``d0-dn``
        are the delta values from the *n* regions. Each ``V`` is an absolute
        coordinate from the default font.

        We want to return a list::

                [
                        [v0, v1..vm]
                        [d0..dn]
                        ...
                        [d0..dn]
                        numBlends
                        blendOp
                ]

        where each ``v`` is relative to the previous default font value.
        """
        numMasters = len(value[0])
        numBlends = len(value)
        numStack = (numBlends * numMasters) + 1
        if numStack > self.maxBlendStack:
            # Figure out the max number of value we can blend
            # and divide this list up into chunks of that size.

            numBlendValues = int((self.maxBlendStack - 1) / numMasters)
            out = []
            while True:
                numVal = min(len(value), numBlendValues)
                if numVal == 0:
                    break
                valList = value[0:numVal]
                out1 = self.arg_delta_blend(valList)
                out.extend(out1)
                value = value[numVal:]
        else:
            firstList = [0] * numBlends
            deltaList = [None] * numBlends
            i = 0
            prevVal = 0
            while i < numBlends:
                # For PrivateDict BlueValues, the default font
                # values are absolute, not relative.
                # Must convert these back to relative coordinates
                # befor writing to CFF2.
                defaultValue = value[i][0]
                firstList[i] = defaultValue - prevVal
                prevVal = defaultValue
                deltaList[i] = value[i][1:]
                i += 1

            relValueList = firstList
            for blendList in deltaList:
                relValueList.extend(blendList)
            out = [encodeNumber(val) for val in relValueList]
            out.append(encodeNumber(numBlends))
            out.append(bytechr(blendOp))
        return out


def encodeNumber(num):
    if isinstance(num, float):
        return psCharStrings.encodeFloat(num)
    else:
        return psCharStrings.encodeIntCFF(num)


class TopDictCompiler(DictCompiler):
    opcodes = buildOpcodeDict(topDictOperators)

    def getChildren(self, strings):
        isCFF2 = self.isCFF2
        children = []
        if self.dictObj.cff2GetGlyphOrder is None:
            if hasattr(self.dictObj, "charset") and self.dictObj.charset:
                if hasattr(self.dictObj, "ROS"):  # aka isCID
                    charsetCode = None
                else:
                    charsetCode = getStdCharSet(self.dictObj.charset)
                if charsetCode is None:
                    children.append(
                        CharsetCompiler(strings, self.dictObj.charset, self)
                    )
                else:
                    self.rawDict["charset"] = charsetCode
            if hasattr(self.dictObj, "Encoding") and self.dictObj.Encoding:
                encoding = self.dictObj.Encoding
                if not isinstance(encoding, str):
                    children.append(EncodingCompiler(strings, encoding, self))
        else:
            if hasattr(self.dictObj, "VarStore"):
                varStoreData = self.dictObj.VarStore
                varStoreComp = VarStoreCompiler(varStoreData, self)
                children.append(varStoreComp)
        if hasattr(self.dictObj, "FDSelect"):
            # I have not yet supported merging a ttx CFF-CID font, as there are
            # interesting issues about merging the FDArrays. Here I assume that
            # either the font was read from XML, and the FDSelect indices are all
            # in the charstring data, or the FDSelect array is already fully defined.
            fdSelect = self.dictObj.FDSelect
            # probably read in from XML; assume fdIndex in CharString data
            if len(fdSelect) == 0:
                charStrings = self.dictObj.CharStrings
                for name in self.dictObj.charset:
                    fdSelect.append(charStrings[name].fdSelectIndex)
            fdSelectComp = FDSelectCompiler(fdSelect, self)
            children.append(fdSelectComp)
        if hasattr(self.dictObj, "CharStrings"):
            items = []
            charStrings = self.dictObj.CharStrings
            for name in self.dictObj.charset:
                items.append(charStrings[name])
            charStringsComp = CharStringsCompiler(items, strings, self, isCFF2=isCFF2)
            children.append(charStringsComp)
        if hasattr(self.dictObj, "FDArray"):
            # I have not yet supported merging a ttx CFF-CID font, as there are
            # interesting issues about merging the FDArrays. Here I assume that the
            # FDArray info is correct and complete.
            fdArrayIndexComp = self.dictObj.FDArray.getCompiler(strings, self)
            children.append(fdArrayIndexComp)
            children.extend(fdArrayIndexComp.getChildren(strings))
        if hasattr(self.dictObj, "Private"):
            privComp = self.dictObj.Private.getCompiler(strings, self)
            children.append(privComp)
            children.extend(privComp.getChildren(strings))
        return children


class FontDictCompiler(DictCompiler):
    opcodes = buildOpcodeDict(topDictOperators)

    def __init__(self, dictObj, strings, parent, isCFF2=None):
        super(FontDictCompiler, self).__init__(dictObj, strings, parent, isCFF2=isCFF2)
        #
        # We now take some effort to detect if there were any key/value pairs
        # supplied that were ignored in the FontDict context, and issue a warning
        # for those cases.
        #
        ignoredNames = []
        dictObj = self.dictObj
        for name in sorted(set(dictObj.converters) - set(dictObj.order)):
            if name in dictObj.rawDict:
                # The font was directly read from binary. In this
                # case, we want to report *all* "useless" key/value
                # pairs that are in the font, not just the ones that
                # are different from the default.
                ignoredNames.append(name)
            else:
                # The font was probably read from a TTX file. We only
                # warn about keys whos value is not the default. The
                # ones that have the default value will not be written
                # to binary anyway.
                default = dictObj.defaults.get(name)
                if default is not None:
                    conv = dictObj.converters[name]
                    default = conv.read(dictObj, default)
                if getattr(dictObj, name, None) != default:
                    ignoredNames.append(name)
        if ignoredNames:
            log.warning(
                "Some CFF FDArray/FontDict keys were ignored upon compile: "
                + " ".join(sorted(ignoredNames))
            )

    def getChildren(self, strings):
        children = []
        if hasattr(self.dictObj, "Private"):
            privComp = self.dictObj.Private.getCompiler(strings, self)
            children.append(privComp)
            children.extend(privComp.getChildren(strings))
        return children


class PrivateDictCompiler(DictCompiler):
    maxBlendStack = maxStackLimit
    opcodes = buildOpcodeDict(privateDictOperators)

    def setPos(self, pos, endPos):
        size = endPos - pos
        self.parent.rawDict["Private"] = size, pos
        self.pos = pos

    def getChildren(self, strings):
        children = []
        if hasattr(self.dictObj, "Subrs"):
            children.append(self.dictObj.Subrs.getCompiler(strings, self))
        return children


class BaseDict(object):
    def __init__(self, strings=None, file=None, offset=None, isCFF2=None):
        assert (isCFF2 is None) == (file is None)
        self.rawDict = {}
        self.skipNames = []
        self.strings = strings
        if file is None:
            return
        self._isCFF2 = isCFF2
        self.file = file
        if offset is not None:
            log.log(DEBUG, "loading %s at %s", self.__class__.__name__, offset)
            self.offset = offset

    def decompile(self, data):
        log.log(DEBUG, "    length %s is %d", self.__class__.__name__, len(data))
        dec = self.decompilerClass(self.strings, self)
        dec.decompile(data)
        self.rawDict = dec.getDict()
        self.postDecompile()

    def postDecompile(self):
        pass

    def getCompiler(self, strings, parent, isCFF2=None):
        return self.compilerClass(self, strings, parent, isCFF2=isCFF2)

    def __getattr__(self, name):
        if name[:2] == name[-2:] == "__":
            # to make deepcopy() and pickle.load() work, we need to signal with
            # AttributeError that dunder methods like '__deepcopy__' or '__getstate__'
            # aren't implemented. For more details, see:
            # https://github.com/fonttools/fonttools/pull/1488
            raise AttributeError(name)
        value = self.rawDict.get(name, None)
        if value is None:
            value = self.defaults.get(name)
        if value is None:
            raise AttributeError(name)
        conv = self.converters[name]
        value = conv.read(self, value)
        setattr(self, name, value)
        return value

    def toXML(self, xmlWriter):
        for name in self.order:
            if name in self.skipNames:
                continue
            value = getattr(self, name, None)
            # XXX For "charset" we never skip calling xmlWrite even if the
            # value is None, so we always write the following XML comment:
            #
            # <!-- charset is dumped separately as the 'GlyphOrder' element -->
            #
            # Charset is None when 'CFF ' table is imported from XML into an
            # empty TTFont(). By writing this comment all the time, we obtain
            # the same XML output whether roundtripping XML-to-XML or
            # dumping binary-to-XML
            if value is None and name != "charset":
                continue
            conv = self.converters[name]
            conv.xmlWrite(xmlWriter, name, value)
        ignoredNames = set(self.rawDict) - set(self.order)
        if ignoredNames:
            xmlWriter.comment(
                "some keys were ignored: %s" % " ".join(sorted(ignoredNames))
            )
            xmlWriter.newline()

    def fromXML(self, name, attrs, content):
        conv = self.converters[name]
        value = conv.xmlRead(name, attrs, content, self)
        setattr(self, name, value)


class TopDict(BaseDict):
    """The ``TopDict`` represents the top-level dictionary holding font
    information. CFF2 tables contain a restricted set of top-level entries
    as described `here <https://docs.microsoft.com/en-us/typography/opentype/spec/cff2#7-top-dict-data>`_,
    but CFF tables may contain a wider range of information. This information
    can be accessed through attributes or through the dictionary returned
    through the ``rawDict`` property:

    .. code:: python

            font = tt["CFF "].cff[0]
            font.FamilyName
            # 'Linux Libertine O'
            font.rawDict["FamilyName"]
            # 'Linux Libertine O'

    More information is available in the CFF file's private dictionary, accessed
    via the ``Private`` property:

    .. code:: python

            tt["CFF "].cff[0].Private.BlueValues
            # [-15, 0, 515, 515, 666, 666]

    """

    defaults = buildDefaults(topDictOperators)
    converters = buildConverters(topDictOperators)
    compilerClass = TopDictCompiler
    order = buildOrder(topDictOperators)
    decompilerClass = TopDictDecompiler

    def __init__(
        self,
        strings=None,
        file=None,
        offset=None,
        GlobalSubrs=None,
        cff2GetGlyphOrder=None,
        isCFF2=None,
    ):
        super(TopDict, self).__init__(strings, file, offset, isCFF2=isCFF2)
        self.cff2GetGlyphOrder = cff2GetGlyphOrder
        self.GlobalSubrs = GlobalSubrs
        if isCFF2:
            self.defaults = buildDefaults(topDictOperators2)
            self.charset = cff2GetGlyphOrder()
            self.order = buildOrder(topDictOperators2)
        else:
            self.defaults = buildDefaults(topDictOperators)
            self.order = buildOrder(topDictOperators)

    def getGlyphOrder(self):
        """Returns a list of glyph names in the CFF font."""
        return self.charset

    def postDecompile(self):
        offset = self.rawDict.get("CharStrings")
        if offset is None:
            return
        # get the number of glyphs beforehand.
        self.file.seek(offset)
        if self._isCFF2:
            self.numGlyphs = readCard32(self.file)
        else:
            self.numGlyphs = readCard16(self.file)

    def toXML(self, xmlWriter):
        if hasattr(self, "CharStrings"):
            self.decompileAllCharStrings()
        if hasattr(self, "ROS"):
            self.skipNames = ["Encoding"]
        if not hasattr(self, "ROS") or not hasattr(self, "CharStrings"):
            # these values have default values, but I only want them to show up
            # in CID fonts.
            self.skipNames = [
                "CIDFontVersion",
                "CIDFontRevision",
                "CIDFontType",
                "CIDCount",
            ]
        BaseDict.toXML(self, xmlWriter)

    def decompileAllCharStrings(self):
        # Make sure that all the Private Dicts have been instantiated.
        for i, charString in enumerate(self.CharStrings.values()):
            try:
                charString.decompile()
            except:
                log.error("Error in charstring %s", i)
                raise

    def recalcFontBBox(self):
        fontBBox = None
        for charString in self.CharStrings.values():
            bounds = charString.calcBounds(self.CharStrings)
            if bounds is not None:
                if fontBBox is not None:
                    fontBBox = unionRect(fontBBox, bounds)
                else:
                    fontBBox = bounds

        if fontBBox is None:
            self.FontBBox = self.defaults["FontBBox"][:]
        else:
            self.FontBBox = list(intRect(fontBBox))


class FontDict(BaseDict):
    #
    # Since fonttools used to pass a lot of fields that are not relevant in the FDArray
    # FontDict, there are 'ttx' files in the wild that contain all these. These got in
    # the ttx files because fonttools writes explicit values for all the TopDict default
    # values. These are not actually illegal in the context of an FDArray FontDict - you
    # can legally, per spec, put any arbitrary key/value pair in a FontDict - but are
    # useless since current major company CFF interpreters ignore anything but the set
    # listed in this file. So, we just silently skip them. An exception is Weight: this
    # is not used by any interpreter, but some foundries have asked that this be
    # supported in FDArray FontDicts just to preserve information about the design when
    # the font is being inspected.
    #
    # On top of that, there are fonts out there that contain such useless FontDict values.
    #
    # By subclassing TopDict, we *allow* all key/values from TopDict, both when reading
    # from binary or when reading from XML, but by overriding `order` with a limited
    # list of names, we ensure that only the useful names ever get exported to XML and
    # ever get compiled into the binary font.
    #
    # We override compilerClass so we can warn about "useless" key/value pairs, either
    # from the original binary font or from TTX input.
    #
    # See:
    # - https://github.com/fonttools/fonttools/issues/740
    # - https://github.com/fonttools/fonttools/issues/601
    # - https://github.com/adobe-type-tools/afdko/issues/137
    #
    defaults = {}
    converters = buildConverters(topDictOperators)
    compilerClass = FontDictCompiler
    orderCFF = ["FontName", "FontMatrix", "Weight", "Private"]
    orderCFF2 = ["Private"]
    decompilerClass = TopDictDecompiler

    def __init__(
        self,
        strings=None,
        file=None,
        offset=None,
        GlobalSubrs=None,
        isCFF2=None,
        vstore=None,
    ):
        super(FontDict, self).__init__(strings, file, offset, isCFF2=isCFF2)
        self.vstore = vstore
        self.setCFF2(isCFF2)

    def setCFF2(self, isCFF2):
        # isCFF2 may be None.
        if isCFF2:
            self.order = self.orderCFF2
            self._isCFF2 = True
        else:
            self.order = self.orderCFF
            self._isCFF2 = False


class PrivateDict(BaseDict):
    defaults = buildDefaults(privateDictOperators)
    converters = buildConverters(privateDictOperators)
    order = buildOrder(privateDictOperators)
    decompilerClass = PrivateDictDecompiler
    compilerClass = PrivateDictCompiler

    def __init__(self, strings=None, file=None, offset=None, isCFF2=None, vstore=None):
        super(PrivateDict, self).__init__(strings, file, offset, isCFF2=isCFF2)
        self.vstore = vstore
        if isCFF2:
            self.defaults = buildDefaults(privateDictOperators2)
            self.order = buildOrder(privateDictOperators2)
            # Provide dummy values. This avoids needing to provide
            # an isCFF2 state in a lot of places.
            self.nominalWidthX = self.defaultWidthX = None
            self._isCFF2 = True
        else:
            self.defaults = buildDefaults(privateDictOperators)
            self.order = buildOrder(privateDictOperators)
            self._isCFF2 = False

    @property
    def in_cff2(self):
        return self._isCFF2

    def getNumRegions(self, vi=None):  # called from misc/psCharStrings.py
        # if getNumRegions is being called, we can assume that VarStore exists.
        if vi is None:
            if hasattr(self, "vsindex"):
                vi = self.vsindex
            else:
                vi = 0
        numRegions = self.vstore.getNumRegions(vi)
        return numRegions


class IndexedStrings(object):
    """SID -> string mapping."""

    def __init__(self, file=None):
        if file is None:
            strings = []
        else:
            strings = [tostr(s, encoding="latin1") for s in Index(file, isCFF2=False)]
        self.strings = strings

    def getCompiler(self):
        return IndexedStringsCompiler(self, None, self, isCFF2=False)

    def __len__(self):
        return len(self.strings)

    def __getitem__(self, SID):
        if SID < cffStandardStringCount:
            return cffStandardStrings[SID]
        else:
            return self.strings[SID - cffStandardStringCount]

    def getSID(self, s):
        if not hasattr(self, "stringMapping"):
            self.buildStringMapping()
        s = tostr(s, encoding="latin1")
        if s in cffStandardStringMapping:
            SID = cffStandardStringMapping[s]
        elif s in self.stringMapping:
            SID = self.stringMapping[s]
        else:
            SID = len(self.strings) + cffStandardStringCount
            self.strings.append(s)
            self.stringMapping[s] = SID
        return SID

    def getStrings(self):
        return self.strings

    def buildStringMapping(self):
        self.stringMapping = {}
        for index in range(len(self.strings)):
            self.stringMapping[self.strings[index]] = index + cffStandardStringCount


# The 391 Standard Strings as used in the CFF format.
# from Adobe Technical None #5176, version 1.0, 18 March 1998

cffStandardStrings = [
    ".notdef",
    "space",
    "exclam",
    "quotedbl",
    "numbersign",
    "dollar",
    "percent",
    "ampersand",
    "quoteright",
    "parenleft",
    "parenright",
    "asterisk",
    "plus",
    "comma",
    "hyphen",
    "period",
    "slash",
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "colon",
    "semicolon",
    "less",
    "equal",
    "greater",
    "question",
    "at",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "bracketleft",
    "backslash",
    "bracketright",
    "asciicircum",
    "underscore",
    "quoteleft",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "braceleft",
    "bar",
    "braceright",
    "asciitilde",
    "exclamdown",
    "cent",
    "sterling",
    "fraction",
    "yen",
    "florin",
    "section",
    "currency",
    "quotesingle",
    "quotedblleft",
    "guillemotleft",
    "guilsinglleft",
    "guilsinglright",
    "fi",
    "fl",
    "endash",
    "dagger",
    "daggerdbl",
    "periodcentered",
    "paragraph",
    "bullet",
    "quotesinglbase",
    "quotedblbase",
    "quotedblright",
    "guillemotright",
    "ellipsis",
    "perthousand",
    "questiondown",
    "grave",
    "acute",
    "circumflex",
    "tilde",
    "macron",
    "breve",
    "dotaccent",
    "dieresis",
    "ring",
    "cedilla",
    "hungarumlaut",
    "ogonek",
    "caron",
    "emdash",
    "AE",
    "ordfeminine",
    "Lslash",
    "Oslash",
    "OE",
    "ordmasculine",
    "ae",
    "dotlessi",
    "lslash",
    "oslash",
    "oe",
    "germandbls",
    "onesuperior",
    "logicalnot",
    "mu",
    "trademark",
    "Eth",
    "onehalf",
    "plusminus",
    "Thorn",
    "onequarter",
    "divide",
    "brokenbar",
    "degree",
    "thorn",
    "threequarters",
    "twosuperior",
    "registered",
    "minus",
    "eth",
    "multiply",
    "threesuperior",
    "copyright",
    "Aacute",
    "Acircumflex",
    "Adieresis",
    "Agrave",
    "Aring",
    "Atilde",
    "Ccedilla",
    "Eacute",
    "Ecircumflex",
    "Edieresis",
    "Egrave",
    "Iacute",
    "Icircumflex",
    "Idieresis",
    "Igrave",
    "Ntilde",
    "Oacute",
    "Ocircumflex",
    "Odieresis",
    "Ograve",
    "Otilde",
    "Scaron",
    "Uacute",
    "Ucircumflex",
    "Udieresis",
    "Ugrave",
    "Yacute",
    "Ydieresis",
    "Zcaron",
    "aacute",
    "acircumflex",
    "adieresis",
    "agrave",
    "aring",
    "atilde",
    "ccedilla",
    "eacute",
    "ecircumflex",
    "edieresis",
    "egrave",
    "iacute",
    "icircumflex",
    "idieresis",
    "igrave",
    "ntilde",
    "oacute",
    "ocircumflex",
    "odieresis",
    "ograve",
    "otilde",
    "scaron",
    "uacute",
    "ucircumflex",
    "udieresis",
    "ugrave",
    "yacute",
    "ydieresis",
    "zcaron",
    "exclamsmall",
    "Hungarumlautsmall",
    "dollaroldstyle",
    "dollarsuperior",
    "ampersandsmall",
    "Acutesmall",
    "parenleftsuperior",
    "parenrightsuperior",
    "twodotenleader",
    "onedotenleader",
    "zerooldstyle",
    "oneoldstyle",
    "twooldstyle",
    "threeoldstyle",
    "fouroldstyle",
    "fiveoldstyle",
    "sixoldstyle",
    "sevenoldstyle",
    "eightoldstyle",
    "nineoldstyle",
    "commasuperior",
    "threequartersemdash",
    "periodsuperior",
    "questionsmall",
    "asuperior",
    "bsuperior",
    "centsuperior",
    "dsuperior",
    "esuperior",
    "isuperior",
    "lsuperior",
    "msuperior",
    "nsuperior",
    "osuperior",
    "rsuperior",
    "ssuperior",
    "tsuperior",
    "ff",
    "ffi",
    "ffl",
    "parenleftinferior",
    "parenrightinferior",
    "Circumflexsmall",
    "hyphensuperior",
    "Gravesmall",
    "Asmall",
    "Bsmall",
    "Csmall",
    "Dsmall",
    "Esmall",
    "Fsmall",
    "Gsmall",
    "Hsmall",
    "Ismall",
    "Jsmall",
    "Ksmall",
    "Lsmall",
    "Msmall",
    "Nsmall",
    "Osmall",
    "Psmall",
    "Qsmall",
    "Rsmall",
    "Ssmall",
    "Tsmall",
    "Usmall",
    "Vsmall",
    "Wsmall",
    "Xsmall",
    "Ysmall",
    "Zsmall",
    "colonmonetary",
    "onefitted",
    "rupiah",
    "Tildesmall",
    "exclamdownsmall",
    "centoldstyle",
    "Lslashsmall",
    "Scaronsmall",
    "Zcaronsmall",
    "Dieresissmall",
    "Brevesmall",
    "Caronsmall",
    "Dotaccentsmall",
    "Macronsmall",
    "figuredash",
    "hypheninferior",
    "Ogoneksmall",
    "Ringsmall",
    "Cedillasmall",
    "questiondownsmall",
    "oneeighth",
    "threeeighths",
    "fiveeighths",
    "seveneighths",
    "onethird",
    "twothirds",
    "zerosuperior",
    "foursuperior",
    "fivesuperior",
    "sixsuperior",
    "sevensuperior",
    "eightsuperior",
    "ninesuperior",
    "zeroinferior",
    "oneinferior",
    "twoinferior",
    "threeinferior",
    "fourinferior",
    "fiveinferior",
    "sixinferior",
    "seveninferior",
    "eightinferior",
    "nineinferior",
    "centinferior",
    "dollarinferior",
    "periodinferior",
    "commainferior",
    "Agravesmall",
    "Aacutesmall",
    "Acircumflexsmall",
    "Atildesmall",
    "Adieresissmall",
    "Aringsmall",
    "AEsmall",
    "Ccedillasmall",
    "Egravesmall",
    "Eacutesmall",
    "Ecircumflexsmall",
    "Edieresissmall",
    "Igravesmall",
    "Iacutesmall",
    "Icircumflexsmall",
    "Idieresissmall",
    "Ethsmall",
    "Ntildesmall",
    "Ogravesmall",
    "Oacutesmall",
    "Ocircumflexsmall",
    "Otildesmall",
    "Odieresissmall",
    "OEsmall",
    "Oslashsmall",
    "Ugravesmall",
    "Uacutesmall",
    "Ucircumflexsmall",
    "Udieresissmall",
    "Yacutesmall",
    "Thornsmall",
    "Ydieresissmall",
    "001.000",
    "001.001",
    "001.002",
    "001.003",
    "Black",
    "Bold",
    "Book",
    "Light",
    "Medium",
    "Regular",
    "Roman",
    "Semibold",
]

cffStandardStringCount = 391
assert len(cffStandardStrings) == cffStandardStringCount
# build reverse mapping
cffStandardStringMapping = {}
for _i in range(cffStandardStringCount):
    cffStandardStringMapping[cffStandardStrings[_i]] = _i

cffISOAdobeStrings = [
    ".notdef",
    "space",
    "exclam",
    "quotedbl",
    "numbersign",
    "dollar",
    "percent",
    "ampersand",
    "quoteright",
    "parenleft",
    "parenright",
    "asterisk",
    "plus",
    "comma",
    "hyphen",
    "period",
    "slash",
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "colon",
    "semicolon",
    "less",
    "equal",
    "greater",
    "question",
    "at",
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "bracketleft",
    "backslash",
    "bracketright",
    "asciicircum",
    "underscore",
    "quoteleft",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "braceleft",
    "bar",
    "braceright",
    "asciitilde",
    "exclamdown",
    "cent",
    "sterling",
    "fraction",
    "yen",
    "florin",
    "section",
    "currency",
    "quotesingle",
    "quotedblleft",
    "guillemotleft",
    "guilsinglleft",
    "guilsinglright",
    "fi",
    "fl",
    "endash",
    "dagger",
    "daggerdbl",
    "periodcentered",
    "paragraph",
    "bullet",
    "quotesinglbase",
    "quotedblbase",
    "quotedblright",
    "guillemotright",
    "ellipsis",
    "perthousand",
    "questiondown",
    "grave",
    "acute",
    "circumflex",
    "tilde",
    "macron",
    "breve",
    "dotaccent",
    "dieresis",
    "ring",
    "cedilla",
    "hungarumlaut",
    "ogonek",
    "caron",
    "emdash",
    "AE",
    "ordfeminine",
    "Lslash",
    "Oslash",
    "OE",
    "ordmasculine",
    "ae",
    "dotlessi",
    "lslash",
    "oslash",
    "oe",
    "germandbls",
    "onesuperior",
    "logicalnot",
    "mu",
    "trademark",
    "Eth",
    "onehalf",
    "plusminus",
    "Thorn",
    "onequarter",
    "divide",
    "brokenbar",
    "degree",
    "thorn",
    "threequarters",
    "twosuperior",
    "registered",
    "minus",
    "eth",
    "multiply",
    "threesuperior",
    "copyright",
    "Aacute",
    "Acircumflex",
    "Adieresis",
    "Agrave",
    "Aring",
    "Atilde",
    "Ccedilla",
    "Eacute",
    "Ecircumflex",
    "Edieresis",
    "Egrave",
    "Iacute",
    "Icircumflex",
    "Idieresis",
    "Igrave",
    "Ntilde",
    "Oacute",
    "Ocircumflex",
    "Odieresis",
    "Ograve",
    "Otilde",
    "Scaron",
    "Uacute",
    "Ucircumflex",
    "Udieresis",
    "Ugrave",
    "Yacute",
    "Ydieresis",
    "Zcaron",
    "aacute",
    "acircumflex",
    "adieresis",
    "agrave",
    "aring",
    "atilde",
    "ccedilla",
    "eacute",
    "ecircumflex",
    "edieresis",
    "egrave",
    "iacute",
    "icircumflex",
    "idieresis",
    "igrave",
    "ntilde",
    "oacute",
    "ocircumflex",
    "odieresis",
    "ograve",
    "otilde",
    "scaron",
    "uacute",
    "ucircumflex",
    "udieresis",
    "ugrave",
    "yacute",
    "ydieresis",
    "zcaron",
]

cffISOAdobeStringCount = 229
assert len(cffISOAdobeStrings) == cffISOAdobeStringCount

cffIExpertStrings = [
    ".notdef",
    "space",
    "exclamsmall",
    "Hungarumlautsmall",
    "dollaroldstyle",
    "dollarsuperior",
    "ampersandsmall",
    "Acutesmall",
    "parenleftsuperior",
    "parenrightsuperior",
    "twodotenleader",
    "onedotenleader",
    "comma",
    "hyphen",
    "period",
    "fraction",
    "zerooldstyle",
    "oneoldstyle",
    "twooldstyle",
    "threeoldstyle",
    "fouroldstyle",
    "fiveoldstyle",
    "sixoldstyle",
    "sevenoldstyle",
    "eightoldstyle",
    "nineoldstyle",
    "colon",
    "semicolon",
    "commasuperior",
    "threequartersemdash",
    "periodsuperior",
    "questionsmall",
    "asuperior",
    "bsuperior",
    "centsuperior",
    "dsuperior",
    "esuperior",
    "isuperior",
    "lsuperior",
    "msuperior",
    "nsuperior",
    "osuperior",
    "rsuperior",
    "ssuperior",
    "tsuperior",
    "ff",
    "fi",
    "fl",
    "ffi",
    "ffl",
    "parenleftinferior",
    "parenrightinferior",
    "Circumflexsmall",
    "hyphensuperior",
    "Gravesmall",
    "Asmall",
    "Bsmall",
    "Csmall",
    "Dsmall",
    "Esmall",
    "Fsmall",
    "Gsmall",
    "Hsmall",
    "Ismall",
    "Jsmall",
    "Ksmall",
    "Lsmall",
    "Msmall",
    "Nsmall",
    "Osmall",
    "Psmall",
    "Qsmall",
    "Rsmall",
    "Ssmall",
    "Tsmall",
    "Usmall",
    "Vsmall",
    "Wsmall",
    "Xsmall",
    "Ysmall",
    "Zsmall",
    "colonmonetary",
    "onefitted",
    "rupiah",
    "Tildesmall",
    "exclamdownsmall",
    "centoldstyle",
    "Lslashsmall",
    "Scaronsmall",
    "Zcaronsmall",
    "Dieresissmall",
    "Brevesmall",
    "Caronsmall",
    "Dotaccentsmall",
    "Macronsmall",
    "figuredash",
    "hypheninferior",
    "Ogoneksmall",
    "Ringsmall",
    "Cedillasmall",
    "onequarter",
    "onehalf",
    "threequarters",
    "questiondownsmall",
    "oneeighth",
    "threeeighths",
    "fiveeighths",
    "seveneighths",
    "onethird",
    "twothirds",
    "zerosuperior",
    "onesuperior",
    "twosuperior",
    "threesuperior",
    "foursuperior",
    "fivesuperior",
    "sixsuperior",
    "sevensuperior",
    "eightsuperior",
    "ninesuperior",
    "zeroinferior",
    "oneinferior",
    "twoinferior",
    "threeinferior",
    "fourinferior",
    "fiveinferior",
    "sixinferior",
    "seveninferior",
    "eightinferior",
    "nineinferior",
    "centinferior",
    "dollarinferior",
    "periodinferior",
    "commainferior",
    "Agravesmall",
    "Aacutesmall",
    "Acircumflexsmall",
    "Atildesmall",
    "Adieresissmall",
    "Aringsmall",
    "AEsmall",
    "Ccedillasmall",
    "Egravesmall",
    "Eacutesmall",
    "Ecircumflexsmall",
    "Edieresissmall",
    "Igravesmall",
    "Iacutesmall",
    "Icircumflexsmall",
    "Idieresissmall",
    "Ethsmall",
    "Ntildesmall",
    "Ogravesmall",
    "Oacutesmall",
    "Ocircumflexsmall",
    "Otildesmall",
    "Odieresissmall",
    "OEsmall",
    "Oslashsmall",
    "Ugravesmall",
    "Uacutesmall",
    "Ucircumflexsmall",
    "Udieresissmall",
    "Yacutesmall",
    "Thornsmall",
    "Ydieresissmall",
]

cffExpertStringCount = 166
assert len(cffIExpertStrings) == cffExpertStringCount

cffExpertSubsetStrings = [
    ".notdef",
    "space",
    "dollaroldstyle",
    "dollarsuperior",
    "parenleftsuperior",
    "parenrightsuperior",
    "twodotenleader",
    "onedotenleader",
    "comma",
    "hyphen",
    "period",
    "fraction",
    "zerooldstyle",
    "oneoldstyle",
    "twooldstyle",
    "threeoldstyle",
    "fouroldstyle",
    "fiveoldstyle",
    "sixoldstyle",
    "sevenoldstyle",
    "eightoldstyle",
    "nineoldstyle",
    "colon",
    "semicolon",
    "commasuperior",
    "threequartersemdash",
    "periodsuperior",
    "asuperior",
    "bsuperior",
    "centsuperior",
    "dsuperior",
    "esuperior",
    "isuperior",
    "lsuperior",
    "msuperior",
    "nsuperior",
    "osuperior",
    "rsuperior",
    "ssuperior",
    "tsuperior",
    "ff",
    "fi",
    "fl",
    "ffi",
    "ffl",
    "parenleftinferior",
    "parenrightinferior",
    "hyphensuperior",
    "colonmonetary",
    "onefitted",
    "rupiah",
    "centoldstyle",
    "figuredash",
    "hypheninferior",
    "onequarter",
    "onehalf",
    "threequarters",
    "oneeighth",
    "threeeighths",
    "fiveeighths",
    "seveneighths",
    "onethird",
    "twothirds",
    "zerosuperior",
    "onesuperior",
    "twosuperior",
    "threesuperior",
    "foursuperior",
    "fivesuperior",
    "sixsuperior",
    "sevensuperior",
    "eightsuperior",
    "ninesuperior",
    "zeroinferior",
    "oneinferior",
    "twoinferior",
    "threeinferior",
    "fourinferior",
    "fiveinferior",
    "sixinferior",
    "seveninferior",
    "eightinferior",
    "nineinferior",
    "centinferior",
    "dollarinferior",
    "periodinferior",
    "commainferior",
]

cffExpertSubsetStringCount = 87
assert len(cffExpertSubsetStrings) == cffExpertSubsetStringCount