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
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
// Copyright Mozilla Foundation. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![cfg_attr(
    feature = "cargo-clippy",
    allow(doc_markdown, inline_always, new_ret_no_self)
)]

//! encoding_rs is a Gecko-oriented Free Software / Open Source implementation
//! of the [Encoding Standard](https://encoding.spec.whatwg.org/) in Rust.
//! Gecko-oriented means that converting to and from UTF-16 is supported in
//! addition to converting to and from UTF-8, that the performance and
//! streamability goals are browser-oriented, and that FFI-friendliness is a
//! goal.
//!
//! Additionally, the `mem` module provides functions that are useful for
//! applications that need to be able to deal with legacy in-memory
//! representations of Unicode.
//!
//! For expectation setting, please be sure to read the sections
//! [_UTF-16LE, UTF-16BE and Unicode Encoding Schemes_](#utf-16le-utf-16be-and-unicode-encoding-schemes),
//! [_ISO-8859-1_](#iso-8859-1) and [_Web / Browser Focus_](#web--browser-focus) below.
//!
//! There is a [long-form write-up](https://hsivonen.fi/encoding_rs/) about the
//! design and internals of the crate.
//!
//! # Availability
//!
//! The code is available under the
//! [Apache license, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
//! or the [MIT license](https://opensource.org/licenses/MIT), at your option.
//! See the
//! [`COPYRIGHT`](https://github.com/hsivonen/encoding_rs/blob/master/COPYRIGHT)
//! file for details.
//! The [repository is on GitHub](https://github.com/hsivonen/encoding_rs). The
//! [crate is available on crates.io](https://crates.io/crates/encoding_rs).
//!
//! # Integration with `std::io`
//!
//! This crate doesn't implement traits from `std::io`. However, for the case of
//! wrapping a `std::io::Read` in a decoder that implements `std::io::Read` and
//! presents the data from the wrapped `std::io::Read` as UTF-8 is addressed by
//! the [`encoding_rs_io`](https://docs.rs/encoding_rs_io/) crate.
//!
//! # Examples
//!
//! Example programs:
//!
//! * [Rust](https://github.com/hsivonen/recode_rs)
//! * [C](https://github.com/hsivonen/recode_c)
//! * [C++](https://github.com/hsivonen/recode_cpp)
//!
//! Decode using the non-streaming API:
//!
//! ```
//! use encoding_rs::*;
//!
//! let expectation = "\u{30CF}\u{30ED}\u{30FC}\u{30FB}\u{30EF}\u{30FC}\u{30EB}\u{30C9}";
//! let bytes = b"\x83n\x83\x8D\x81[\x81E\x83\x8F\x81[\x83\x8B\x83h";
//!
//! let (cow, encoding_used, had_errors) = SHIFT_JIS.decode(bytes);
//! assert_eq!(&cow[..], expectation);
//! assert_eq!(encoding_used, SHIFT_JIS);
//! assert!(!had_errors);
//! ```
//!
//! Decode using the streaming API with minimal `unsafe`:
//!
//! ```
//! use encoding_rs::*;
//!
//! let expectation = "\u{30CF}\u{30ED}\u{30FC}\u{30FB}\u{30EF}\u{30FC}\u{30EB}\u{30C9}";
//!
//! // Use an array of byte slices to demonstrate content arriving piece by
//! // piece from the network.
//! let bytes: [&'static [u8]; 4] = [b"\x83",
//!                                  b"n\x83\x8D\x81",
//!                                  b"[\x81E\x83\x8F\x81[\x83",
//!                                  b"\x8B\x83h"];
//!
//! // Very short output buffer to demonstrate the output buffer getting full.
//! // Normally, you'd use something like `[0u8; 2048]`.
//! let mut buffer_bytes = [0u8; 8];
//! let mut buffer: &mut str = std::str::from_utf8_mut(&mut buffer_bytes[..]).unwrap();
//!
//! // How many bytes in the buffer currently hold significant data.
//! let mut bytes_in_buffer = 0usize;
//!
//! // Collect the output to a string for demonstration purposes.
//! let mut output = String::new();
//!
//! // The `Decoder`
//! let mut decoder = SHIFT_JIS.new_decoder();
//!
//! // Track whether we see errors.
//! let mut total_had_errors = false;
//!
//! // Decode using a fixed-size intermediate buffer (for demonstrating the
//! // use of a fixed-size buffer; normally when the output of an incremental
//! // decode goes to a `String` one would use `Decoder.decode_to_string()` to
//! // avoid the intermediate buffer).
//! for input in &bytes[..] {
//!     // The number of bytes already read from current `input` in total.
//!     let mut total_read_from_current_input = 0usize;
//!
//!     loop {
//!         let (result, read, written, had_errors) =
//!             decoder.decode_to_str(&input[total_read_from_current_input..],
//!                                   &mut buffer[bytes_in_buffer..],
//!                                   false);
//!         total_read_from_current_input += read;
//!         bytes_in_buffer += written;
//!         total_had_errors |= had_errors;
//!         match result {
//!             CoderResult::InputEmpty => {
//!                 // We have consumed the current input buffer. Break out of
//!                 // the inner loop to get the next input buffer from the
//!                 // outer loop.
//!                 break;
//!             },
//!             CoderResult::OutputFull => {
//!                 // Write the current buffer out and consider the buffer
//!                 // empty.
//!                 output.push_str(&buffer[..bytes_in_buffer]);
//!                 bytes_in_buffer = 0usize;
//!                 continue;
//!             }
//!         }
//!     }
//! }
//!
//! // Process EOF
//! loop {
//!     let (result, _, written, had_errors) =
//!         decoder.decode_to_str(b"",
//!                               &mut buffer[bytes_in_buffer..],
//!                               true);
//!     bytes_in_buffer += written;
//!     total_had_errors |= had_errors;
//!     // Write the current buffer out and consider the buffer empty.
//!     // Need to do this here for both `match` arms, because we exit the
//!     // loop on `CoderResult::InputEmpty`.
//!     output.push_str(&buffer[..bytes_in_buffer]);
//!     bytes_in_buffer = 0usize;
//!     match result {
//!         CoderResult::InputEmpty => {
//!             // Done!
//!             break;
//!         },
//!         CoderResult::OutputFull => {
//!             continue;
//!         }
//!     }
//! }
//!
//! assert_eq!(&output[..], expectation);
//! assert!(!total_had_errors);
//! ```
//!
//! ## UTF-16LE, UTF-16BE and Unicode Encoding Schemes
//!
//! The Encoding Standard doesn't specify encoders for UTF-16LE and UTF-16BE,
//! __so this crate does not provide encoders for those encodings__!
//! Along with the replacement encoding, their _output encoding_ is UTF-8,
//! so you get an UTF-8 encoder if you request an encoder for them.
//!
//! Additionally, the Encoding Standard factors BOM handling into wrapper
//! algorithms so that BOM handling isn't part of the definition of the
//! encodings themselves. The Unicode _encoding schemes_ in the Unicode
//! Standard define BOM handling or lack thereof as part of the encoding
//! scheme.
//!
//! When used with the `_without_bom_handling` entry points, the UTF-16LE
//! and UTF-16BE _encodings_ match the same-named _encoding schemes_ from
//! the Unicode Standard.
//!
//! When used with the `_with_bom_removal` entry points, the UTF-8
//! _encoding_ matches the UTF-8 _encoding scheme_ from the Unicode
//! Standard.
//!
//! This crate does not provide a mode that matches the UTF-16 _encoding
//! scheme_ from the Unicode Stardard. The UTF-16BE encoding used with
//! the entry points without `_bom_` qualifiers is the closest match,
//! but in that case, the UTF-8 BOM triggers UTF-8 decoding, which is
//! not part of the behavior of the UTF-16 _encoding scheme_ per the
//! Unicode Standard.
//!
//! The UTF-32 family of Unicode encoding schemes is not supported
//! by this crate. The Encoding Standard doesn't define any UTF-32
//! family encodings, since they aren't necessary for consuming Web
//! content.
//!
//! ## ISO-8859-1
//!
//! ISO-8859-1 does not exist as a distinct encoding from windows-1252 in
//! the Encoding Standard. Therefore, an encoding that maps the unsigned
//! byte value to the same Unicode scalar value is not available via
//! `Encoding` in this crate.
//!
//! However, the functions whose name starts with `convert` and contains
//! `latin1` in the `mem` module support such conversions, which are known as
//! [_isomorphic decode_](https://infra.spec.whatwg.org/#isomorphic-decode)
//! and [_isomorphic encode_](https://infra.spec.whatwg.org/#isomorphic-encode)
//! in the [Infra Standard](https://infra.spec.whatwg.org/).
//!
//! ## Web / Browser Focus
//!
//! Both in terms of scope and performance, the focus is on the Web. For scope,
//! this means that encoding_rs implements the Encoding Standard fully and
//! doesn't implement encodings that are not specified in the Encoding
//! Standard. For performance, this means that decoding performance is
//! important as well as performance for encoding into UTF-8 or encoding the
//! Basic Latin range (ASCII) into legacy encodings. Non-Basic Latin needs to
//! be encoded into legacy encodings in only two places in the Web platform: in
//! the query part of URLs, in which case it's a matter of relatively rare
//! error handling, and in form submission, in which case the user action and
//! networking tend to hide the performance of the encoder.
//!
//! Deemphasizing performance of encoding non-Basic Latin text into legacy
//! encodings enables smaller code size thanks to the encoder side using the
//! decode-optimized data tables without having encode-optimized data tables at
//! all. Even in decoders, smaller lookup table size is preferred over avoiding
//! multiplication operations.
//!
//! Additionally, performance is a non-goal for the ASCII-incompatible
//! ISO-2022-JP encoding, which are rarely used on the Web. Instead of
//! performance, the decoder for ISO-2022-JP optimizes for ease/clarity
//! of implementation.
//!
//! Despite the browser focus, the hope is that non-browser applications
//! that wish to consume Web content or submit Web forms in a Web-compatible
//! way will find encoding_rs useful. While encoding_rs does not try to match
//! Windows behavior, many of the encodings are close enough to legacy
//! encodings implemented by Windows that applications that need to consume
//! data in legacy Windows encodins may find encoding_rs useful. The
//! [codepage](https://crates.io/crates/codepage) crate maps from Windows
//! code page identifiers onto encoding_rs `Encoding`s and vice versa.
//!
//! For decoding email, UTF-7 support is needed (unfortunately) in additition
//! to the encodings defined in the Encoding Standard. The
//! [charset](https://crates.io/crates/charset) wraps encoding_rs and adds
//! UTF-7 decoding for email purposes.
//!
//! # Preparing Text for the Encoders
//!
//! Normalizing text into Unicode Normalization Form C prior to encoding text
//! into a legacy encoding minimizes unmappable characters. Text can be
//! normalized to Unicode Normalization Form C using the
//! [`unic-normal`](https://crates.io/crates/unic-normal) crate.
//!
//! The exception is windows-1258, which after normalizing to Unicode
//! Normalization Form C requires tone marks to be decomposed in order to
//! minimize unmappable characters. Vietnamese tone marks can be decomposed
//! using the [`detone`](https://crates.io/crates/detone) crate.
//!
//! # Streaming & Non-Streaming; Rust & C/C++
//!
//! The API in Rust has two modes of operation: streaming and non-streaming.
//! The streaming API is the foundation of the implementation and should be
//! used when processing data that arrives piecemeal from an i/o stream. The
//! streaming API has an FFI wrapper (as a [separate crate][1]) that exposes it
//! to C callers. The non-streaming part of the API is for Rust callers only and
//! is smart about borrowing instead of copying when possible. When
//! streamability is not needed, the non-streaming API should be preferrer in
//! order to avoid copying data when a borrow suffices.
//!
//! There is no analogous C API exposed via FFI, mainly because C doesn't have
//! standard types for growable byte buffers and Unicode strings that know
//! their length.
//!
//! The C API (header file generated at `target/include/encoding_rs.h` when
//! building encoding_rs) can, in turn, be wrapped for use from C++. Such a
//! C++ wrapper can re-create the non-streaming API in C++ for C++ callers.
//! The C binding comes with a [C++14 wrapper][2] that uses standard library +
//! [GSL][3] types and that recreates the non-streaming API in C++ on top of
//! the streaming API. A C++ wrapper with XPCOM/MFBT types is being developed
//! as part of Mozilla [bug 1261841][4].
//!
//! The `Encoding` type is common to both the streaming and non-streaming
//! modes. In the streaming mode, decoding operations are performed with a
//! `Decoder` and encoding operations with an `Encoder` object obtained via
//! `Encoding`. In the non-streaming mode, decoding and encoding operations are
//! performed using methods on `Encoding` objects themselves, so the `Decoder`
//! and `Encoder` objects are not used at all.
//!
//! [1]: https://github.com/hsivonen/encoding_c
//! [2]: https://github.com/hsivonen/encoding_c/blob/master/include/encoding_rs_cpp.h
//! [3]: https://github.com/Microsoft/GSL/
//! [4]: https://bugzilla.mozilla.org/show_bug.cgi?id=encoding_rs
//!
//! # Memory management
//!
//! The non-streaming mode never performs heap allocations (even the methods
//! that write into a `Vec<u8>` or a `String` by taking them as arguments do
//! not reallocate the backing buffer of the `Vec<u8>` or the `String`). That
//! is, the non-streaming mode uses caller-allocated buffers exclusively.
//!
//! The methods of the streaming mode that return a `Vec<u8>` or a `String`
//! perform heap allocations but only to allocate the backing buffer of the
//! `Vec<u8>` or the `String`.
//!
//! `Encoding` is always statically allocated. `Decoder` and `Encoder` need no
//! `Drop` cleanup.
//!
//! # Buffer reading and writing behavior
//!
//! Based on experience gained with the `java.nio.charset` encoding converter
//! API and with the Gecko uconv encoding converter API, the buffer reading
//! and writing behaviors of encoding_rs are asymmetric: input buffers are
//! fully drained but output buffers are not always fully filled.
//!
//! When reading from an input buffer, encoding_rs always consumes all input
//! up to the next error or to the end of the buffer. In particular, when
//! decoding, even if the input buffer ends in the middle of a byte sequence
//! for a character, the decoder consumes all input. This has the benefit that
//! the caller of the API can always fill the next buffer from the start from
//! whatever source the bytes come from and never has to first copy the last
//! bytes of the previous buffer to the start of the next buffer. However, when
//! encoding, the UTF-8 input buffers have to end at a character boundary, which
//! is a requirement for the Rust `str` type anyway, and UTF-16 input buffer
//! boundaries falling in the middle of a surrogate pair result in both
//! suggorates being treated individually as unpaired surrogates.
//!
//! Additionally, decoders guarantee that they can be fed even one byte at a
//! time and encoders guarantee that they can be fed even one code point at a
//! time. This has the benefit of not placing restrictions on the size of
//! chunks the content arrives e.g. from network.
//!
//! When writing into an output buffer, encoding_rs makes sure that the code
//! unit sequence for a character is never split across output buffer
//! boundaries. This may result in wasted space at the end of an output buffer,
//! but the advantages are that the output side of both decoders and encoders
//! is greatly simplified compared to designs that attempt to fill output
//! buffers exactly even when that entails splitting a code unit sequence and
//! when encoding_rs methods return to the caller, the output produces thus
//! far is always valid taken as whole. (In the case of encoding to ISO-2022-JP,
//! the output needs to be considered as a whole, because the latest output
//! buffer taken alone might not be valid taken alone if the transition away
//! from the ASCII state occurred in an earlier output buffer. However, since
//! the ISO-2022-JP decoder doesn't treat streams that don't end in the ASCII
//! state as being in error despite the encoder generating a transition to the
//! ASCII state at the end, the claim about the partial output taken as a whole
//! being valid is true even for ISO-2022-JP.)
//!
//! # Error Reporting
//!
//! Based on experience gained with the `java.nio.charset` encoding converter
//! API and with the Gecko uconv encoding converter API, the error reporting
//! behaviors of encoding_rs are asymmetric: decoder errors include offsets
//! that leave it up to the caller to extract the erroneous bytes from the
//! input stream if the caller wishes to do so but encoder errors provide the
//! code point associated with the error without requiring the caller to
//! extract it from the input on its own.
//!
//! On the encoder side, an error is always triggered by the most recently
//! pushed Unicode scalar, which makes it simple to pass the `char` to the
//! caller. Also, it's very typical for the caller to wish to do something with
//! this data: generate a numeric escape for the character. Additionally, the
//! ISO-2022-JP encoder reports U+FFFD instead of the actual input character in
//! certain cases, so requiring the caller to extract the character from the
//! input buffer would require the caller to handle ISO-2022-JP details.
//! Furthermore, requiring the caller to extract the character from the input
//! buffer would require the caller to implement UTF-8 or UTF-16 math, which is
//! the job of an encoding conversion library.
//!
//! On the decoder side, errors are triggered in more complex ways. For
//! example, when decoding the sequence ESC, '$', _buffer boundary_, 'A' as
//! ISO-2022-JP, the ESC byte is in error, but this is discovered only after
//! the buffer boundary when processing 'A'. Thus, the bytes in error might not
//! be the ones most recently pushed to the decoder and the error might not even
//! be in the current buffer.
//!
//! Some encoding conversion APIs address the problem by not acknowledging
//! trailing bytes of an input buffer as consumed if it's still possible for
//! future bytes to cause the trailing bytes to be in error. This way, error
//! reporting can always refer to the most recently pushed buffer. This has the
//! problem that the caller of the API has to copy the unconsumed trailing
//! bytes to the start of the next buffer before being able to fill the rest
//! of the next buffer. This is annoying, error-prone and inefficient.
//!
//! A possible solution would be making the decoder remember recently consumed
//! bytes in order to be able to include a copy of the erroneous bytes when
//! reporting an error. This has two problem: First, callers a rarely
//! interested in the erroneous bytes, so attempts to identify them are most
//! often just overhead anyway. Second, the rare applications that are
//! interested typically care about the location of the error in the input
//! stream.
//!
//! To keep the API convenient for common uses and the overhead low while making
//! it possible to develop applications, such as HTML validators, that care
//! about which bytes were in error, encoding_rs reports the length of the
//! erroneous sequence and the number of bytes consumed after the erroneous
//! sequence. As long as the caller doesn't discard the 6 most recent bytes,
//! this makes it possible for callers that care about the erroneous bytes to
//! locate them.
//!
//! # No Convenience API for Custom Replacements
//!
//! The Web Platform and, therefore, the Encoding Standard supports only one
//! error recovery mode for decoders and only one error recovery mode for
//! encoders. The supported error recovery mode for decoders is emitting the
//! REPLACEMENT CHARACTER on error. The supported error recovery mode for
//! encoders is emitting an HTML decimal numeric character reference for
//! unmappable characters.
//!
//! Since encoding_rs is Web-focused, these are the only error recovery modes
//! for which convenient support is provided. Moreover, on the decoder side,
//! there aren't really good alternatives for emitting the REPLACEMENT CHARACTER
//! on error (other than treating errors as fatal). In particular, simply
//! ignoring errors is a
//! [security problem](http://www.unicode.org/reports/tr36/#Substituting_for_Ill_Formed_Subsequences),
//! so it would be a bad idea for encoding_rs to provide a mode that encouraged
//! callers to ignore errors.
//!
//! On the encoder side, there are plausible alternatives for HTML decimal
//! numeric character references. For example, when outputting CSS, CSS-style
//! escapes would seem to make sense. However, instead of facilitating the
//! output of CSS, JS, etc. in non-UTF-8 encodings, encoding_rs takes the design
//! position that you shouldn't generate output in encodings other than UTF-8,
//! except where backward compatibility with interacting with the legacy Web
//! requires it. The legacy Web requires it only when parsing the query strings
//! of URLs and when submitting forms, and those two both use HTML decimal
//! numeric character references.
//!
//! While encoding_rs doesn't make encoder replacements other than HTML decimal
//! numeric character references easy, it does make them _possible_.
//! `encode_from_utf8()`, which emits HTML decimal numeric character references
//! for unmappable characters, is implemented on top of
//! `encode_from_utf8_without_replacement()`. Applications that really, really
//! want other replacement schemes for unmappable characters can likewise
//! implement them on top of `encode_from_utf8_without_replacement()`.
//!
//! # No Extensibility by Design
//!
//! The set of encodings supported by encoding_rs is not extensible by design.
//! That is, `Encoding`, `Decoder` and `Encoder` are intentionally `struct`s
//! rather than `trait`s. encoding_rs takes the design position that all future
//! text interchange should be done using UTF-8, which can represent all of
//! Unicode. (It is, in fact, the only encoding supported by the Encoding
//! Standard and encoding_rs that can represent all of Unicode and that has
//! encoder support. UTF-16LE and UTF-16BE don't have encoder support, and
//! gb18030 cannot encode U+E5E5.) The other encodings are supported merely for
//! legacy compatibility and not due to non-UTF-8 encodings having benefits
//! other than being able to consume legacy content.
//!
//! Considering that UTF-8 can represent all of Unicode and is already supported
//! by all Web browsers, introducing a new encoding wouldn't add to the
//! expressiveness but would add to compatibility problems. In that sense,
//! adding new encodings to the Web Platform doesn't make sense, and, in fact,
//! post-UTF-8 attempts at encodings, such as BOCU-1, have been rejected from
//! the Web Platform. On the other hand, the set of legacy encodings that must
//! be supported for a Web browser to be able to be successful is not going to
//! expand. Empirically, the set of encodings specified in the Encoding Standard
//! is already sufficient and the set of legacy encodings won't grow
//! retroactively.
//!
//! Since extensibility doesn't make sense considering the Web focus of
//! encoding_rs and adding encodings to Web clients would be actively harmful,
//! it makes sense to make the set of encodings that encoding_rs supports
//! non-extensible and to take the (admittedly small) benefits arising from
//! that, such as the size of `Decoder` and `Encoder` objects being known ahead
//!  of time, which enables stack allocation thereof.
//!
//! This does have downsides for applications that might want to put encoding_rs
//! to non-Web uses if those non-Web uses involve legacy encodings that aren't
//! needed for Web uses. The needs of such applications should not complicate
//! encoding_rs itself, though. It is up to those applications to provide a
//! framework that delegates the operations with encodings that encoding_rs
//! supports to encoding_rs and operations with other encodings to something
//! else (as opposed to encoding_rs itself providing an extensibility
//! framework).
//!
//! # Panics
//!
//! Methods in encoding_rs can panic if the API is used against the requirements
//! stated in the documentation, if a state that's supposed to be impossible
//! is reached due to an internal bug or on integer overflow. When used
//! according to documentation with buffer sizes that stay below integer
//! overflow, in the absence of internal bugs, encoding_rs does not panic.
//!
//! Panics arising from API misuse aren't documented beyond this on individual
//! methods.
//!
//! # At-Risk Parts of the API
//!
//! The foreseeable source of partially backward-incompatible API change is the
//! way the instances of `Encoding` are made available.
//!
//! If Rust changes to allow the entries of `[&'static Encoding; N]` to be
//! initialized with `static`s of type `&'static Encoding`, the non-reference
//! `FOO_INIT` public `Encoding` instances will be removed from the public API.
//!
//! If Rust changes to make the referent of `pub const FOO: &'static Encoding`
//! unique when the constant is used in different crates, the reference-typed
//! `static`s for the encoding instances will be changed from `static` to
//! `const` and the non-reference-typed `_INIT` instances will be removed.
//!
//! # Mapping Spec Concepts onto the API
//!
//! <table>
//! <thead>
//! <tr><th>Spec Concept</th><th>Streaming</th><th>Non-Streaming</th></tr>
//! </thead>
//! <tbody>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#encoding">encoding</a></td><td><code>&amp;'static Encoding</code></td><td><code>&amp;'static Encoding</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#utf-8">UTF-8 encoding</a></td><td><code>UTF_8</code></td><td><code>UTF_8</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#concept-encoding-get">get an encoding</a></td><td><code>Encoding::for_label(<var>label</var>)</code></td><td><code>Encoding::for_label(<var>label</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#name">name</a></td><td><code><var>encoding</var>.name()</code></td><td><code><var>encoding</var>.name()</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#get-an-output-encoding">get an output encoding</a></td><td><code><var>encoding</var>.output_encoding()</code></td><td><code><var>encoding</var>.output_encoding()</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#decode">decode</a></td><td><code>let d = <var>encoding</var>.new_decoder();<br>let res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, false);<br>// &hellip;</br>let last_res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, true);</code></td><td><code><var>encoding</var>.decode(<var>src</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#utf-8-decode">UTF-8 decode</a></td><td><code>let d = UTF_8.new_decoder_with_bom_removal();<br>let res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, false);<br>// &hellip;</br>let last_res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, true);</code></td><td><code>UTF_8.decode_with_bom_removal(<var>src</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#utf-8-decode-without-bom">UTF-8 decode without BOM</a></td><td><code>let d = UTF_8.new_decoder_without_bom_handling();<br>let res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, false);<br>// &hellip;</br>let last_res = d.decode_to_<var>*</var>(<var>src</var>, <var>dst</var>, true);</code></td><td><code>UTF_8.decode_without_bom_handling(<var>src</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#utf-8-decode-without-bom-or-fail">UTF-8 decode without BOM or fail</a></td><td><code>let d = UTF_8.new_decoder_without_bom_handling();<br>let res = d.decode_to_<var>*</var>_without_replacement(<var>src</var>, <var>dst</var>, false);<br>// &hellip; (fail if malformed)</br>let last_res = d.decode_to_<var>*</var>_without_replacement(<var>src</var>, <var>dst</var>, true);<br>// (fail if malformed)</code></td><td><code>UTF_8.decode_without_bom_handling_and_without_replacement(<var>src</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#encode">encode</a></td><td><code>let e = <var>encoding</var>.new_encoder();<br>let res = e.encode_to_<var>*</var>(<var>src</var>, <var>dst</var>, false);<br>// &hellip;</br>let last_res = e.encode_to_<var>*</var>(<var>src</var>, <var>dst</var>, true);</code></td><td><code><var>encoding</var>.encode(<var>src</var>)</code></td></tr>
//! <tr><td><a href="https://encoding.spec.whatwg.org/#utf-8-encode">UTF-8 encode</a></td><td>Use the UTF-8 nature of Rust strings directly:<br><code><var>write</var>(<var>src</var>.as_bytes());<br>// refill src<br><var>write</var>(<var>src</var>.as_bytes());<br>// refill src<br><var>write</var>(<var>src</var>.as_bytes());<br>// &hellip;</code></td><td>Use the UTF-8 nature of Rust strings directly:<br><code><var>src</var>.as_bytes()</code></td></tr>
//! </tbody>
//! </table>
//!
//! # Compatibility with the rust-encoding API
//!
//! The crate
//! [encoding_rs_compat](https://github.com/hsivonen/encoding_rs_compat/)
//! is a drop-in replacement for rust-encoding 0.2.32 that implements (most of)
//! the API of rust-encoding 0.2.32 on top of encoding_rs.
//!
//! # Mapping rust-encoding concepts to encoding_rs concepts
//!
//! The following table provides a mapping from rust-encoding constructs to
//! encoding_rs ones.
//!
//! <table>
//! <thead>
//! <tr><th>rust-encoding</th><th>encoding_rs</th></tr>
//! </thead>
//! <tbody>
//! <tr><td><code>encoding::EncodingRef</code></td><td><code>&amp;'static encoding_rs::Encoding</code></td></tr>
//! <tr><td><code>encoding::all::<var>WINDOWS_31J</var></code> (not based on the WHATWG name for some encodings)</td><td><code>encoding_rs::<var>SHIFT_JIS</var></code> (always the WHATWG name uppercased and hyphens replaced with underscores)</td></tr>
//! <tr><td><code>encoding::all::ERROR</code></td><td>Not available because not in the Encoding Standard</td></tr>
//! <tr><td><code>encoding::all::ASCII</code></td><td>Not available because not in the Encoding Standard</td></tr>
//! <tr><td><code>encoding::all::ISO_8859_1</code></td><td>Not available because not in the Encoding Standard</td></tr>
//! <tr><td><code>encoding::all::HZ</code></td><td>Not available because not in the Encoding Standard</td></tr>
//! <tr><td><code>encoding::label::encoding_from_whatwg_label(<var>string</var>)</code></td><td><code>encoding_rs::Encoding::for_label(<var>string</var>)</code></td></tr>
//! <tr><td><code><var>enc</var>.whatwg_name()</code> (always lower case)</td><td><code><var>enc</var>.name()</code> (potentially mixed case)</td></tr>
//! <tr><td><code><var>enc</var>.name()</code></td><td>Not available because not in the Encoding Standard</td></tr>
//! <tr><td><code>encoding::decode(<var>bytes</var>, encoding::DecoderTrap::Replace, <var>enc</var>)</code></td><td><code><var>enc</var>.decode(<var>bytes</var>)</code></td></tr>
//! <tr><td><code><var>enc</var>.decode(<var>bytes</var>, encoding::DecoderTrap::Replace)</code></td><td><code><var>enc</var>.decode_without_bom_handling(<var>bytes</var>)</code></td></tr>
//! <tr><td><code><var>enc</var>.encode(<var>string</var>, encoding::EncoderTrap::NcrEscape)</code></td><td><code><var>enc</var>.encode(<var>string</var>)</code></td></tr>
//! <tr><td><code><var>enc</var>.raw_decoder()</code></td><td><code><var>enc</var>.new_decoder_without_bom_handling()</code></td></tr>
//! <tr><td><code><var>enc</var>.raw_encoder()</code></td><td><code><var>enc</var>.new_encoder()</code></td></tr>
//! <tr><td><code>encoding::RawDecoder</code></td><td><code>encoding_rs::Decoder</code></td></tr>
//! <tr><td><code>encoding::RawEncoder</code></td><td><code>encoding_rs::Encoder</code></td></tr>
//! <tr><td><code><var>raw_decoder</var>.raw_feed(<var>src</var>, <var>dst_string</var>)</code></td><td><code><var>dst_string</var>.reserve(<var>decoder</var>.max_utf8_buffer_length_without_replacement(<var>src</var>.len()));<br><var>decoder</var>.decode_to_string_without_replacement(<var>src</var>, <var>dst_string</var>, false)</code></td></tr>
//! <tr><td><code><var>raw_encoder</var>.raw_feed(<var>src</var>, <var>dst_vec</var>)</code></td><td><code><var>dst_vec</var>.reserve(<var>encoder</var>.max_buffer_length_from_utf8_without_replacement(<var>src</var>.len()));<br><var>encoder</var>.encode_from_utf8_to_vec_without_replacement(<var>src</var>, <var>dst_vec</var>, false)</code></td></tr>
//! <tr><td><code><var>raw_decoder</var>.raw_finish(<var>dst</var>)</code></td><td><code><var>dst_string</var>.reserve(<var>decoder</var>.max_utf8_buffer_length_without_replacement(0));<br><var>decoder</var>.decode_to_string_without_replacement(b"", <var>dst</var>, true)</code></td></tr>
//! <tr><td><code><var>raw_encoder</var>.raw_finish(<var>dst</var>)</code></td><td><code><var>dst_vec</var>.reserve(<var>encoder</var>.max_buffer_length_from_utf8_without_replacement(0));<br><var>encoder</var>.encode_from_utf8_to_vec_without_replacement("", <var>dst</var>, true)</code></td></tr>
//! <tr><td><code>encoding::DecoderTrap::Strict</code></td><td><code>decode*</code> methods that have <code>_without_replacement</code> in their name (and treating the `Malformed` result as fatal).</td></tr>
//! <tr><td><code>encoding::DecoderTrap::Replace</code></td><td><code>decode*</code> methods that <i>do not</i> have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::DecoderTrap::Ignore</code></td><td>It is a bad idea to ignore errors due to security issues, but this could be implemented using <code>decode*</code> methods that have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::DecoderTrap::Call(DecoderTrapFunc)</code></td><td>Can be implemented using <code>decode*</code> methods that have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::EncoderTrap::Strict</code></td><td><code>encode*</code> methods that have <code>_without_replacement</code> in their name (and treating the `Unmappable` result as fatal).</td></tr>
//! <tr><td><code>encoding::EncoderTrap::Replace</code></td><td>Can be implemented using <code>encode*</code> methods that have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::EncoderTrap::Ignore</code></td><td>It is a bad idea to ignore errors due to security issues, but this could be implemented using <code>encode*</code> methods that have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::EncoderTrap::NcrEscape</code></td><td><code>encode*</code> methods that <i>do not</i> have <code>_without_replacement</code> in their name.</td></tr>
//! <tr><td><code>encoding::EncoderTrap::Call(EncoderTrapFunc)</code></td><td>Can be implemented using <code>encode*</code> methods that have <code>_without_replacement</code> in their name.</td></tr>
//! </tbody>
//! </table>
//!
//! # Relationship with Windows Code Pages
//!
//! Despite the Web and browser focus, the encodings defined by the Encoding
//! Standard and implemented by this crate may be useful for decoding legacy
//! data that uses Windows code pages. The following table names the single-byte
//! encodings
//! that have a closely related Windows code page, the number of the closest
//! code page, a column indicating whether Windows maps unassigned code points
//! to the Unicode Private Use Area instead of U+FFFD and a remark number
//! indicating remarks in the list after the table.
//!
//! <table>
//! <thead>
//! <tr><th>Encoding</th><th>Code Page</th><th>PUA</th><th>Remarks</th></tr>
//! </thead>
//! <tbody>
//! <tr><td>Shift_JIS</td><td>932</td><td></td><td></td></tr>
//! <tr><td>GBK</td><td>936</td><td></td><td></td></tr>
//! <tr><td>EUC-KR</td><td>949</td><td></td><td></td></tr>
//! <tr><td>Big5</td><td>950</td><td></td><td></td></tr>
//! <tr><td>IBM866</td><td>866</td><td></td><td></td></tr>
//! <tr><td>windows-874</td><td>874</td><td>&bullet;</td><td></td></tr>
//! <tr><td>UTF-16LE</td><td>1200</td><td></td><td></td></tr>
//! <tr><td>UTF-16BE</td><td>1201</td><td></td><td></td></tr>
//! <tr><td>windows-1250</td><td>1250</td><td></td><td></td></tr>
//! <tr><td>windows-1251</td><td>1251</td><td></td><td></td></tr>
//! <tr><td>windows-1252</td><td>1252</td><td></td><td></td></tr>
//! <tr><td>windows-1253</td><td>1253</td><td>&bullet;</td><td></td></tr>
//! <tr><td>windows-1254</td><td>1254</td><td></td><td></td></tr>
//! <tr><td>windows-1255</td><td>1255</td><td>&bullet;</td><td></td></tr>
//! <tr><td>windows-1256</td><td>1256</td><td></td><td></td></tr>
//! <tr><td>windows-1257</td><td>1257</td><td>&bullet;</td><td></td></tr>
//! <tr><td>windows-1258</td><td>1258</td><td></td><td></td></tr>
//! <tr><td>macintosh</td><td>10000</td><td></td><td>1</td></tr>
//! <tr><td>x-mac-cyrillic</td><td>10017</td><td></td><td>2</td></tr>
//! <tr><td>KOI8-R</td><td>20866</td><td></td><td></td></tr>
//! <tr><td>EUC-JP</td><td>20932</td><td></td><td></td></tr>
//! <tr><td>KOI8-U</td><td>21866</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-2</td><td>28592</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-3</td><td>28593</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-4</td><td>28594</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-5</td><td>28595</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-6</td><td>28596</td><td>&bullet;</td><td></td></tr>
//! <tr><td>ISO-8859-7</td><td>28597</td><td>&bullet;</td><td>3</td></tr>
//! <tr><td>ISO-8859-8</td><td>28598</td><td>&bullet;</td><td>4</td></tr>
//! <tr><td>ISO-8859-13</td><td>28603</td><td>&bullet;</td><td></td></tr>
//! <tr><td>ISO-8859-15</td><td>28605</td><td></td><td></td></tr>
//! <tr><td>ISO-8859-8-I</td><td>38598</td><td></td><td>5</td></tr>
//! <tr><td>ISO-2022-JP</td><td>50220</td><td></td><td></td></tr>
//! <tr><td>gb18030</td><td>54936</td><td></td><td></td></tr>
//! <tr><td>UTF-8</td><td>65001</td><td></td><td></td></tr>
//! </tbody>
//! </table>
//!
//! 1. Windows decodes 0xBD to U+2126 OHM SIGN instead of U+03A9 GREEK CAPITAL LETTER OMEGA.
//! 2. Windows decodes 0xFF to U+00A4 CURRENCY SIGN instead of U+20AC EURO SIGN.
//! 3. Windows decodes the currency signs at 0xA4 and 0xA5 as well as 0xAA,
//!    which should be U+037A GREEK YPOGEGRAMMENI, to PUA code points. Windows
//!    decodes 0xA1 to U+02BD MODIFIER LETTER REVERSED COMMA instead of U+2018
//!    LEFT SINGLE QUOTATION MARK and 0xA2 to U+02BC MODIFIER LETTER APOSTROPHE
//!    instead of U+2019 RIGHT SINGLE QUOTATION MARK.
//! 4. Windows decodes 0xAF to OVERLINE instead of MACRON and 0xFE and 0xFD to PUA instead
//!    of LRM and RLM.
//! 5. Remarks from the previous item apply.
//!
//! The differences between this crate and Windows in the case of multibyte encodings
//! are not yet fully documented here. The lack of remarks above should not be taken
//! as indication of lack of differences.
//!
//! # Notable Differences from IANA Naming
//!
//! In some cases, the Encoding Standard specifies the popular unextended encoding
//! name where in IANA terms one of the other labels would be more precise considering
//! the extensions that the Encoding Standard has unified into the encoding.
//!
//! <table>
//! <thead>
//! <tr><th>Encoding</th><th>IANA</th></tr>
//! </thead>
//! <tbody>
//! <tr><td>Big5</td><td>Big5-HKSCS</td></tr>
//! <tr><td>EUC-KR</td><td>windows-949</td></tr>
//! <tr><td>Shift_JIS</td><td>windows-31j</td></tr>
//! <tr><td>x-mac-cyrillic</td><td>x-mac-ukrainian</td></tr>
//! </tbody>
//! </table>
//!
//! In other cases where the Encoding Standard unifies unextended and extended
//! variants of an encoding, the encoding gets the name of the extended
//! variant.
//!
//! <table>
//! <thead>
//! <tr><th>IANA</th><th>Unified into Encoding</th></tr>
//! </thead>
//! <tbody>
//! <tr><td>ISO-8859-1</td><td>windows-1252</td></tr>
//! <tr><td>ISO-8859-9</td><td>windows-1254</td></tr>
//! <tr><td>TIS-620</td><td>windows-874</td></tr>
//! </tbody>
//! </table>
//!
//! See the section [_UTF-16LE, UTF-16BE and Unicode Encoding Schemes_](#utf-16le-utf-16be-and-unicode-encoding-schemes)
//! for discussion about the UTF-16 family.

#![cfg_attr(feature = "simd-accel", feature(stdsimd, core_intrinsics))]

#[macro_use]
extern crate cfg_if;

#[cfg(all(
    feature = "simd-accel",
    any(
        target_feature = "sse2",
        all(target_endian = "little", target_arch = "aarch64"),
        all(target_endian = "little", target_feature = "neon")
    )
))]
#[macro_use(shuffle)]
extern crate packed_simd;

#[cfg(feature = "serde")]
extern crate serde;

#[cfg(all(test, feature = "serde"))]
extern crate bincode;
#[cfg(all(test, feature = "serde"))]
#[macro_use]
extern crate serde_derive;
#[cfg(all(test, feature = "serde"))]
extern crate serde_json;

#[macro_use]
mod macros;

#[cfg(all(
    feature = "simd-accel",
    any(
        target_feature = "sse2",
        all(target_endian = "little", target_arch = "aarch64"),
        all(target_endian = "little", target_feature = "neon")
    )
))]
mod simd_funcs;

#[cfg(test)]
mod testing;

mod big5;
mod euc_jp;
mod euc_kr;
mod gb18030;
mod iso_2022_jp;
mod replacement;
mod shift_jis;
mod single_byte;
mod utf_16;
mod utf_8;
mod x_user_defined;

mod ascii;
mod data;
mod handles;
mod variant;

pub mod mem;

use ascii::ascii_valid_up_to;
use ascii::iso_2022_jp_ascii_valid_up_to;
use utf_8::utf8_valid_up_to;
use variant::*;

use std::borrow::Cow;
use std::cmp::Ordering;
use std::hash::Hash;
use std::hash::Hasher;

#[cfg(feature = "serde")]
use serde::de::Visitor;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// This has to be the max length of an NCR instead of max
/// minus one, because we can't rely on getting the minus
/// one from the space reserved for the current unmappable,
/// because the ISO-2022-JP encoder can fill up that space
/// with a state transition escape.
const NCR_EXTRA: usize = 10; // &#1114111;

// BEGIN GENERATED CODE. PLEASE DO NOT EDIT.
// Instead, please regenerate using generate-encoding-data.py

const LONGEST_LABEL_LENGTH: usize = 19; // cseucpkdfmtjapanese

/// The initializer for the [Big5](static.BIG5.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static BIG5_INIT: Encoding = Encoding {
    name: "Big5",
    variant: VariantEncoding::Big5,
};

/// The Big5 encoding.
///
/// This is Big5 with HKSCS with mappings to more recent Unicode assignments
/// instead of the Private Use Area code points that have been used historically.
/// It is believed to be able to decode existing Web content in a way that makes
/// sense.
///
/// To avoid form submissions generating data that Web servers don't understand,
/// the encoder doesn't use the HKSCS byte sequences that precede the unextended
/// Big5 in the lexical order.
///
/// [Index visualization](https://encoding.spec.whatwg.org/big5.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/big5-bmp.html)
///
/// This encoding is designed to be suited for decoding the Windows code page 950
/// and its HKSCS patched "951" variant such that the text makes sense, given
/// assignments that Unicode has made after those encodings used Private Use
/// Area characters.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static BIG5: &'static Encoding = &BIG5_INIT;

/// The initializer for the [EUC-JP](static.EUC_JP.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static EUC_JP_INIT: Encoding = Encoding {
    name: "EUC-JP",
    variant: VariantEncoding::EucJp,
};

/// The EUC-JP encoding.
///
/// This is the legacy Unix encoding for Japanese.
///
/// For compatibility with Web servers that don't expect three-byte sequences
/// in form submissions, the encoder doesn't generate three-byte sequences.
/// That is, the JIS X 0212 support is decode-only.
///
/// [Index visualization](https://encoding.spec.whatwg.org/euc-jp.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/euc-jp-bmp.html)
///
/// This encoding roughly matches the Windows code page 20932. There are error
/// handling differences and a handful of 2-byte sequences that decode differently.
/// Additionall, Windows doesn't support 3-byte sequences.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static EUC_JP: &'static Encoding = &EUC_JP_INIT;

/// The initializer for the [EUC-KR](static.EUC_KR.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static EUC_KR_INIT: Encoding = Encoding {
    name: "EUC-KR",
    variant: VariantEncoding::EucKr,
};

/// The EUC-KR encoding.
///
/// This is the Korean encoding for Windows. It extends the Unix legacy encoding
/// for Korean, based on KS X 1001 (which also formed the base of MacKorean on Mac OS
/// Classic), with all the characters from the Hangul Syllables block of Unicode.
///
/// [Index visualization](https://encoding.spec.whatwg.org/euc-kr.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/euc-kr-bmp.html)
///
/// This encoding matches the Windows code page 949, except Windows decodes byte 0x80
/// to U+0080 and some byte sequences that are error per the Encoding Standard to
/// the question mark or the Private Use Area.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static EUC_KR: &'static Encoding = &EUC_KR_INIT;

/// The initializer for the [GBK](static.GBK.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static GBK_INIT: Encoding = Encoding {
    name: "GBK",
    variant: VariantEncoding::Gbk,
};

/// The GBK encoding.
///
/// The decoder for this encoding is the same as the decoder for gb18030.
/// The encoder side of this encoding is GBK with Windows code page 936 euro
/// sign behavior. GBK extends GB2312-80 to cover the CJK Unified Ideographs
/// Unicode block as well as a handful of ideographs from the CJK Unified
/// Ideographs Extension A and CJK Compatibility Ideographs blocks.
///
/// Unlike e.g. in the case of ISO-8859-1 and windows-1252, GBK encoder wasn't
/// unified with the gb18030 encoder in the Encoding Standard out of concern
/// that servers that expect GBK form submissions might not be able to handle
/// the four-byte sequences.
///
/// [Index visualization for the two-byte sequences](https://encoding.spec.whatwg.org/gb18030.html),
/// [Visualization of BMP coverage of the two-byte index](https://encoding.spec.whatwg.org/gb18030-bmp.html)
///
/// The encoder of this encoding roughly matches the Windows code page 936.
/// The decoder side is a superset.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static GBK: &'static Encoding = &GBK_INIT;

/// The initializer for the [IBM866](static.IBM866.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static IBM866_INIT: Encoding = Encoding {
    name: "IBM866",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.ibm866, 0x0440, 96, 16),
};

/// The IBM866 encoding.
///
/// This the most notable one of the DOS Cyrillic code pages. It has the same
/// box drawing characters as code page 437, so it can be used for decoding
/// DOS-era ASCII + box drawing data.
///
/// [Index visualization](https://encoding.spec.whatwg.org/ibm866.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/ibm866-bmp.html)
///
/// This encoding matches the Windows code page 866.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static IBM866: &'static Encoding = &IBM866_INIT;

/// The initializer for the [ISO-2022-JP](static.ISO_2022_JP.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_2022_JP_INIT: Encoding = Encoding {
    name: "ISO-2022-JP",
    variant: VariantEncoding::Iso2022Jp,
};

/// The ISO-2022-JP encoding.
///
/// This the primary pre-UTF-8 encoding for Japanese email. It uses the ASCII
/// byte range to encode non-Basic Latin characters. It's the only encoding
/// supported by this crate whose encoder is stateful.
///
/// [Index visualization](https://encoding.spec.whatwg.org/jis0208.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/jis0208-bmp.html)
///
/// This encoding roughly matches the Windows code page 50220. Notably, Windows
/// uses U+30FB in place of the REPLACEMENT CHARACTER and otherwise differs in
/// error handling.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_2022_JP: &'static Encoding = &ISO_2022_JP_INIT;

/// The initializer for the [ISO-8859-10](static.ISO_8859_10.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_10_INIT: Encoding = Encoding {
    name: "ISO-8859-10",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_10, 0x00DA, 90, 6),
};

/// The ISO-8859-10 encoding.
///
/// This is the Nordic part of the ISO/IEC 8859 encoding family. This encoding
/// is also known as Latin 6.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-10.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-10-bmp.html)
///
/// The Windows code page number for this encoding is 28600, but kernel32.dll
/// does not support this encoding.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_10: &'static Encoding = &ISO_8859_10_INIT;

/// The initializer for the [ISO-8859-13](static.ISO_8859_13.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_13_INIT: Encoding = Encoding {
    name: "ISO-8859-13",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_13, 0x00DF, 95, 1),
};

/// The ISO-8859-13 encoding.
///
/// This is the Baltic part of the ISO/IEC 8859 encoding family. This encoding
/// is also known as Latin 7.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-13.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-13-bmp.html)
///
/// This encoding matches the Windows code page 28603, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_13: &'static Encoding = &ISO_8859_13_INIT;

/// The initializer for the [ISO-8859-14](static.ISO_8859_14.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_14_INIT: Encoding = Encoding {
    name: "ISO-8859-14",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_14, 0x00DF, 95, 17),
};

/// The ISO-8859-14 encoding.
///
/// This is the Celtic part of the ISO/IEC 8859 encoding family. This encoding
/// is also known as Latin 8.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-14.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-14-bmp.html)
///
/// The Windows code page number for this encoding is 28604, but kernel32.dll
/// does not support this encoding.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_14: &'static Encoding = &ISO_8859_14_INIT;

/// The initializer for the [ISO-8859-15](static.ISO_8859_15.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_15_INIT: Encoding = Encoding {
    name: "ISO-8859-15",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_15, 0x00BF, 63, 65),
};

/// The ISO-8859-15 encoding.
///
/// This is the revised Western European part of the ISO/IEC 8859 encoding
/// family. This encoding is also known as Latin 9.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-15.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-15-bmp.html)
///
/// This encoding matches the Windows code page 28605.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_15: &'static Encoding = &ISO_8859_15_INIT;

/// The initializer for the [ISO-8859-16](static.ISO_8859_16.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_16_INIT: Encoding = Encoding {
    name: "ISO-8859-16",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_16, 0x00DF, 95, 4),
};

/// The ISO-8859-16 encoding.
///
/// This is the South-Eastern European part of the ISO/IEC 8859 encoding
/// family. This encoding is also known as Latin 10.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-16.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-16-bmp.html)
///
/// The Windows code page number for this encoding is 28606, but kernel32.dll
/// does not support this encoding.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_16: &'static Encoding = &ISO_8859_16_INIT;

/// The initializer for the [ISO-8859-2](static.ISO_8859_2.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_2_INIT: Encoding = Encoding {
    name: "ISO-8859-2",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_2, 0x00DF, 95, 1),
};

/// The ISO-8859-2 encoding.
///
/// This is the Central European part of the ISO/IEC 8859 encoding family. This encoding is also known as Latin 2.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-2.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-2-bmp.html)
///
/// This encoding matches the Windows code page 28592.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_2: &'static Encoding = &ISO_8859_2_INIT;

/// The initializer for the [ISO-8859-3](static.ISO_8859_3.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_3_INIT: Encoding = Encoding {
    name: "ISO-8859-3",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_3, 0x00DF, 95, 4),
};

/// The ISO-8859-3 encoding.
///
/// This is the South European part of the ISO/IEC 8859 encoding family. This encoding is also known as Latin 3.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-3.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-3-bmp.html)
///
/// This encoding matches the Windows code page 28593.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_3: &'static Encoding = &ISO_8859_3_INIT;

/// The initializer for the [ISO-8859-4](static.ISO_8859_4.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_4_INIT: Encoding = Encoding {
    name: "ISO-8859-4",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_4, 0x00DF, 95, 1),
};

/// The ISO-8859-4 encoding.
///
/// This is the North European part of the ISO/IEC 8859 encoding family. This encoding is also known as Latin 4.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-4.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-4-bmp.html)
///
/// This encoding matches the Windows code page 28594.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_4: &'static Encoding = &ISO_8859_4_INIT;

/// The initializer for the [ISO-8859-5](static.ISO_8859_5.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_5_INIT: Encoding = Encoding {
    name: "ISO-8859-5",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_5, 0x040E, 46, 66),
};

/// The ISO-8859-5 encoding.
///
/// This is the Cyrillic part of the ISO/IEC 8859 encoding family.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-5.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-5-bmp.html)
///
/// This encoding matches the Windows code page 28595.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_5: &'static Encoding = &ISO_8859_5_INIT;

/// The initializer for the [ISO-8859-6](static.ISO_8859_6.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_6_INIT: Encoding = Encoding {
    name: "ISO-8859-6",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_6, 0x0621, 65, 26),
};

/// The ISO-8859-6 encoding.
///
/// This is the Arabic part of the ISO/IEC 8859 encoding family.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-6.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-6-bmp.html)
///
/// This encoding matches the Windows code page 28596, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_6: &'static Encoding = &ISO_8859_6_INIT;

/// The initializer for the [ISO-8859-7](static.ISO_8859_7.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_7_INIT: Encoding = Encoding {
    name: "ISO-8859-7",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_7, 0x03A3, 83, 44),
};

/// The ISO-8859-7 encoding.
///
/// This is the Greek part of the ISO/IEC 8859 encoding family.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-7.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-7-bmp.html)
///
/// This encoding roughly matches the Windows code page 28597. Windows decodes
/// unassigned code points, the currency signs at 0xA4 and 0xA5 as well as
/// 0xAA, which should be U+037A GREEK YPOGEGRAMMENI, to the Private Use Area
/// of Unicode. Windows decodes 0xA1 to U+02BD MODIFIER LETTER REVERSED COMMA
/// instead of U+2018 LEFT SINGLE QUOTATION MARK and 0xA2 to U+02BC MODIFIER
/// LETTER APOSTROPHE instead of U+2019 RIGHT SINGLE QUOTATION MARK.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_7: &'static Encoding = &ISO_8859_7_INIT;

/// The initializer for the [ISO-8859-8](static.ISO_8859_8.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_8_INIT: Encoding = Encoding {
    name: "ISO-8859-8",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_8, 0x05D0, 96, 27),
};

/// The ISO-8859-8 encoding.
///
/// This is the Hebrew part of the ISO/IEC 8859 encoding family in visual order.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-8.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-8-bmp.html)
///
/// This encoding roughly matches the Windows code page 28598. Windows decodes
/// 0xAF to OVERLINE instead of MACRON and 0xFE and 0xFD to the Private Use
/// Area instead of LRM and RLM. Windows decodes unassigned code points to
/// the private use area.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_8: &'static Encoding = &ISO_8859_8_INIT;

/// The initializer for the [ISO-8859-8-I](static.ISO_8859_8_I.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static ISO_8859_8_I_INIT: Encoding = Encoding {
    name: "ISO-8859-8-I",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.iso_8859_8, 0x05D0, 96, 27),
};

/// The ISO-8859-8-I encoding.
///
/// This is the Hebrew part of the ISO/IEC 8859 encoding family in logical order.
///
/// [Index visualization](https://encoding.spec.whatwg.org/iso-8859-8.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/iso-8859-8-bmp.html)
///
/// This encoding roughly matches the Windows code page 38598. Windows decodes
/// 0xAF to OVERLINE instead of MACRON and 0xFE and 0xFD to the Private Use
/// Area instead of LRM and RLM. Windows decodes unassigned code points to
/// the private use area.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static ISO_8859_8_I: &'static Encoding = &ISO_8859_8_I_INIT;

/// The initializer for the [KOI8-R](static.KOI8_R.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static KOI8_R_INIT: Encoding = Encoding {
    name: "KOI8-R",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.koi8_r, 0x044E, 64, 1),
};

/// The KOI8-R encoding.
///
/// This is an encoding for Russian from [RFC 1489](https://tools.ietf.org/html/rfc1489).
///
/// [Index visualization](https://encoding.spec.whatwg.org/koi8-r.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/koi8-r-bmp.html)
///
/// This encoding matches the Windows code page 20866.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static KOI8_R: &'static Encoding = &KOI8_R_INIT;

/// The initializer for the [KOI8-U](static.KOI8_U.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static KOI8_U_INIT: Encoding = Encoding {
    name: "KOI8-U",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.koi8_u, 0x044E, 64, 1),
};

/// The KOI8-U encoding.
///
/// This is an encoding for Ukrainian adapted from KOI8-R.
///
/// [Index visualization](https://encoding.spec.whatwg.org/koi8-u.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/koi8-u-bmp.html)
///
/// This encoding matches the Windows code page 21866.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static KOI8_U: &'static Encoding = &KOI8_U_INIT;

/// The initializer for the [Shift_JIS](static.SHIFT_JIS.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static SHIFT_JIS_INIT: Encoding = Encoding {
    name: "Shift_JIS",
    variant: VariantEncoding::ShiftJis,
};

/// The Shift_JIS encoding.
///
/// This is the Japanese encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/shift_jis.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/shift_jis-bmp.html)
///
/// This encoding matches the Windows code page 932, except Windows decodes some byte
/// sequences that are error per the Encoding Standard to the question mark or the
/// Private Use Area and generally uses U+30FB in place of the REPLACEMENT CHARACTER.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static SHIFT_JIS: &'static Encoding = &SHIFT_JIS_INIT;

/// The initializer for the [UTF-16BE](static.UTF_16BE.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static UTF_16BE_INIT: Encoding = Encoding {
    name: "UTF-16BE",
    variant: VariantEncoding::Utf16Be,
};

/// The UTF-16BE encoding.
///
/// This decode-only encoding uses 16-bit code units due to Unicode originally
/// having been designed as a 16-bit reportoire. In the absence of a byte order
/// mark the big endian byte order is assumed.
///
/// There is no corresponding encoder in this crate or in the Encoding
/// Standard. The output encoding of this encoding is UTF-8.
///
/// This encoding matches the Windows code page 1201.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static UTF_16BE: &'static Encoding = &UTF_16BE_INIT;

/// The initializer for the [UTF-16LE](static.UTF_16LE.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static UTF_16LE_INIT: Encoding = Encoding {
    name: "UTF-16LE",
    variant: VariantEncoding::Utf16Le,
};

/// The UTF-16LE encoding.
///
/// This decode-only encoding uses 16-bit code units due to Unicode originally
/// having been designed as a 16-bit reportoire. In the absence of a byte order
/// mark the little endian byte order is assumed.
///
/// There is no corresponding encoder in this crate or in the Encoding
/// Standard. The output encoding of this encoding is UTF-8.
///
/// This encoding matches the Windows code page 1200.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static UTF_16LE: &'static Encoding = &UTF_16LE_INIT;

/// The initializer for the [UTF-8](static.UTF_8.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static UTF_8_INIT: Encoding = Encoding {
    name: "UTF-8",
    variant: VariantEncoding::Utf8,
};

/// The UTF-8 encoding.
///
/// This is the encoding that should be used for all new development it can
/// represent all of Unicode.
///
/// This encoding matches the Windows code page 65001, except Windows differs
/// in the number of errors generated for some erroneous byte sequences.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static UTF_8: &'static Encoding = &UTF_8_INIT;

/// The initializer for the [gb18030](static.GB18030.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static GB18030_INIT: Encoding = Encoding {
    name: "gb18030",
    variant: VariantEncoding::Gb18030,
};

/// The gb18030 encoding.
///
/// This encoding matches GB18030-2005 except the two-byte sequence 0xA3 0xA0
/// maps to U+3000 for compatibility with existing Web content. As a result,
/// this encoding can represent all of Unicode except for the private-use
/// character U+E5E5.
///
/// [Index visualization for the two-byte sequences](https://encoding.spec.whatwg.org/gb18030.html),
/// [Visualization of BMP coverage of the two-byte index](https://encoding.spec.whatwg.org/gb18030-bmp.html)
///
/// This encoding matches the Windows code page 54936.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static GB18030: &'static Encoding = &GB18030_INIT;

/// The initializer for the [macintosh](static.MACINTOSH.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static MACINTOSH_INIT: Encoding = Encoding {
    name: "macintosh",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.macintosh, 0x00CD, 106, 3),
};

/// The macintosh encoding.
///
/// This is the MacRoman encoding from Mac OS Classic.
///
/// [Index visualization](https://encoding.spec.whatwg.org/macintosh.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/macintosh-bmp.html)
///
/// This encoding matches the Windows code page 10000, except Windows decodes
/// 0xBD to U+2126 OHM SIGN instead of U+03A9 GREEK CAPITAL LETTER OMEGA.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static MACINTOSH: &'static Encoding = &MACINTOSH_INIT;

/// The initializer for the [replacement](static.REPLACEMENT.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static REPLACEMENT_INIT: Encoding = Encoding {
    name: "replacement",
    variant: VariantEncoding::Replacement,
};

/// The replacement encoding.
///
/// This decode-only encoding decodes all non-zero-length streams to a single
/// REPLACEMENT CHARACTER. Its purpose is to avoid the use of an
/// ASCII-compatible fallback encoding (typically windows-1252) for some
/// encodings that are no longer supported by the Web Platform and that
/// would be dangerous to treat as ASCII-compatible.
///
/// There is no corresponding encoder. The output encoding of this encoding
/// is UTF-8.
///
/// This encoding does not have a Windows code page number.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static REPLACEMENT: &'static Encoding = &REPLACEMENT_INIT;

/// The initializer for the [windows-1250](static.WINDOWS_1250.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1250_INIT: Encoding = Encoding {
    name: "windows-1250",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1250, 0x00DC, 92, 2),
};

/// The windows-1250 encoding.
///
/// This is the Central European encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1250.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1250-bmp.html)
///
/// This encoding matches the Windows code page 1250.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1250: &'static Encoding = &WINDOWS_1250_INIT;

/// The initializer for the [windows-1251](static.WINDOWS_1251.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1251_INIT: Encoding = Encoding {
    name: "windows-1251",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1251, 0x0410, 64, 64),
};

/// The windows-1251 encoding.
///
/// This is the Cyrillic encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1251.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1251-bmp.html)
///
/// This encoding matches the Windows code page 1251.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1251: &'static Encoding = &WINDOWS_1251_INIT;

/// The initializer for the [windows-1252](static.WINDOWS_1252.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1252_INIT: Encoding = Encoding {
    name: "windows-1252",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1252, 0x00A0, 32, 96),
};

/// The windows-1252 encoding.
///
/// This is the Western encoding for Windows. It is an extension of ISO-8859-1,
/// which is known as Latin 1.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1252.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1252-bmp.html)
///
/// This encoding matches the Windows code page 1252.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1252: &'static Encoding = &WINDOWS_1252_INIT;

/// The initializer for the [windows-1253](static.WINDOWS_1253.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1253_INIT: Encoding = Encoding {
    name: "windows-1253",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1253, 0x03A3, 83, 44),
};

/// The windows-1253 encoding.
///
/// This is the Greek encoding for Windows. It is mostly an extension of
/// ISO-8859-7, but U+0386 is mapped to a different byte.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1253.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1253-bmp.html)
///
/// This encoding matches the Windows code page 1253, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1253: &'static Encoding = &WINDOWS_1253_INIT;

/// The initializer for the [windows-1254](static.WINDOWS_1254.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1254_INIT: Encoding = Encoding {
    name: "windows-1254",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1254, 0x00DF, 95, 17),
};

/// The windows-1254 encoding.
///
/// This is the Turkish encoding for Windows. It is an extension of ISO-8859-9,
/// which is known as Latin 5.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1254.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1254-bmp.html)
///
/// This encoding matches the Windows code page 1254.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1254: &'static Encoding = &WINDOWS_1254_INIT;

/// The initializer for the [windows-1255](static.WINDOWS_1255.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1255_INIT: Encoding = Encoding {
    name: "windows-1255",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1255, 0x05D0, 96, 27),
};

/// The windows-1255 encoding.
///
/// This is the Hebrew encoding for Windows. It is an extension of ISO-8859-8-I,
/// except for a currency sign swap.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1255.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1255-bmp.html)
///
/// This encoding matches the Windows code page 1255, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1255: &'static Encoding = &WINDOWS_1255_INIT;

/// The initializer for the [windows-1256](static.WINDOWS_1256.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1256_INIT: Encoding = Encoding {
    name: "windows-1256",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1256, 0x0621, 65, 22),
};

/// The windows-1256 encoding.
///
/// This is the Arabic encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1256.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1256-bmp.html)
///
/// This encoding matches the Windows code page 1256.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1256: &'static Encoding = &WINDOWS_1256_INIT;

/// The initializer for the [windows-1257](static.WINDOWS_1257.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1257_INIT: Encoding = Encoding {
    name: "windows-1257",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1257, 0x00DF, 95, 1),
};

/// The windows-1257 encoding.
///
/// This is the Baltic encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1257.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1257-bmp.html)
///
/// This encoding matches the Windows code page 1257, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1257: &'static Encoding = &WINDOWS_1257_INIT;

/// The initializer for the [windows-1258](static.WINDOWS_1258.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_1258_INIT: Encoding = Encoding {
    name: "windows-1258",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_1258, 0x00DF, 95, 4),
};

/// The windows-1258 encoding.
///
/// This is the Vietnamese encoding for Windows.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-1258.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-1258-bmp.html)
///
/// This encoding matches the Windows code page 1258 when used in the
/// non-normalizing mode. Unlike with the other single-byte encodings, the
/// result of decoding is not necessarily in Normalization Form C. On the
/// other hand, input in the Normalization Form C is not encoded without
/// replacement. In general, it's a bad idea to encode to encodings other
/// than UTF-8, but this encoding is especially hazardous to encode to.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_1258: &'static Encoding = &WINDOWS_1258_INIT;

/// The initializer for the [windows-874](static.WINDOWS_874.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static WINDOWS_874_INIT: Encoding = Encoding {
    name: "windows-874",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.windows_874, 0x0E01, 33, 58),
};

/// The windows-874 encoding.
///
/// This is the Thai encoding for Windows. It is an extension of TIS-620 / ISO-8859-11.
///
/// [Index visualization](https://encoding.spec.whatwg.org/windows-874.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/windows-874-bmp.html)
///
/// This encoding matches the Windows code page 874, except Windows decodes
/// unassigned code points to the Private Use Area of Unicode.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static WINDOWS_874: &'static Encoding = &WINDOWS_874_INIT;

/// The initializer for the [x-mac-cyrillic](static.X_MAC_CYRILLIC.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static X_MAC_CYRILLIC_INIT: Encoding = Encoding {
    name: "x-mac-cyrillic",
    variant: VariantEncoding::SingleByte(&data::SINGLE_BYTE_DATA.x_mac_cyrillic, 0x0430, 96, 31),
};

/// The x-mac-cyrillic encoding.
///
/// This is the MacUkrainian encoding from Mac OS Classic.
///
/// [Index visualization](https://encoding.spec.whatwg.org/x-mac-cyrillic.html),
/// [Visualization of BMP coverage](https://encoding.spec.whatwg.org/x-mac-cyrillic-bmp.html)
///
/// This encoding matches the Windows code page 10017.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static X_MAC_CYRILLIC: &'static Encoding = &X_MAC_CYRILLIC_INIT;

/// The initializer for the [x-user-defined](static.X_USER_DEFINED.html) encoding.
///
/// For use only for taking the address of this form when
/// Rust prohibits the use of the non-`_INIT` form directly,
/// such as in initializers of other `static`s. If in doubt,
/// use the corresponding non-`_INIT` reference-typed `static`.
///
/// This part of the public API will go away if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate or if Rust starts allowing static arrays
/// to be initialized with `pub static FOO: &'static Encoding`
/// items.
pub static X_USER_DEFINED_INIT: Encoding = Encoding {
    name: "x-user-defined",
    variant: VariantEncoding::UserDefined,
};

/// The x-user-defined encoding.
///
/// This encoding offsets the non-ASCII bytes by `0xF700` thereby decoding
/// them to the Private Use Area of Unicode. It was used for loading binary
/// data into a JavaScript string using `XMLHttpRequest` before XHR supported
/// the `"arraybuffer"` response type.
///
/// This encoding does not have a Windows code page number.
///
/// This will change from `static` to `const` if Rust changes
/// to make the referent of `pub const FOO: &'static Encoding`
/// unique cross-crate, so don't take the address of this
/// `static`.
pub static X_USER_DEFINED: &'static Encoding = &X_USER_DEFINED_INIT;

static LABELS_SORTED: [&'static str; 219] = [
    "l1",
    "l2",
    "l3",
    "l4",
    "l5",
    "l6",
    "l9",
    "866",
    "mac",
    "koi",
    "gbk",
    "big5",
    "utf8",
    "koi8",
    "sjis",
    "ms932",
    "cp866",
    "utf-8",
    "cp819",
    "ascii",
    "x-gbk",
    "greek",
    "cp1250",
    "cp1251",
    "latin1",
    "gb2312",
    "cp1252",
    "latin2",
    "cp1253",
    "latin3",
    "cp1254",
    "latin4",
    "cp1255",
    "csbig5",
    "latin5",
    "utf-16",
    "cp1256",
    "ibm866",
    "latin6",
    "cp1257",
    "cp1258",
    "greek8",
    "ibm819",
    "arabic",
    "visual",
    "korean",
    "euc-jp",
    "koi8-r",
    "koi8_r",
    "euc-kr",
    "x-sjis",
    "koi8-u",
    "hebrew",
    "tis-620",
    "gb18030",
    "ksc5601",
    "gb_2312",
    "dos-874",
    "cn-big5",
    "chinese",
    "logical",
    "cskoi8r",
    "cseuckr",
    "koi8-ru",
    "x-cp1250",
    "ksc_5601",
    "x-cp1251",
    "iso88591",
    "csgb2312",
    "x-cp1252",
    "iso88592",
    "x-cp1253",
    "iso88593",
    "ecma-114",
    "x-cp1254",
    "iso88594",
    "x-cp1255",
    "iso88595",
    "x-x-big5",
    "x-cp1256",
    "csibm866",
    "iso88596",
    "x-cp1257",
    "iso88597",
    "asmo-708",
    "ecma-118",
    "elot_928",
    "x-cp1258",
    "iso88598",
    "iso88599",
    "cyrillic",
    "utf-16be",
    "utf-16le",
    "us-ascii",
    "ms_kanji",
    "x-euc-jp",
    "iso885910",
    "iso8859-1",
    "iso885911",
    "iso8859-2",
    "iso8859-3",
    "iso885913",
    "iso8859-4",
    "iso885914",
    "iso8859-5",
    "iso885915",
    "iso8859-6",
    "iso8859-7",
    "iso8859-8",
    "iso-ir-58",
    "iso8859-9",
    "macintosh",
    "shift-jis",
    "shift_jis",
    "iso-ir-100",
    "iso8859-10",
    "iso-ir-110",
    "gb_2312-80",
    "iso-8859-1",
    "iso_8859-1",
    "iso-ir-101",
    "iso8859-11",
    "iso-8859-2",
    "iso_8859-2",
    "hz-gb-2312",
    "iso-8859-3",
    "iso_8859-3",
    "iso8859-13",
    "iso-8859-4",
    "iso_8859-4",
    "iso8859-14",
    "iso-ir-144",
    "iso-8859-5",
    "iso_8859-5",
    "iso8859-15",
    "iso-8859-6",
    "iso_8859-6",
    "iso-ir-126",
    "iso-8859-7",
    "iso_8859-7",
    "iso-ir-127",
    "iso-ir-157",
    "iso-8859-8",
    "iso_8859-8",
    "iso-ir-138",
    "iso-ir-148",
    "iso-8859-9",
    "iso_8859-9",
    "iso-ir-109",
    "iso-ir-149",
    "big5-hkscs",
    "csshiftjis",
    "iso-8859-10",
    "iso-8859-11",
    "csisolatin1",
    "csisolatin2",
    "iso-8859-13",
    "csisolatin3",
    "iso-8859-14",
    "windows-874",
    "csisolatin4",
    "iso-8859-15",
    "iso_8859-15",
    "csisolatin5",
    "iso-8859-16",
    "csisolatin6",
    "windows-949",
    "csisolatin9",
    "csiso88596e",
    "csiso88598e",
    "csmacintosh",
    "csiso88596i",
    "csiso88598i",
    "windows-31j",
    "x-mac-roman",
    "iso-2022-cn",
    "iso-2022-jp",
    "csiso2022jp",
    "iso-2022-kr",
    "csiso2022kr",
    "replacement",
    "windows-1250",
    "windows-1251",
    "windows-1252",
    "windows-1253",
    "windows-1254",
    "windows-1255",
    "windows-1256",
    "windows-1257",
    "windows-1258",
    "iso-8859-6-e",
    "iso-8859-8-e",
    "iso-8859-6-i",
    "iso-8859-8-i",
    "sun_eu_greek",
    "csksc56011987",
    "ks_c_5601-1987",
    "ansi_x3.4-1968",
    "ks_c_5601-1989",
    "x-mac-cyrillic",
    "x-user-defined",
    "csiso58gb231280",
    "iso_8859-1:1987",
    "iso_8859-2:1987",
    "iso_8859-6:1987",
    "iso_8859-7:1987",
    "iso_8859-3:1988",
    "iso_8859-4:1988",
    "iso_8859-5:1988",
    "iso_8859-8:1988",
    "iso_8859-9:1989",
    "csisolatingreek",
    "x-mac-ukrainian",
    "iso-2022-cn-ext",
    "csisolatinarabic",
    "csisolatinhebrew",
    "unicode-1-1-utf-8",
    "csisolatincyrillic",
    "cseucpkdfmtjapanese",
];

static ENCODINGS_IN_LABEL_SORT: [&'static Encoding; 219] = [
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_4_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_10_INIT,
    &ISO_8859_15_INIT,
    &IBM866_INIT,
    &MACINTOSH_INIT,
    &KOI8_R_INIT,
    &GBK_INIT,
    &BIG5_INIT,
    &UTF_8_INIT,
    &KOI8_R_INIT,
    &SHIFT_JIS_INIT,
    &SHIFT_JIS_INIT,
    &IBM866_INIT,
    &UTF_8_INIT,
    &WINDOWS_1252_INIT,
    &WINDOWS_1252_INIT,
    &GBK_INIT,
    &ISO_8859_7_INIT,
    &WINDOWS_1250_INIT,
    &WINDOWS_1251_INIT,
    &WINDOWS_1252_INIT,
    &GBK_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &WINDOWS_1253_INIT,
    &ISO_8859_3_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_4_INIT,
    &WINDOWS_1255_INIT,
    &BIG5_INIT,
    &WINDOWS_1254_INIT,
    &UTF_16LE_INIT,
    &WINDOWS_1256_INIT,
    &IBM866_INIT,
    &ISO_8859_10_INIT,
    &WINDOWS_1257_INIT,
    &WINDOWS_1258_INIT,
    &ISO_8859_7_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_INIT,
    &EUC_KR_INIT,
    &EUC_JP_INIT,
    &KOI8_R_INIT,
    &KOI8_R_INIT,
    &EUC_KR_INIT,
    &SHIFT_JIS_INIT,
    &KOI8_U_INIT,
    &ISO_8859_8_INIT,
    &WINDOWS_874_INIT,
    &GB18030_INIT,
    &EUC_KR_INIT,
    &GBK_INIT,
    &WINDOWS_874_INIT,
    &BIG5_INIT,
    &GBK_INIT,
    &ISO_8859_8_I_INIT,
    &KOI8_R_INIT,
    &EUC_KR_INIT,
    &KOI8_U_INIT,
    &WINDOWS_1250_INIT,
    &EUC_KR_INIT,
    &WINDOWS_1251_INIT,
    &WINDOWS_1252_INIT,
    &GBK_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &WINDOWS_1253_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_6_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_4_INIT,
    &WINDOWS_1255_INIT,
    &ISO_8859_5_INIT,
    &BIG5_INIT,
    &WINDOWS_1256_INIT,
    &IBM866_INIT,
    &ISO_8859_6_INIT,
    &WINDOWS_1257_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_7_INIT,
    &WINDOWS_1258_INIT,
    &ISO_8859_8_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_5_INIT,
    &UTF_16BE_INIT,
    &UTF_16LE_INIT,
    &WINDOWS_1252_INIT,
    &SHIFT_JIS_INIT,
    &EUC_JP_INIT,
    &ISO_8859_10_INIT,
    &WINDOWS_1252_INIT,
    &WINDOWS_874_INIT,
    &ISO_8859_2_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_13_INIT,
    &ISO_8859_4_INIT,
    &ISO_8859_14_INIT,
    &ISO_8859_5_INIT,
    &ISO_8859_15_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_8_INIT,
    &GBK_INIT,
    &WINDOWS_1254_INIT,
    &MACINTOSH_INIT,
    &SHIFT_JIS_INIT,
    &SHIFT_JIS_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_10_INIT,
    &ISO_8859_4_INIT,
    &GBK_INIT,
    &WINDOWS_1252_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &WINDOWS_874_INIT,
    &ISO_8859_2_INIT,
    &ISO_8859_2_INIT,
    &REPLACEMENT_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_13_INIT,
    &ISO_8859_4_INIT,
    &ISO_8859_4_INIT,
    &ISO_8859_14_INIT,
    &ISO_8859_5_INIT,
    &ISO_8859_5_INIT,
    &ISO_8859_5_INIT,
    &ISO_8859_15_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_10_INIT,
    &ISO_8859_8_INIT,
    &ISO_8859_8_INIT,
    &ISO_8859_8_INIT,
    &WINDOWS_1254_INIT,
    &WINDOWS_1254_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_3_INIT,
    &EUC_KR_INIT,
    &BIG5_INIT,
    &SHIFT_JIS_INIT,
    &ISO_8859_10_INIT,
    &WINDOWS_874_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &ISO_8859_13_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_14_INIT,
    &WINDOWS_874_INIT,
    &ISO_8859_4_INIT,
    &ISO_8859_15_INIT,
    &ISO_8859_15_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_16_INIT,
    &ISO_8859_10_INIT,
    &EUC_KR_INIT,
    &ISO_8859_15_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_INIT,
    &MACINTOSH_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_I_INIT,
    &SHIFT_JIS_INIT,
    &MACINTOSH_INIT,
    &REPLACEMENT_INIT,
    &ISO_2022_JP_INIT,
    &ISO_2022_JP_INIT,
    &REPLACEMENT_INIT,
    &REPLACEMENT_INIT,
    &REPLACEMENT_INIT,
    &WINDOWS_1250_INIT,
    &WINDOWS_1251_INIT,
    &WINDOWS_1252_INIT,
    &WINDOWS_1253_INIT,
    &WINDOWS_1254_INIT,
    &WINDOWS_1255_INIT,
    &WINDOWS_1256_INIT,
    &WINDOWS_1257_INIT,
    &WINDOWS_1258_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_I_INIT,
    &ISO_8859_7_INIT,
    &EUC_KR_INIT,
    &EUC_KR_INIT,
    &WINDOWS_1252_INIT,
    &EUC_KR_INIT,
    &X_MAC_CYRILLIC_INIT,
    &X_USER_DEFINED_INIT,
    &GBK_INIT,
    &WINDOWS_1252_INIT,
    &ISO_8859_2_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_7_INIT,
    &ISO_8859_3_INIT,
    &ISO_8859_4_INIT,
    &ISO_8859_5_INIT,
    &ISO_8859_8_INIT,
    &WINDOWS_1254_INIT,
    &ISO_8859_7_INIT,
    &X_MAC_CYRILLIC_INIT,
    &REPLACEMENT_INIT,
    &ISO_8859_6_INIT,
    &ISO_8859_8_INIT,
    &UTF_8_INIT,
    &ISO_8859_5_INIT,
    &EUC_JP_INIT,
];

// END GENERATED CODE

/// An encoding as defined in the [Encoding Standard][1].
///
/// An _encoding_ defines a mapping from a `u8` sequence to a `char` sequence
/// and, in most cases, vice versa. Each encoding has a name, an output
/// encoding, and one or more labels.
///
/// _Labels_ are ASCII-case-insensitive strings that are used to identify an
/// encoding in formats and protocols. The _name_ of the encoding is the
/// preferred label in the case appropriate for returning from the
/// [`characterSet`][2] property of the `Document` DOM interface.
///
/// The _output encoding_ is the encoding used for form submission and URL
/// parsing on Web pages in the encoding. This is UTF-8 for the replacement,
/// UTF-16LE and UTF-16BE encodings and the encoding itself for other
/// encodings.
///
/// [1]: https://encoding.spec.whatwg.org/
/// [2]: https://dom.spec.whatwg.org/#dom-document-characterset
///
/// # Streaming vs. Non-Streaming
///
/// When you have the entire input in a single buffer, you can use the
/// methods [`decode()`][3], [`decode_with_bom_removal()`][3],
/// [`decode_without_bom_handling()`][5],
/// [`decode_without_bom_handling_and_without_replacement()`][6] and
/// [`encode()`][7]. (These methods are available to Rust callers only and are
/// not available in the C API.) Unlike the rest of the API available to Rust,
/// these methods perform heap allocations. You should the `Decoder` and
/// `Encoder` objects when your input is split into multiple buffers or when
/// you want to control the allocation of the output buffers.
///
/// [3]: #method.decode
/// [4]: #method.decode_with_bom_removal
/// [5]: #method.decode_without_bom_handling
/// [6]: #method.decode_without_bom_handling_and_without_replacement
/// [7]: #method.encode
///
/// # Instances
///
/// All instances of `Encoding` are statically allocated and have the `'static`
/// lifetime. There is precisely one unique `Encoding` instance for each
/// encoding defined in the Encoding Standard.
///
/// To obtain a reference to a particular encoding whose identity you know at
/// compile time, use a `static` that refers to encoding. There is a `static`
/// for each encoding. The `static`s are named in all caps with hyphens
/// replaced with underscores (and in C/C++ have `_ENCODING` appended to the
/// name). For example, if you know at compile time that you will want to
/// decode using the UTF-8 encoding, use the `UTF_8` `static` (`UTF_8_ENCODING`
/// in C/C++).
///
/// Additionally, there are non-reference-typed forms ending with `_INIT` to
/// work around the problem that `static`s of the type `&'static Encoding`
/// cannot be used to initialize items of an array whose type is
/// `[&'static Encoding; N]`.
///
/// If you don't know what encoding you need at compile time and need to
/// dynamically get an encoding by label, use
/// <code>Encoding::<a href="#method.for_label">for_label</a>(<var>label</var>)</code>.
///
/// Instances of `Encoding` can be compared with `==` (in both Rust and in
/// C/C++).
pub struct Encoding {
    name: &'static str,
    variant: VariantEncoding,
}

impl Encoding {
    /// Implements the
    /// [_get an encoding_](https://encoding.spec.whatwg.org/#concept-encoding-get)
    /// algorithm.
    ///
    /// If, after ASCII-lowercasing and removing leading and trailing
    /// whitespace, the argument matches a label defined in the Encoding
    /// Standard, `Some(&'static Encoding)` representing the corresponding
    /// encoding is returned. If there is no match, `None` is returned.
    ///
    /// This is the right method to use if the action upon the method returning
    /// `None` is to use a fallback encoding (e.g. `WINDOWS_1252`) instead.
    /// When the action upon the method returning `None` is not to proceed with
    /// a fallback but to refuse processing, `for_label_no_replacement()` is more
    /// appropriate.
    ///
    /// The argument is of type `&[u8]` instead of `&str` to save callers
    /// that are extracting the label from a non-UTF-8 protocol the trouble
    /// of conversion to UTF-8. (If you have a `&str`, just call `.as_bytes()`
    /// on it.)
    ///
    /// Available via the C wrapper.
    pub fn for_label(label: &[u8]) -> Option<&'static Encoding> {
        let mut trimmed = [0u8; LONGEST_LABEL_LENGTH];
        let mut trimmed_pos = 0usize;
        let mut iter = label.into_iter();
        // before
        loop {
            match iter.next() {
                None => {
                    return None;
                }
                Some(byte) => {
                    // The characters used in labels are:
                    // a-z (except q, but excluding it below seems excessive)
                    // 0-9
                    // . _ - :
                    match *byte {
                        0x09u8 | 0x0Au8 | 0x0Cu8 | 0x0Du8 | 0x20u8 => {
                            continue;
                        }
                        b'A'...b'Z' => {
                            trimmed[trimmed_pos] = *byte + 0x20u8;
                            trimmed_pos = 1usize;
                            break;
                        }
                        b'a'...b'z' | b'0'...b'9' | b'-' | b'_' | b':' | b'.' => {
                            trimmed[trimmed_pos] = *byte;
                            trimmed_pos = 1usize;
                            break;
                        }
                        _ => {
                            return None;
                        }
                    }
                }
            }
        }
        // inside
        loop {
            match iter.next() {
                None => {
                    break;
                }
                Some(byte) => {
                    match *byte {
                        0x09u8 | 0x0Au8 | 0x0Cu8 | 0x0Du8 | 0x20u8 => {
                            break;
                        }
                        b'A'...b'Z' => {
                            if trimmed_pos == LONGEST_LABEL_LENGTH {
                                // There's no encoding with a label this long
                                return None;
                            }
                            trimmed[trimmed_pos] = *byte + 0x20u8;
                            trimmed_pos += 1usize;
                            continue;
                        }
                        b'a'...b'z' | b'0'...b'9' | b'-' | b'_' | b':' | b'.' => {
                            if trimmed_pos == LONGEST_LABEL_LENGTH {
                                // There's no encoding with a label this long
                                return None;
                            }
                            trimmed[trimmed_pos] = *byte;
                            trimmed_pos += 1usize;
                            continue;
                        }
                        _ => {
                            return None;
                        }
                    }
                }
            }
        }
        // after
        loop {
            match iter.next() {
                None => {
                    break;
                }
                Some(byte) => {
                    match *byte {
                        0x09u8 | 0x0Au8 | 0x0Cu8 | 0x0Du8 | 0x20u8 => {
                            continue;
                        }
                        _ => {
                            // There's no label with space in the middle
                            return None;
                        }
                    }
                }
            }
        }
        let candidate = &trimmed[..trimmed_pos];
        match LABELS_SORTED.binary_search_by(|probe| {
            let bytes = probe.as_bytes();
            let c = bytes.len().cmp(&candidate.len());
            if c != Ordering::Equal {
                return c;
            }
            let probe_iter = bytes.iter().rev();
            let candidate_iter = candidate.iter().rev();
            probe_iter.cmp(candidate_iter)
        }) {
            Ok(i) => Some(ENCODINGS_IN_LABEL_SORT[i]),
            Err(_) => None,
        }
    }

    /// This method behaves the same as `for_label()`, except when `for_label()`
    /// would return `Some(REPLACEMENT)`, this method returns `None` instead.
    ///
    /// This method is useful in scenarios where a fatal error is required
    /// upon invalid label, because in those cases the caller typically wishes
    /// to treat the labels that map to the replacement encoding as fatal
    /// errors, too.
    ///
    /// It is not OK to use this method when the action upon the method returning
    /// `None` is to use a fallback encoding (e.g. `WINDOWS_1252`). In such a
    /// case, the `for_label()` method should be used instead in order to avoid
    /// unsafe fallback for labels that `for_label()` maps to `Some(REPLACEMENT)`.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn for_label_no_replacement(label: &[u8]) -> Option<&'static Encoding> {
        match Encoding::for_label(label) {
            None => None,
            Some(encoding) => {
                if encoding == REPLACEMENT {
                    None
                } else {
                    Some(encoding)
                }
            }
        }
    }

    /// Performs non-incremental BOM sniffing.
    ///
    /// The argument must either be a buffer representing the entire input
    /// stream (non-streaming case) or a buffer representing at least the first
    /// three bytes of the input stream (streaming case).
    ///
    /// Returns `Some((UTF_8, 3))`, `Some((UTF_16LE, 2))` or
    /// `Some((UTF_16BE, 2))` if the argument starts with the UTF-8, UTF-16LE
    /// or UTF-16BE BOM or `None` otherwise.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn for_bom(buffer: &[u8]) -> Option<(&'static Encoding, usize)> {
        if buffer.starts_with(b"\xEF\xBB\xBF") {
            Some((UTF_8, 3))
        } else if buffer.starts_with(b"\xFF\xFE") {
            Some((UTF_16LE, 2))
        } else if buffer.starts_with(b"\xFE\xFF") {
            Some((UTF_16BE, 2))
        } else {
            None
        }
    }

    /// Returns the name of this encoding.
    ///
    /// This name is appropriate to return as-is from the DOM
    /// `document.characterSet` property.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn name(&'static self) -> &'static str {
        self.name
    }

    /// Checks whether the _output encoding_ of this encoding can encode every
    /// `char`. (Only true if the output encoding is UTF-8.)
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn can_encode_everything(&'static self) -> bool {
        self.output_encoding() == UTF_8
    }

    /// Checks whether the bytes 0x00...0x7F map exclusively to the characters
    /// U+0000...U+007F and vice versa.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn is_ascii_compatible(&'static self) -> bool {
        !(self == REPLACEMENT || self == UTF_16BE || self == UTF_16LE || self == ISO_2022_JP)
    }

    /// Checks whether this encoding maps one byte to one Basic Multilingual
    /// Plane code point (i.e. byte length equals decoded UTF-16 length) and
    /// vice versa (for mappable characters).
    ///
    /// `true` iff this encoding is on the list of [Legacy single-byte
    /// encodings](https://encoding.spec.whatwg.org/#legacy-single-byte-encodings)
    /// in the spec or x-user-defined.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn is_single_byte(&'static self) -> bool {
        self.variant.is_single_byte()
    }

    /// Checks whether the bytes 0x00...0x7F map mostly to the characters
    /// U+0000...U+007F and vice versa.
    #[inline]
    fn is_potentially_borrowable(&'static self) -> bool {
        !(self == REPLACEMENT || self == UTF_16BE || self == UTF_16LE)
    }

    /// Returns the _output encoding_ of this encoding. This is UTF-8 for
    /// UTF-16BE, UTF-16LE and replacement and the encoding itself otherwise.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn output_encoding(&'static self) -> &'static Encoding {
        if self == REPLACEMENT || self == UTF_16BE || self == UTF_16LE {
            UTF_8
        } else {
            self
        }
    }

    /// Decode complete input to `Cow<'a, str>` _with BOM sniffing_ and with
    /// malformed sequences replaced with the REPLACEMENT CHARACTER when the
    /// entire input is available as a single buffer (i.e. the end of the
    /// buffer marks the end of the stream).
    ///
    /// This method implements the (non-streaming version of) the
    /// [_decode_](https://encoding.spec.whatwg.org/#decode) spec concept.
    ///
    /// The second item in the returned tuple is the encoding that was actually
    /// used (which may differ from this encoding thanks to BOM sniffing).
    ///
    /// The third item in the returned tuple indicates whether there were
    /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER).
    ///
    /// _Note:_ It is wrong to use this when the input buffer represents only
    /// a segment of the input instead of the whole input. Use `new_decoder()`
    /// when decoding segmented input.
    ///
    /// This method performs a one or two heap allocations for the backing
    /// buffer of the `String` when unable to borrow. (One allocation if not
    /// errors and potentially another one in the presence of errors.) The
    /// first allocation assumes jemalloc and may not be optimal with
    /// allocators that do not use power-of-two buckets. A borrow is performed
    /// if decoding UTF-8 and the input is valid UTF-8, if decoding an
    /// ASCII-compatible encoding and the input is ASCII-only, or when decoding
    /// ISO-2022-JP and the input is entirely in the ASCII state without state
    /// transitions.
    ///
    /// # Panics
    ///
    /// If the size calculation for a heap-allocated backing buffer overflows
    /// `usize`.
    ///
    /// Available to Rust only.
    #[inline]
    pub fn decode<'a>(&'static self, bytes: &'a [u8]) -> (Cow<'a, str>, &'static Encoding, bool) {
        let (encoding, without_bom) = match Encoding::for_bom(bytes) {
            Some((encoding, bom_length)) => (encoding, &bytes[bom_length..]),
            None => (self, bytes),
        };
        let (cow, had_errors) = encoding.decode_without_bom_handling(without_bom);
        (cow, encoding, had_errors)
    }

    /// Decode complete input to `Cow<'a, str>` _with BOM removal_ and with
    /// malformed sequences replaced with the REPLACEMENT CHARACTER when the
    /// entire input is available as a single buffer (i.e. the end of the
    /// buffer marks the end of the stream).
    ///
    /// When invoked on `UTF_8`, this method implements the (non-streaming
    /// version of) the
    /// [_UTF-8 decode_](https://encoding.spec.whatwg.org/#utf-8-decode) spec
    /// concept.
    ///
    /// The second item in the returned pair indicates whether there were
    /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER).
    ///
    /// _Note:_ It is wrong to use this when the input buffer represents only
    /// a segment of the input instead of the whole input. Use
    /// `new_decoder_with_bom_removal()` when decoding segmented input.
    ///
    /// This method performs a one or two heap allocations for the backing
    /// buffer of the `String` when unable to borrow. (One allocation if not
    /// errors and potentially another one in the presence of errors.) The
    /// first allocation assumes jemalloc and may not be optimal with
    /// allocators that do not use power-of-two buckets. A borrow is performed
    /// if decoding UTF-8 and the input is valid UTF-8, if decoding an
    /// ASCII-compatible encoding and the input is ASCII-only, or when decoding
    /// ISO-2022-JP and the input is entirely in the ASCII state without state
    /// transitions.
    ///
    /// # Panics
    ///
    /// If the size calculation for a heap-allocated backing buffer overflows
    /// `usize`.
    ///
    /// Available to Rust only.
    #[inline]
    pub fn decode_with_bom_removal<'a>(&'static self, bytes: &'a [u8]) -> (Cow<'a, str>, bool) {
        let without_bom = if self == UTF_8 && bytes.starts_with(b"\xEF\xBB\xBF") {
            &bytes[3..]
        } else if (self == UTF_16LE && bytes.starts_with(b"\xFF\xFE"))
            || (self == UTF_16BE && bytes.starts_with(b"\xFE\xFF"))
        {
            &bytes[2..]
        } else {
            bytes
        };
        self.decode_without_bom_handling(without_bom)
    }

    /// Decode complete input to `Cow<'a, str>` _without BOM handling_ and
    /// with malformed sequences replaced with the REPLACEMENT CHARACTER when
    /// the entire input is available as a single buffer (i.e. the end of the
    /// buffer marks the end of the stream).
    ///
    /// When invoked on `UTF_8`, this method implements the (non-streaming
    /// version of) the
    /// [_UTF-8 decode without BOM_](https://encoding.spec.whatwg.org/#utf-8-decode-without-bom)
    /// spec concept.
    ///
    /// The second item in the returned pair indicates whether there were
    /// malformed sequences (that were replaced with the REPLACEMENT CHARACTER).
    ///
    /// _Note:_ It is wrong to use this when the input buffer represents only
    /// a segment of the input instead of the whole input. Use
    /// `new_decoder_without_bom_handling()` when decoding segmented input.
    ///
    /// This method performs a one or two heap allocations for the backing
    /// buffer of the `String` when unable to borrow. (One allocation if not
    /// errors and potentially another one in the presence of errors.) The
    /// first allocation assumes jemalloc and may not be optimal with
    /// allocators that do not use power-of-two buckets. A borrow is performed
    /// if decoding UTF-8 and the input is valid UTF-8, if decoding an
    /// ASCII-compatible encoding and the input is ASCII-only, or when decoding
    /// ISO-2022-JP and the input is entirely in the ASCII state without state
    /// transitions.
    ///
    /// # Panics
    ///
    /// If the size calculation for a heap-allocated backing buffer overflows
    /// `usize`.
    ///
    /// Available to Rust only.
    pub fn decode_without_bom_handling<'a>(&'static self, bytes: &'a [u8]) -> (Cow<'a, str>, bool) {
        let (mut decoder, mut string, mut total_read) = if self.is_potentially_borrowable() {
            let valid_up_to = if self == UTF_8 {
                utf8_valid_up_to(bytes)
            } else if self == ISO_2022_JP {
                iso_2022_jp_ascii_valid_up_to(bytes)
            } else {
                ascii_valid_up_to(bytes)
            };
            if valid_up_to == bytes.len() {
                let str: &str = unsafe { std::str::from_utf8_unchecked(bytes) };
                return (Cow::Borrowed(str), false);
            }
            let decoder = self.new_decoder_without_bom_handling();

            let rounded_without_replacement = checked_next_power_of_two(checked_add(
                valid_up_to,
                decoder.max_utf8_buffer_length_without_replacement(bytes.len() - valid_up_to),
            ));
            let with_replacement = checked_add(
                valid_up_to,
                decoder.max_utf8_buffer_length(bytes.len() - valid_up_to),
            );
            let mut string = String::with_capacity(
                checked_min(rounded_without_replacement, with_replacement).unwrap(),
            );
            unsafe {
                let vec = string.as_mut_vec();
                vec.set_len(valid_up_to);
                std::ptr::copy_nonoverlapping(bytes.as_ptr(), vec.as_mut_ptr(), valid_up_to);
            }
            (decoder, string, valid_up_to)
        } else {
            let decoder = self.new_decoder_without_bom_handling();
            let rounded_without_replacement = checked_next_power_of_two(
                decoder.max_utf8_buffer_length_without_replacement(bytes.len()),
            );
            let with_replacement = decoder.max_utf8_buffer_length(bytes.len());
            let string = String::with_capacity(
                checked_min(rounded_without_replacement, with_replacement).unwrap(),
            );
            (decoder, string, 0)
        };

        let mut total_had_errors = false;
        loop {
            let (result, read, had_errors) =
                decoder.decode_to_string(&bytes[total_read..], &mut string, true);
            total_read += read;
            total_had_errors |= had_errors;
            match result {
                CoderResult::InputEmpty => {
                    debug_assert_eq!(total_read, bytes.len());
                    return (Cow::Owned(string), total_had_errors);
                }
                CoderResult::OutputFull => {
                    // Allocate for the worst case. That is, we should come
                    // here at most once per invocation of this method.
                    let needed = decoder.max_utf8_buffer_length(bytes.len() - total_read);
                    string.reserve(needed.unwrap());
                }
            }
        }
    }

    /// Decode complete input to `Cow<'a, str>` _without BOM handling_ and
    /// _with malformed sequences treated as fatal_ when the entire input is
    /// available as a single buffer (i.e. the end of the buffer marks the end
    /// of the stream).
    ///
    /// When invoked on `UTF_8`, this method implements the (non-streaming
    /// version of) the
    /// [_UTF-8 decode without BOM or fail_](https://encoding.spec.whatwg.org/#utf-8-decode-without-bom-or-fail)
    /// spec concept.
    ///
    /// Returns `None` if a malformed sequence was encountered and the result
    /// of the decode as `Some(String)` otherwise.
    ///
    /// _Note:_ It is wrong to use this when the input buffer represents only
    /// a segment of the input instead of the whole input. Use
    /// `new_decoder_without_bom_handling()` when decoding segmented input.
    ///
    /// This method performs a single heap allocation for the backing
    /// buffer of the `String` when unable to borrow. A borrow is performed if
    /// decoding UTF-8 and the input is valid UTF-8, if decoding an
    /// ASCII-compatible encoding and the input is ASCII-only, or when decoding
    /// ISO-2022-JP and the input is entirely in the ASCII state without state
    /// transitions.
    ///
    /// # Panics
    ///
    /// If the size calculation for a heap-allocated backing buffer overflows
    /// `usize`.
    ///
    /// Available to Rust only.
    pub fn decode_without_bom_handling_and_without_replacement<'a>(
        &'static self,
        bytes: &'a [u8],
    ) -> Option<Cow<'a, str>> {
        if self == UTF_8 {
            let valid_up_to = utf8_valid_up_to(bytes);
            if valid_up_to == bytes.len() {
                let str: &str = unsafe { std::str::from_utf8_unchecked(bytes) };
                return Some(Cow::Borrowed(str));
            }
            return None;
        }
        let (mut decoder, mut string, input) = if self.is_potentially_borrowable() {
            let valid_up_to = if self == ISO_2022_JP {
                iso_2022_jp_ascii_valid_up_to(bytes)
            } else {
                ascii_valid_up_to(bytes)
            };
            if valid_up_to == bytes.len() {
                let str: &str = unsafe { std::str::from_utf8_unchecked(bytes) };
                return Some(Cow::Borrowed(str));
            }
            let decoder = self.new_decoder_without_bom_handling();
            let mut string = String::with_capacity(
                checked_add(
                    valid_up_to,
                    decoder.max_utf8_buffer_length_without_replacement(bytes.len() - valid_up_to),
                )
                .unwrap(),
            );
            unsafe {
                let vec = string.as_mut_vec();
                vec.set_len(valid_up_to);
                std::ptr::copy_nonoverlapping(bytes.as_ptr(), vec.as_mut_ptr(), valid_up_to);
            }
            (decoder, string, &bytes[valid_up_to..])
        } else {
            let decoder = self.new_decoder_without_bom_handling();
            let string = String::with_capacity(
                decoder
                    .max_utf8_buffer_length_without_replacement(bytes.len())
                    .unwrap(),
            );
            (decoder, string, bytes)
        };
        let (result, read) = decoder.decode_to_string_without_replacement(input, &mut string, true);
        match result {
            DecoderResult::InputEmpty => {
                debug_assert_eq!(read, input.len());
                Some(Cow::Owned(string))
            }
            DecoderResult::Malformed(_, _) => None,
            DecoderResult::OutputFull => unreachable!(),
        }
    }

    /// Encode complete input to `Cow<'a, [u8]>` with unmappable characters
    /// replaced with decimal numeric character references when the entire input
    /// is available as a single buffer (i.e. the end of the buffer marks the
    /// end of the stream).
    ///
    /// This method implements the (non-streaming version of) the
    /// [_encode_](https://encoding.spec.whatwg.org/#encode) spec concept. For
    /// the [_UTF-8 encode_](https://encoding.spec.whatwg.org/#utf-8-encode)
    /// spec concept, it is slightly more efficient to use
    /// <code><var>string</var>.as_bytes()</code> instead of invoking this
    /// method on `UTF_8`.
    ///
    /// The second item in the returned tuple is the encoding that was actually
    /// used (which may differ from this encoding thanks to some encodings
    /// having UTF-8 as their output encoding).
    ///
    /// The third item in the returned tuple indicates whether there were
    /// unmappable characters (that were replaced with HTML numeric character
    /// references).
    ///
    /// _Note:_ It is wrong to use this when the input buffer represents only
    /// a segment of the input instead of the whole input. Use `new_encoder()`
    /// when encoding segmented output.
    ///
    /// When encoding to UTF-8 or when encoding an ASCII-only input to a
    /// ASCII-compatible encoding, this method returns a borrow of the input
    /// without a heap allocation. Otherwise, this method performs a single
    /// heap allocation for the backing buffer of the `Vec<u8>` if there are no
    /// unmappable characters and potentially multiple heap allocations if
    /// there are. These allocations are tuned for jemalloc and may not be
    /// optimal when using a different allocator that doesn't use power-of-two
    /// buckets.
    ///
    /// # Panics
    ///
    /// If the size calculation for a heap-allocated backing buffer overflows
    /// `usize`.
    ///
    /// Available to Rust only.
    pub fn encode<'a>(&'static self, string: &'a str) -> (Cow<'a, [u8]>, &'static Encoding, bool) {
        let output_encoding = self.output_encoding();
        if output_encoding == UTF_8 {
            return (Cow::Borrowed(string.as_bytes()), output_encoding, false);
        }
        debug_assert!(output_encoding.is_potentially_borrowable());
        let bytes = string.as_bytes();
        let valid_up_to = if output_encoding == ISO_2022_JP {
            iso_2022_jp_ascii_valid_up_to(bytes)
        } else {
            ascii_valid_up_to(bytes)
        };
        if valid_up_to == bytes.len() {
            return (Cow::Borrowed(bytes), output_encoding, false);
        }
        let mut encoder = output_encoding.new_encoder();
        let mut vec: Vec<u8> = Vec::with_capacity(
            (checked_add(
                valid_up_to,
                encoder.max_buffer_length_from_utf8_if_no_unmappables(string.len() - valid_up_to),
            ))
            .unwrap()
            .next_power_of_two(),
        );
        unsafe {
            vec.set_len(valid_up_to);
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), vec.as_mut_ptr(), valid_up_to);
        }
        let mut total_read = valid_up_to;
        let mut total_had_errors = false;
        loop {
            let (result, read, had_errors) =
                encoder.encode_from_utf8_to_vec(&string[total_read..], &mut vec, true);
            total_read += read;
            total_had_errors |= had_errors;
            match result {
                CoderResult::InputEmpty => {
                    debug_assert_eq!(total_read, string.len());
                    return (Cow::Owned(vec), output_encoding, total_had_errors);
                }
                CoderResult::OutputFull => {
                    // reserve_exact wants to know how much more on top of current
                    // length--not current capacity.
                    let needed = encoder
                        .max_buffer_length_from_utf8_if_no_unmappables(string.len() - total_read);
                    let rounded = (checked_add(vec.capacity(), needed))
                        .unwrap()
                        .next_power_of_two();
                    let additional = rounded - vec.len();
                    vec.reserve_exact(additional);
                }
            }
        }
    }

    fn new_variant_decoder(&'static self) -> VariantDecoder {
        self.variant.new_variant_decoder()
    }

    /// Instantiates a new decoder for this encoding with BOM sniffing enabled.
    ///
    /// BOM sniffing may cause the returned decoder to morph into a decoder
    /// for UTF-8, UTF-16LE or UTF-16BE instead of this encoding.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn new_decoder(&'static self) -> Decoder {
        Decoder::new(self, self.new_variant_decoder(), BomHandling::Sniff)
    }

    /// Instantiates a new decoder for this encoding with BOM removal.
    ///
    /// If the input starts with bytes that are the BOM for this encoding,
    /// those bytes are removed. However, the decoder never morphs into a
    /// decoder for another encoding: A BOM for another encoding is treated as
    /// (potentially malformed) input to the decoding algorithm for this
    /// encoding.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn new_decoder_with_bom_removal(&'static self) -> Decoder {
        Decoder::new(self, self.new_variant_decoder(), BomHandling::Remove)
    }

    /// Instantiates a new decoder for this encoding with BOM handling disabled.
    ///
    /// If the input starts with bytes that look like a BOM, those bytes are
    /// not treated as a BOM. (Hence, the decoder never morphs into a decoder
    /// for another encoding.)
    ///
    /// _Note:_ If the caller has performed BOM sniffing on its own but has not
    /// removed the BOM, the caller should use `new_decoder_with_bom_removal()`
    /// instead of this method to cause the BOM to be removed.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn new_decoder_without_bom_handling(&'static self) -> Decoder {
        Decoder::new(self, self.new_variant_decoder(), BomHandling::Off)
    }

    /// Instantiates a new encoder for the output encoding of this encoding.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn new_encoder(&'static self) -> Encoder {
        let enc = self.output_encoding();
        enc.variant.new_encoder(enc)
    }

    /// Validates UTF-8.
    ///
    /// Returns the index of the first byte that makes the input malformed as
    /// UTF-8 or the length of the slice if the slice is entirely valid.
    ///
    /// This is currently faster than the corresponding standard library
    /// functionality. If this implementation gets upstreamed to the standard
    /// library, this method may be removed in the future.
    ///
    /// Available via the C wrapper.
    pub fn utf8_valid_up_to(bytes: &[u8]) -> usize {
        utf8_valid_up_to(bytes)
    }

    /// Validates ASCII.
    ///
    /// Returns the index of the first byte that makes the input malformed as
    /// ASCII or the length of the slice if the slice is entirely valid.
    ///
    /// Available via the C wrapper.
    pub fn ascii_valid_up_to(bytes: &[u8]) -> usize {
        ascii_valid_up_to(bytes)
    }

    /// Validates ISO-2022-JP ASCII-state data.
    ///
    /// Returns the index of the first byte that makes the input not
    /// representable in the ASCII state of ISO-2022-JP or the length of the
    /// slice if the slice is entirely representable in the ASCII state of
    /// ISO-2022-JP.
    ///
    /// Available via the C wrapper.
    pub fn iso_2022_jp_ascii_valid_up_to(bytes: &[u8]) -> usize {
        iso_2022_jp_ascii_valid_up_to(bytes)
    }
}

impl PartialEq for Encoding {
    #[inline]
    fn eq(&self, other: &Encoding) -> bool {
        (self as *const Encoding) == (other as *const Encoding)
    }
}

impl Eq for Encoding {}

impl Hash for Encoding {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        (self as *const Encoding).hash(state);
    }
}

impl std::fmt::Debug for Encoding {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Encoding {{ {} }}", self.name)
    }
}

#[cfg(feature = "serde")]
impl Serialize for Encoding {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.name)
    }
}

#[cfg(feature = "serde")]
struct EncodingVisitor;

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for EncodingVisitor {
    type Value = &'static Encoding;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a valid encoding label")
    }

    fn visit_str<E>(self, value: &str) -> Result<&'static Encoding, E>
    where
        E: serde::de::Error,
    {
        if let Some(enc) = Encoding::for_label(value.as_bytes()) {
            Ok(enc)
        } else {
            Err(E::custom(format!("invalid encoding label: {}", value)))
        }
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for &'static Encoding {
    fn deserialize<D>(deserializer: D) -> Result<&'static Encoding, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(EncodingVisitor)
    }
}

/// Tracks the life cycle of a decoder from BOM sniffing to conversion to end.
#[derive(PartialEq, Debug, Copy, Clone)]
enum DecoderLifeCycle {
    /// The decoder has seen no input yet.
    AtStart,
    /// The decoder has seen no input yet but expects UTF-8.
    AtUtf8Start,
    /// The decoder has seen no input yet but expects UTF-16BE.
    AtUtf16BeStart,
    /// The decoder has seen no input yet but expects UTF-16LE.
    AtUtf16LeStart,
    /// The decoder has seen EF.
    SeenUtf8First,
    /// The decoder has seen EF, BB.
    SeenUtf8Second,
    /// The decoder has seen FE.
    SeenUtf16BeFirst,
    /// The decoder has seen FF.
    SeenUtf16LeFirst,
    /// Saw EF, BB but not BF, there was a buffer boundary after BB and the
    /// underlying decoder reported EF as an error, so we need to remember to
    /// push BB before the next buffer.
    ConvertingWithPendingBB,
    /// No longer looking for a BOM and EOF not yet seen.
    Converting,
    /// EOF has been seen.
    Finished,
}

/// Communicate the BOM handling mode.
#[derive(Debug, Copy, Clone)]
enum BomHandling {
    /// Don't handle the BOM
    Off,
    /// Sniff for UTF-8, UTF-16BE or UTF-16LE BOM
    Sniff,
    /// Remove the BOM only if it's the BOM for this encoding
    Remove,
}

/// Result of a (potentially partial) decode or encode operation with
/// replacement.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
pub enum CoderResult {
    /// The input was exhausted.
    ///
    /// If this result was returned from a call where `last` was `true`, the
    /// conversion process has completed. Otherwise, the caller should call a
    /// decode or encode method again with more input.
    InputEmpty,

    /// The converter cannot produce another unit of output, because the output
    /// buffer does not have enough space left.
    ///
    /// The caller must provide more output space upon the next call and re-push
    /// the remaining input to the converter.
    OutputFull,
}

/// Result of a (potentially partial) decode operation without replacement.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
pub enum DecoderResult {
    /// The input was exhausted.
    ///
    /// If this result was returned from a call where `last` was `true`, the
    /// decoding process has completed. Otherwise, the caller should call a
    /// decode method again with more input.
    InputEmpty,

    /// The decoder cannot produce another unit of output, because the output
    /// buffer does not have enough space left.
    ///
    /// The caller must provide more output space upon the next call and re-push
    /// the remaining input to the decoder.
    OutputFull,

    /// The decoder encountered a malformed byte sequence.
    ///
    /// The caller must either treat this as a fatal error or must append one
    /// REPLACEMENT CHARACTER (U+FFFD) to the output and then re-push the
    /// the remaining input to the decoder.
    ///
    /// The first wrapped integer indicates the length of the malformed byte
    /// sequence. The second wrapped integer indicates the number of bytes
    /// that were consumed after the malformed sequence. If the second
    /// integer is zero, the last byte that was consumed is the last byte of
    /// the malformed sequence. Note that the malformed bytes may have been part
    /// of an earlier input buffer.
    ///
    /// The first wrapped integer can have values 1, 2, 3 or 4. The second
    /// wrapped integer can have values 0, 1, 2 or 3. The worst-case sum
    /// of the two is 6, which happens with ISO-2022-JP.
    Malformed(u8, u8), // u8 instead of usize to avoid useless bloat
}

/// A converter that decodes a byte stream into Unicode according to a
/// character encoding in a streaming (incremental) manner.
///
/// The various `decode_*` methods take an input buffer (`src`) and an output
/// buffer `dst` both of which are caller-allocated. There are variants for
/// both UTF-8 and UTF-16 output buffers.
///
/// A `decode_*` method decodes bytes from `src` into Unicode characters stored
/// into `dst` until one of the following three things happens:
///
/// 1. A malformed byte sequence is encountered (`*_without_replacement`
///    variants only).
///
/// 2. The output buffer has been filled so near capacity that the decoder
///    cannot be sure that processing an additional byte of input wouldn't
///    cause so much output that the output buffer would overflow.
///
/// 3. All the input bytes have been processed.
///
/// The `decode_*` method then returns tuple of a status indicating which one
/// of the three reasons to return happened, how many input bytes were read,
/// how many output code units (`u8` when decoding into UTF-8 and `u16`
/// when decoding to UTF-16) were written (except when decoding into `String`,
/// whose length change indicates this), and in the case of the
/// variants performing replacement, a boolean indicating whether an error was
/// replaced with the REPLACEMENT CHARACTER during the call.
///
/// The number of bytes "written" is what's logically written. Garbage may be
/// written in the output buffer beyond the point logically written to.
/// Therefore, if you wish to decode into an `&mut str`, you should use the
/// methods that take an `&mut str` argument instead of the ones that take an
/// `&mut [u8]` argument. The former take care of overwriting the trailing
/// garbage to ensure the UTF-8 validity of the `&mut str` as a whole, but the
/// latter don't.
///
/// In the case of the `*_without_replacement` variants, the status is a
/// [`DecoderResult`][1] enumeration (possibilities `Malformed`, `OutputFull` and
/// `InputEmpty` corresponding to the three cases listed above).
///
/// In the case of methods whose name does not end with
/// `*_without_replacement`, malformed sequences are automatically replaced
/// with the REPLACEMENT CHARACTER and errors do not cause the methods to
/// return early.
///
/// When decoding to UTF-8, the output buffer must have at least 4 bytes of
/// space. When decoding to UTF-16, the output buffer must have at least two
/// UTF-16 code units (`u16`) of space.
///
/// When decoding to UTF-8 without replacement, the methods are guaranteed
/// not to return indicating that more output space is needed if the length
/// of the output buffer is at least the length returned by
/// [`max_utf8_buffer_length_without_replacement()`][2]. When decoding to UTF-8
/// with replacement, the length of the output buffer that guarantees the
/// methods not to return indicating that more output space is needed is given
/// by [`max_utf8_buffer_length()`][3]. When decoding to UTF-16 with
/// or without replacement, the length of the output buffer that guarantees
/// the methods not to return indicating that more output space is needed is
/// given by [`max_utf16_buffer_length()`][4].
///
/// The output written into `dst` is guaranteed to be valid UTF-8 or UTF-16,
/// and the output after each `decode_*` call is guaranteed to consist of
/// complete characters. (I.e. the code unit sequence for the last character is
/// guaranteed not to be split across output buffers.)
///
/// The boolean argument `last` indicates that the end of the stream is reached
/// when all the bytes in `src` have been consumed.
///
/// A `Decoder` object can be used to incrementally decode a byte stream.
///
/// During the processing of a single stream, the caller must call `decode_*`
/// zero or more times with `last` set to `false` and then call `decode_*` at
/// least once with `last` set to `true`. If `decode_*` returns `InputEmpty`,
/// the processing of the stream has ended. Otherwise, the caller must call
/// `decode_*` again with `last` set to `true` (or treat a `Malformed` result as
///  a fatal error).
///
/// Once the stream has ended, the `Decoder` object must not be used anymore.
/// That is, you need to create another one to process another stream.
///
/// When the decoder returns `OutputFull` or the decoder returns `Malformed` and
/// the caller does not wish to treat it as a fatal error, the input buffer
/// `src` may not have been completely consumed. In that case, the caller must
/// pass the unconsumed contents of `src` to `decode_*` again upon the next
/// call.
///
/// [1]: enum.DecoderResult.html
/// [2]: #method.max_utf8_buffer_length_without_replacement
/// [3]: #method.max_utf8_buffer_length
/// [4]: #method.max_utf16_buffer_length
///
/// # Infinite loops
///
/// When converting with a fixed-size output buffer whose size is too small to
/// accommodate one character or (when applicable) one numeric character
/// reference of output, an infinite loop ensues. When converting with a
/// fixed-size output buffer, it generally makes sense to make the buffer
/// fairly large (e.g. couple of kilobytes).
pub struct Decoder {
    encoding: &'static Encoding,
    variant: VariantDecoder,
    life_cycle: DecoderLifeCycle,
}

impl Decoder {
    fn new(enc: &'static Encoding, decoder: VariantDecoder, sniffing: BomHandling) -> Decoder {
        Decoder {
            encoding: enc,
            variant: decoder,
            life_cycle: match sniffing {
                BomHandling::Off => DecoderLifeCycle::Converting,
                BomHandling::Sniff => DecoderLifeCycle::AtStart,
                BomHandling::Remove => {
                    if enc == UTF_8 {
                        DecoderLifeCycle::AtUtf8Start
                    } else if enc == UTF_16BE {
                        DecoderLifeCycle::AtUtf16BeStart
                    } else if enc == UTF_16LE {
                        DecoderLifeCycle::AtUtf16LeStart
                    } else {
                        DecoderLifeCycle::Converting
                    }
                }
            },
        }
    }

    /// The `Encoding` this `Decoder` is for.
    ///
    /// BOM sniffing can change the return value of this method during the life
    /// of the decoder.
    ///
    /// Available via the C wrapper.
    #[inline]
    pub fn encoding(&self) -> &'static Encoding {
        self.encoding
    }

    /// Query the worst-case UTF-8 output size _with replacement_.
    ///
    /// Returns the size of the output buffer in UTF-8 code units (`u8`)
    /// that will not overflow given the current state of the decoder and
    /// `byte_length` number of additional input bytes when decoding with
    /// errors handled by outputting a REPLACEMENT CHARACTER for each malformed
    /// sequence or `None` if `usize` would overflow.
    ///
    /// Available via the C wrapper.
    pub fn max_utf8_buffer_length(&self, byte_length: usize) -> Option<usize> {
        // Need to consider a) the decoder morphing due to the BOM and b) a partial
        // BOM getting pushed to the underlying decoder.
        match self.life_cycle {
            DecoderLifeCycle::Converting
            | DecoderLifeCycle::AtUtf8Start
            | DecoderLifeCycle::AtUtf16LeStart
            | DecoderLifeCycle::AtUtf16BeStart => {
                return self.variant.max_utf8_buffer_length(byte_length);
            }
            DecoderLifeCycle::AtStart => {
                if let Some(utf8_bom) = checked_add(3, byte_length.checked_mul(3)) {
                    if let Some(utf16_bom) = checked_add(
                        1,
                        checked_mul(3, checked_div(byte_length.checked_add(1), 2)),
                    ) {
                        let utf_bom = std::cmp::max(utf8_bom, utf16_bom);
                        let encoding = self.encoding();
                        if encoding == UTF_8 || encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf_bom);
                        } else if let Some(non_bom) =
                            self.variant.max_utf8_buffer_length(byte_length)
                        {
                            return Some(std::cmp::max(utf_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::SeenUtf8First | DecoderLifeCycle::SeenUtf8Second => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf8_bom) = checked_add(3, sum.checked_mul(3)) {
                        if self.encoding() == UTF_8 {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf8_bom);
                        } else if let Some(non_bom) = self.variant.max_utf8_buffer_length(sum) {
                            return Some(std::cmp::max(utf8_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::ConvertingWithPendingBB => {
                if let Some(sum) = byte_length.checked_add(2) {
                    return self.variant.max_utf8_buffer_length(sum);
                }
            }
            DecoderLifeCycle::SeenUtf16LeFirst | DecoderLifeCycle::SeenUtf16BeFirst => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf16_bom) =
                        checked_add(1, checked_mul(3, checked_div(sum.checked_add(1), 2)))
                    {
                        let encoding = self.encoding();
                        if encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf16_bom);
                        } else if let Some(non_bom) = self.variant.max_utf8_buffer_length(sum) {
                            return Some(std::cmp::max(utf16_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::Finished => panic!("Must not use a decoder that has finished."),
        }
        None
    }

    /// Query the worst-case UTF-8 output size _without replacement_.
    ///
    /// Returns the size of the output buffer in UTF-8 code units (`u8`)
    /// that will not overflow given the current state of the decoder and
    /// `byte_length` number of additional input bytes when decoding without
    /// replacement error handling or `None` if `usize` would overflow.
    ///
    /// Note that this value may be too small for the `_with_replacement` case.
    /// Use `max_utf8_buffer_length()` for that case.
    ///
    /// Available via the C wrapper.
    pub fn max_utf8_buffer_length_without_replacement(&self, byte_length: usize) -> Option<usize> {
        // Need to consider a) the decoder morphing due to the BOM and b) a partial
        // BOM getting pushed to the underlying decoder.
        match self.life_cycle {
            DecoderLifeCycle::Converting
            | DecoderLifeCycle::AtUtf8Start
            | DecoderLifeCycle::AtUtf16LeStart
            | DecoderLifeCycle::AtUtf16BeStart => {
                return self
                    .variant
                    .max_utf8_buffer_length_without_replacement(byte_length);
            }
            DecoderLifeCycle::AtStart => {
                if let Some(utf8_bom) = byte_length.checked_add(3) {
                    if let Some(utf16_bom) = checked_add(
                        1,
                        checked_mul(3, checked_div(byte_length.checked_add(1), 2)),
                    ) {
                        let utf_bom = std::cmp::max(utf8_bom, utf16_bom);
                        let encoding = self.encoding();
                        if encoding == UTF_8 || encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf_bom);
                        } else if let Some(non_bom) = self
                            .variant
                            .max_utf8_buffer_length_without_replacement(byte_length)
                        {
                            return Some(std::cmp::max(utf_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::SeenUtf8First | DecoderLifeCycle::SeenUtf8Second => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf8_bom) = sum.checked_add(3) {
                        if self.encoding() == UTF_8 {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf8_bom);
                        } else if let Some(non_bom) =
                            self.variant.max_utf8_buffer_length_without_replacement(sum)
                        {
                            return Some(std::cmp::max(utf8_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::ConvertingWithPendingBB => {
                if let Some(sum) = byte_length.checked_add(2) {
                    return self.variant.max_utf8_buffer_length_without_replacement(sum);
                }
            }
            DecoderLifeCycle::SeenUtf16LeFirst | DecoderLifeCycle::SeenUtf16BeFirst => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf16_bom) =
                        checked_add(1, checked_mul(3, checked_div(sum.checked_add(1), 2)))
                    {
                        let encoding = self.encoding();
                        if encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf16_bom);
                        } else if let Some(non_bom) =
                            self.variant.max_utf8_buffer_length_without_replacement(sum)
                        {
                            return Some(std::cmp::max(utf16_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::Finished => panic!("Must not use a decoder that has finished."),
        }
        None
    }

    /// Incrementally decode a byte stream into UTF-8 with malformed sequences
    /// replaced with the REPLACEMENT CHARACTER.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn decode_to_utf8(
        &mut self,
        src: &[u8],
        dst: &mut [u8],
        last: bool,
    ) -> (CoderResult, usize, usize, bool) {
        let mut had_errors = false;
        let mut total_read = 0usize;
        let mut total_written = 0usize;
        loop {
            let (result, read, written) = self.decode_to_utf8_without_replacement(
                &src[total_read..],
                &mut dst[total_written..],
                last,
            );
            total_read += read;
            total_written += written;
            match result {
                DecoderResult::InputEmpty => {
                    return (
                        CoderResult::InputEmpty,
                        total_read,
                        total_written,
                        had_errors,
                    );
                }
                DecoderResult::OutputFull => {
                    return (
                        CoderResult::OutputFull,
                        total_read,
                        total_written,
                        had_errors,
                    );
                }
                DecoderResult::Malformed(_, _) => {
                    had_errors = true;
                    // There should always be space for the U+FFFD, because
                    // otherwise we'd have gotten OutputFull already.
                    // XXX: is the above comment actually true for UTF-8 itself?
                    // TODO: Consider having fewer bound checks here.
                    dst[total_written] = 0xEFu8;
                    total_written += 1;
                    dst[total_written] = 0xBFu8;
                    total_written += 1;
                    dst[total_written] = 0xBDu8;
                    total_written += 1;
                }
            }
        }
    }

    /// Incrementally decode a byte stream into UTF-8 with malformed sequences
    /// replaced with the REPLACEMENT CHARACTER with type system signaling
    /// of UTF-8 validity.
    ///
    /// This methods calls `decode_to_utf8` and then zeroes
    /// out up to three bytes that aren't logically part of the write in order
    /// to retain the UTF-8 validity even for the unwritten part of the buffer.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn decode_to_str(
        &mut self,
        src: &[u8],
        dst: &mut str,
        last: bool,
    ) -> (CoderResult, usize, usize, bool) {
        let bytes: &mut [u8] = unsafe { dst.as_bytes_mut() };
        let (result, read, written, replaced) = self.decode_to_utf8(src, bytes, last);
        let len = bytes.len();
        let mut trail = written;
        // Non-UTF-8 ASCII-compatible decoders may write up to `MAX_STRIDE_SIZE`
        // bytes of trailing garbage. No need to optimize non-ASCII-compatible
        // encodings to avoid overwriting here.
        if self.encoding != UTF_8 {
            let max = std::cmp::min(len, trail + ascii::MAX_STRIDE_SIZE);
            while trail < max {
                bytes[trail] = 0;
                trail += 1;
            }
        }
        while trail < len && ((bytes[trail] & 0xC0) == 0x80) {
            bytes[trail] = 0;
            trail += 1;
        }
        (result, read, written, replaced)
    }

    /// Incrementally decode a byte stream into UTF-8 with malformed sequences
    /// replaced with the REPLACEMENT CHARACTER using a `String` receiver.
    ///
    /// Like the others, this method follows the logic that the output buffer is
    /// caller-allocated. This method treats the capacity of the `String` as
    /// the output limit. That is, this method guarantees not to cause a
    /// reallocation of the backing buffer of `String`.
    ///
    /// The return value is a tuple that contains the `DecoderResult`, the
    /// number of bytes read and a boolean indicating whether replacements
    /// were done. The number of bytes written is signaled via the length of
    /// the `String` changing.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn decode_to_string(
        &mut self,
        src: &[u8],
        dst: &mut String,
        last: bool,
    ) -> (CoderResult, usize, bool) {
        unsafe {
            let vec = dst.as_mut_vec();
            let old_len = vec.len();
            let capacity = vec.capacity();
            vec.set_len(capacity);
            let (result, read, written, replaced) =
                self.decode_to_utf8(src, &mut vec[old_len..], last);
            vec.set_len(old_len + written);
            (result, read, replaced)
        }
    }

    public_decode_function!(/// Incrementally decode a byte stream into UTF-8
                            /// _without replacement_.
                            ///
                            /// See the documentation of the struct for
                            /// documentation for `decode_*` methods
                            /// collectively.
                            ///
                            /// Available via the C wrapper.
                            ,
                            decode_to_utf8_without_replacement,
                            decode_to_utf8_raw,
                            decode_to_utf8_checking_end,
                            decode_to_utf8_after_one_potential_bom_byte,
                            decode_to_utf8_after_two_potential_bom_bytes,
                            decode_to_utf8_checking_end_with_offset,
                            u8);

    /// Incrementally decode a byte stream into UTF-8 with type system signaling
    /// of UTF-8 validity.
    ///
    /// This methods calls `decode_to_utf8` and then zeroes out up to three
    /// bytes that aren't logically part of the write in order to retain the
    /// UTF-8 validity even for the unwritten part of the buffer.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn decode_to_str_without_replacement(
        &mut self,
        src: &[u8],
        dst: &mut str,
        last: bool,
    ) -> (DecoderResult, usize, usize) {
        let bytes: &mut [u8] = unsafe { dst.as_bytes_mut() };
        let (result, read, written) = self.decode_to_utf8_without_replacement(src, bytes, last);
        let len = bytes.len();
        let mut trail = written;
        // Non-UTF-8 ASCII-compatible decoders may write up to `MAX_STRIDE_SIZE`
        // bytes of trailing garbage. No need to optimize non-ASCII-compatible
        // encodings to avoid overwriting here.
        if self.encoding != UTF_8 {
            let max = std::cmp::min(len, trail + ascii::MAX_STRIDE_SIZE);
            while trail < max {
                bytes[trail] = 0;
                trail += 1;
            }
        }
        while trail < len && ((bytes[trail] & 0xC0) == 0x80) {
            bytes[trail] = 0;
            trail += 1;
        }
        (result, read, written)
    }

    /// Incrementally decode a byte stream into UTF-8 using a `String` receiver.
    ///
    /// Like the others, this method follows the logic that the output buffer is
    /// caller-allocated. This method treats the capacity of the `String` as
    /// the output limit. That is, this method guarantees not to cause a
    /// reallocation of the backing buffer of `String`.
    ///
    /// The return value is a pair that contains the `DecoderResult` and the
    /// number of bytes read. The number of bytes written is signaled via
    /// the length of the `String` changing.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn decode_to_string_without_replacement(
        &mut self,
        src: &[u8],
        dst: &mut String,
        last: bool,
    ) -> (DecoderResult, usize) {
        unsafe {
            let vec = dst.as_mut_vec();
            let old_len = vec.len();
            let capacity = vec.capacity();
            vec.set_len(capacity);
            let (result, read, written) =
                self.decode_to_utf8_without_replacement(src, &mut vec[old_len..], last);
            vec.set_len(old_len + written);
            (result, read)
        }
    }

    /// Query the worst-case UTF-16 output size (with or without replacement).
    ///
    /// Returns the size of the output buffer in UTF-16 code units (`u16`)
    /// that will not overflow given the current state of the decoder and
    /// `byte_length` number of additional input bytes or `None` if `usize`
    /// would overflow.
    ///
    /// Since the REPLACEMENT CHARACTER fits into one UTF-16 code unit, the
    /// return value of this method applies also in the
    /// `_without_replacement` case.
    ///
    /// Available via the C wrapper.
    pub fn max_utf16_buffer_length(&self, byte_length: usize) -> Option<usize> {
        // Need to consider a) the decoder morphing due to the BOM and b) a partial
        // BOM getting pushed to the underlying decoder.
        match self.life_cycle {
            DecoderLifeCycle::Converting
            | DecoderLifeCycle::AtUtf8Start
            | DecoderLifeCycle::AtUtf16LeStart
            | DecoderLifeCycle::AtUtf16BeStart => {
                return self.variant.max_utf16_buffer_length(byte_length);
            }
            DecoderLifeCycle::AtStart => {
                if let Some(utf8_bom) = byte_length.checked_add(1) {
                    if let Some(utf16_bom) =
                        checked_add(1, checked_div(byte_length.checked_add(1), 2))
                    {
                        let utf_bom = std::cmp::max(utf8_bom, utf16_bom);
                        let encoding = self.encoding();
                        if encoding == UTF_8 || encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf_bom);
                        } else if let Some(non_bom) =
                            self.variant.max_utf16_buffer_length(byte_length)
                        {
                            return Some(std::cmp::max(utf_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::SeenUtf8First | DecoderLifeCycle::SeenUtf8Second => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf8_bom) = sum.checked_add(1) {
                        if self.encoding() == UTF_8 {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf8_bom);
                        } else if let Some(non_bom) = self.variant.max_utf16_buffer_length(sum) {
                            return Some(std::cmp::max(utf8_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::ConvertingWithPendingBB => {
                if let Some(sum) = byte_length.checked_add(2) {
                    return self.variant.max_utf16_buffer_length(sum);
                }
            }
            DecoderLifeCycle::SeenUtf16LeFirst | DecoderLifeCycle::SeenUtf16BeFirst => {
                // Add two bytes even when only one byte has been seen,
                // because the one byte can become a lead byte in multibyte
                // decoders, but only after the decoder has been queried
                // for max length, so the decoder's own logic for adding
                // one for a pending lead cannot work.
                if let Some(sum) = byte_length.checked_add(2) {
                    if let Some(utf16_bom) = checked_add(1, checked_div(sum.checked_add(1), 2)) {
                        let encoding = self.encoding();
                        if encoding == UTF_16LE || encoding == UTF_16BE {
                            // No need to consider the internal state of the underlying decoder,
                            // because it is at start, because no data has reached it yet.
                            return Some(utf16_bom);
                        } else if let Some(non_bom) = self.variant.max_utf16_buffer_length(sum) {
                            return Some(std::cmp::max(utf16_bom, non_bom));
                        }
                    }
                }
            }
            DecoderLifeCycle::Finished => panic!("Must not use a decoder that has finished."),
        }
        None
    }

    /// Incrementally decode a byte stream into UTF-16 with malformed sequences
    /// replaced with the REPLACEMENT CHARACTER.
    ///
    /// See the documentation of the struct for documentation for `decode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn decode_to_utf16(
        &mut self,
        src: &[u8],
        dst: &mut [u16],
        last: bool,
    ) -> (CoderResult, usize, usize, bool) {
        let mut had_errors = false;
        let mut total_read = 0usize;
        let mut total_written = 0usize;
        loop {
            let (result, read, written) = self.decode_to_utf16_without_replacement(
                &src[total_read..],
                &mut dst[total_written..],
                last,
            );
            total_read += read;
            total_written += written;
            match result {
                DecoderResult::InputEmpty => {
                    return (
                        CoderResult::InputEmpty,
                        total_read,
                        total_written,
                        had_errors,
                    );
                }
                DecoderResult::OutputFull => {
                    return (
                        CoderResult::OutputFull,
                        total_read,
                        total_written,
                        had_errors,
                    );
                }
                DecoderResult::Malformed(_, _) => {
                    had_errors = true;
                    // There should always be space for the U+FFFD, because
                    // otherwise we'd have gotten OutputFull already.
                    dst[total_written] = 0xFFFD;
                    total_written += 1;
                }
            }
        }
    }

    public_decode_function!(/// Incrementally decode a byte stream into UTF-16
                            /// _without replacement_.
                            ///
                            /// See the documentation of the struct for
                            /// documentation for `decode_*` methods
                            /// collectively.
                            ///
                            /// Available via the C wrapper.
                            ,
                            decode_to_utf16_without_replacement,
                            decode_to_utf16_raw,
                            decode_to_utf16_checking_end,
                            decode_to_utf16_after_one_potential_bom_byte,
                            decode_to_utf16_after_two_potential_bom_bytes,
                            decode_to_utf16_checking_end_with_offset,
                            u16);

    /// Checks for compatibility with storing Unicode scalar values as unsigned
    /// bytes taking into account the state of the decoder.
    ///
    /// Returns `None` if the decoder is not in a neutral state, including waiting
    /// for the BOM, or if the encoding is never Latin1-byte-compatible.
    ///
    /// Otherwise returns the index of the first byte whose unsigned value doesn't
    /// directly correspond to the decoded Unicode scalar value, or the length
    /// of the input if all bytes in the input decode directly to scalar values
    /// corresponding to the unsigned byte values.
    ///
    /// Does not change the state of the decoder.
    ///
    /// Do not use this unless you are supporting SpiderMonkey/V8-style string
    /// storage optimizations.
    ///
    /// Available via the C wrapper.
    pub fn latin1_byte_compatible_up_to(&self, bytes: &[u8]) -> Option<usize> {
        match self.life_cycle {
            DecoderLifeCycle::Converting => {
                return self.variant.latin1_byte_compatible_up_to(bytes);
            }
            DecoderLifeCycle::Finished => panic!("Must not use a decoder that has finished."),
            _ => None,
        }
    }
}

/// Result of a (potentially partial) encode operation without replacement.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
pub enum EncoderResult {
    /// The input was exhausted.
    ///
    /// If this result was returned from a call where `last` was `true`, the
    /// decoding process has completed. Otherwise, the caller should call a
    /// decode method again with more input.
    InputEmpty,

    /// The encoder cannot produce another unit of output, because the output
    /// buffer does not have enough space left.
    ///
    /// The caller must provide more output space upon the next call and re-push
    /// the remaining input to the decoder.
    OutputFull,

    /// The encoder encountered an unmappable character.
    ///
    /// The caller must either treat this as a fatal error or must append
    /// a placeholder to the output and then re-push the remaining input to the
    /// encoder.
    Unmappable(char),
}

impl EncoderResult {
    fn unmappable_from_bmp(bmp: u16) -> EncoderResult {
        EncoderResult::Unmappable(::std::char::from_u32(u32::from(bmp)).unwrap())
    }
}

/// A converter that encodes a Unicode stream into bytes according to a
/// character encoding in a streaming (incremental) manner.
///
/// The various `encode_*` methods take an input buffer (`src`) and an output
/// buffer `dst` both of which are caller-allocated. There are variants for
/// both UTF-8 and UTF-16 input buffers.
///
/// An `encode_*` method encode characters from `src` into bytes characters
/// stored into `dst` until one of the following three things happens:
///
/// 1. An unmappable character is encountered (`*_without_replacement` variants
///    only).
///
/// 2. The output buffer has been filled so near capacity that the decoder
///    cannot be sure that processing an additional character of input wouldn't
///    cause so much output that the output buffer would overflow.
///
/// 3. All the input characters have been processed.
///
/// The `encode_*` method then returns tuple of a status indicating which one
/// of the three reasons to return happened, how many input code units (`u8`
/// when encoding from UTF-8 and `u16` when encoding from UTF-16) were read,
/// how many output bytes were written (except when encoding into `Vec<u8>`,
/// whose length change indicates this), and in the case of the variants that
/// perform replacement, a boolean indicating whether an unmappable
/// character was replaced with a numeric character reference during the call.
///
/// The number of bytes "written" is what's logically written. Garbage may be
/// written in the output buffer beyond the point logically written to.
///
/// In the case of the methods whose name ends with
/// `*_without_replacement`, the status is an [`EncoderResult`][1] enumeration
/// (possibilities `Unmappable`, `OutputFull` and `InputEmpty` corresponding to
/// the three cases listed above).
///
/// In the case of methods whose name does not end with
/// `*_without_replacement`, unmappable characters are automatically replaced
/// with the corresponding numeric character references and unmappable
/// characters do not cause the methods to return early.
///
/// When encoding from UTF-8 without replacement, the methods are guaranteed
/// not to return indicating that more output space is needed if the length
/// of the output buffer is at least the length returned by
/// [`max_buffer_length_from_utf8_without_replacement()`][2]. When encoding from
/// UTF-8 with replacement, the length of the output buffer that guarantees the
/// methods not to return indicating that more output space is needed in the
/// absence of unmappable characters is given by
/// [`max_buffer_length_from_utf8_if_no_unmappables()`][3]. When encoding from
/// UTF-16 without replacement, the methods are guaranteed not to return
/// indicating that more output space is needed if the length of the output
/// buffer is at least the length returned by
/// [`max_buffer_length_from_utf16_without_replacement()`][4]. When encoding
/// from UTF-16 with replacement, the the length of the output buffer that
/// guarantees the methods not to return indicating that more output space is
/// needed in the absence of unmappable characters is given by
/// [`max_buffer_length_from_utf16_if_no_unmappables()`][5].
/// When encoding with replacement, applications are not expected to size the
/// buffer for the worst case ahead of time but to resize the buffer if there
/// are unmappable characters. This is why max length queries are only available
/// for the case where there are no unmappable characters.
///
/// When encoding from UTF-8, each `src` buffer _must_ be valid UTF-8. (When
/// calling from Rust, the type system takes care of this.) When encoding from
/// UTF-16, unpaired surrogates in the input are treated as U+FFFD REPLACEMENT
/// CHARACTERS. Therefore, in order for astral characters not to turn into a
/// pair of REPLACEMENT CHARACTERS, the caller must ensure that surrogate pairs
/// are not split across input buffer boundaries.
///
/// After an `encode_*` call returns, the output produced so far, taken as a
/// whole from the start of the stream, is guaranteed to consist of a valid
/// byte sequence in the target encoding. (I.e. the code unit sequence for a
/// character is guaranteed not to be split across output buffers. However, due
/// to the stateful nature of ISO-2022-JP, the stream needs to be considered
/// from the start for it to be valid. For other encodings, the validity holds
/// on a per-output buffer basis.)
///
/// The boolean argument `last` indicates that the end of the stream is reached
/// when all the characters in `src` have been consumed. This argument is needed
/// for ISO-2022-JP and is ignored for other encodings.
///
/// An `Encoder` object can be used to incrementally encode a byte stream.
///
/// During the processing of a single stream, the caller must call `encode_*`
/// zero or more times with `last` set to `false` and then call `encode_*` at
/// least once with `last` set to `true`. If `encode_*` returns `InputEmpty`,
/// the processing of the stream has ended. Otherwise, the caller must call
/// `encode_*` again with `last` set to `true` (or treat an `Unmappable` result
/// as a fatal error).
///
/// Once the stream has ended, the `Encoder` object must not be used anymore.
/// That is, you need to create another one to process another stream.
///
/// When the encoder returns `OutputFull` or the encoder returns `Unmappable`
/// and the caller does not wish to treat it as a fatal error, the input buffer
/// `src` may not have been completely consumed. In that case, the caller must
/// pass the unconsumed contents of `src` to `encode_*` again upon the next
/// call.
///
/// [1]: enum.EncoderResult.html
/// [2]: #method.max_buffer_length_from_utf8_without_replacement
/// [3]: #method.max_buffer_length_from_utf8_if_no_unmappables
/// [4]: #method.max_buffer_length_from_utf16_without_replacement
/// [5]: #method.max_buffer_length_from_utf16_if_no_unmappables
///
/// # Infinite loops
///
/// When converting with a fixed-size output buffer whose size is too small to
/// accommodate one character of output, an infinite loop ensues. When
/// converting with a fixed-size output buffer, it generally makes sense to
/// make the buffer fairly large (e.g. couple of kilobytes).
pub struct Encoder {
    encoding: &'static Encoding,
    variant: VariantEncoder,
}

impl Encoder {
    fn new(enc: &'static Encoding, encoder: VariantEncoder) -> Encoder {
        Encoder {
            encoding: enc,
            variant: encoder,
        }
    }

    /// The `Encoding` this `Encoder` is for.
    #[inline]
    pub fn encoding(&self) -> &'static Encoding {
        self.encoding
    }

    /// Returns `true` if this is an ISO-2022-JP encoder that's not in the
    /// ASCII state and `false` otherwise.
    #[inline]
    pub fn has_pending_state(&self) -> bool {
        self.variant.has_pending_state()
    }

    /// Query the worst-case output size when encoding from UTF-8 with
    /// replacement.
    ///
    /// Returns the size of the output buffer in bytes that will not overflow
    /// given the current state of the encoder and `byte_length` number of
    /// additional input code units if there are no unmappable characters in
    /// the input or `None` if `usize` would overflow.
    ///
    /// Available via the C wrapper.
    pub fn max_buffer_length_from_utf8_if_no_unmappables(
        &self,
        byte_length: usize,
    ) -> Option<usize> {
        checked_add(
            if self.encoding().can_encode_everything() {
                0
            } else {
                NCR_EXTRA
            },
            self.max_buffer_length_from_utf8_without_replacement(byte_length),
        )
    }

    /// Query the worst-case output size when encoding from UTF-8 without
    /// replacement.
    ///
    /// Returns the size of the output buffer in bytes that will not overflow
    /// given the current state of the encoder and `byte_length` number of
    /// additional input code units or `None` if `usize` would overflow.
    ///
    /// Available via the C wrapper.
    pub fn max_buffer_length_from_utf8_without_replacement(
        &self,
        byte_length: usize,
    ) -> Option<usize> {
        self.variant
            .max_buffer_length_from_utf8_without_replacement(byte_length)
    }

    /// Incrementally encode into byte stream from UTF-8 with unmappable
    /// characters replaced with HTML (decimal) numeric character references.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn encode_from_utf8(
        &mut self,
        src: &str,
        dst: &mut [u8],
        last: bool,
    ) -> (CoderResult, usize, usize, bool) {
        let dst_len = dst.len();
        let effective_dst_len = if self.encoding().can_encode_everything() {
            dst_len
        } else {
            if dst_len < NCR_EXTRA {
                if src.is_empty() && !(last && self.has_pending_state()) {
                    return (CoderResult::InputEmpty, 0, 0, false);
                }
                return (CoderResult::OutputFull, 0, 0, false);
            }
            dst_len - NCR_EXTRA
        };
        let mut had_unmappables = false;
        let mut total_read = 0usize;
        let mut total_written = 0usize;
        loop {
            let (result, read, written) = self.encode_from_utf8_without_replacement(
                &src[total_read..],
                &mut dst[total_written..effective_dst_len],
                last,
            );
            total_read += read;
            total_written += written;
            match result {
                EncoderResult::InputEmpty => {
                    return (
                        CoderResult::InputEmpty,
                        total_read,
                        total_written,
                        had_unmappables,
                    );
                }
                EncoderResult::OutputFull => {
                    return (
                        CoderResult::OutputFull,
                        total_read,
                        total_written,
                        had_unmappables,
                    );
                }
                EncoderResult::Unmappable(unmappable) => {
                    had_unmappables = true;
                    debug_assert!(dst.len() - total_written >= NCR_EXTRA);
                    debug_assert_ne!(self.encoding(), UTF_16BE);
                    debug_assert_ne!(self.encoding(), UTF_16LE);
                    // Additionally, Iso2022JpEncoder is responsible for
                    // transitioning to ASCII when returning with Unmappable.
                    total_written += write_ncr(unmappable, &mut dst[total_written..]);
                    if total_written >= effective_dst_len {
                        if total_read == src.len() && !(last && self.has_pending_state()) {
                            return (
                                CoderResult::InputEmpty,
                                total_read,
                                total_written,
                                had_unmappables,
                            );
                        }
                        return (
                            CoderResult::OutputFull,
                            total_read,
                            total_written,
                            had_unmappables,
                        );
                    }
                }
            }
        }
    }

    /// Incrementally encode into byte stream from UTF-8 with unmappable
    /// characters replaced with HTML (decimal) numeric character references.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn encode_from_utf8_to_vec(
        &mut self,
        src: &str,
        dst: &mut Vec<u8>,
        last: bool,
    ) -> (CoderResult, usize, bool) {
        unsafe {
            let old_len = dst.len();
            let capacity = dst.capacity();
            dst.set_len(capacity);
            let (result, read, written, replaced) =
                self.encode_from_utf8(src, &mut dst[old_len..], last);
            dst.set_len(old_len + written);
            (result, read, replaced)
        }
    }

    /// Incrementally encode into byte stream from UTF-8 _without replacement_.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn encode_from_utf8_without_replacement(
        &mut self,
        src: &str,
        dst: &mut [u8],
        last: bool,
    ) -> (EncoderResult, usize, usize) {
        self.variant.encode_from_utf8_raw(src, dst, last)
    }

    /// Incrementally encode into byte stream from UTF-8 _without replacement_.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available to Rust only.
    pub fn encode_from_utf8_to_vec_without_replacement(
        &mut self,
        src: &str,
        dst: &mut Vec<u8>,
        last: bool,
    ) -> (EncoderResult, usize) {
        unsafe {
            let old_len = dst.len();
            let capacity = dst.capacity();
            dst.set_len(capacity);
            let (result, read, written) =
                self.encode_from_utf8_without_replacement(src, &mut dst[old_len..], last);
            dst.set_len(old_len + written);
            (result, read)
        }
    }

    /// Query the worst-case output size when encoding from UTF-16 with
    /// replacement.
    ///
    /// Returns the size of the output buffer in bytes that will not overflow
    /// given the current state of the encoder and `u16_length` number of
    /// additional input code units if there are no unmappable characters in
    /// the input or `None` if `usize` would overflow.
    ///
    /// Available via the C wrapper.
    pub fn max_buffer_length_from_utf16_if_no_unmappables(
        &self,
        u16_length: usize,
    ) -> Option<usize> {
        checked_add(
            if self.encoding().can_encode_everything() {
                0
            } else {
                NCR_EXTRA
            },
            self.max_buffer_length_from_utf16_without_replacement(u16_length),
        )
    }

    /// Query the worst-case output size when encoding from UTF-16 without
    /// replacement.
    ///
    /// Returns the size of the output buffer in bytes that will not overflow
    /// given the current state of the encoder and `u16_length` number of
    /// additional input code units or `None` if `usize` would overflow.
    ///
    /// Available via the C wrapper.
    pub fn max_buffer_length_from_utf16_without_replacement(
        &self,
        u16_length: usize,
    ) -> Option<usize> {
        self.variant
            .max_buffer_length_from_utf16_without_replacement(u16_length)
    }

    /// Incrementally encode into byte stream from UTF-16 with unmappable
    /// characters replaced with HTML (decimal) numeric character references.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn encode_from_utf16(
        &mut self,
        src: &[u16],
        dst: &mut [u8],
        last: bool,
    ) -> (CoderResult, usize, usize, bool) {
        let dst_len = dst.len();
        let effective_dst_len = if self.encoding().can_encode_everything() {
            dst_len
        } else {
            if dst_len < NCR_EXTRA {
                if src.is_empty() && !(last && self.has_pending_state()) {
                    return (CoderResult::InputEmpty, 0, 0, false);
                }
                return (CoderResult::OutputFull, 0, 0, false);
            }
            dst_len - NCR_EXTRA
        };
        let mut had_unmappables = false;
        let mut total_read = 0usize;
        let mut total_written = 0usize;
        loop {
            let (result, read, written) = self.encode_from_utf16_without_replacement(
                &src[total_read..],
                &mut dst[total_written..effective_dst_len],
                last,
            );
            total_read += read;
            total_written += written;
            match result {
                EncoderResult::InputEmpty => {
                    return (
                        CoderResult::InputEmpty,
                        total_read,
                        total_written,
                        had_unmappables,
                    );
                }
                EncoderResult::OutputFull => {
                    return (
                        CoderResult::OutputFull,
                        total_read,
                        total_written,
                        had_unmappables,
                    );
                }
                EncoderResult::Unmappable(unmappable) => {
                    had_unmappables = true;
                    debug_assert!(dst.len() - total_written >= NCR_EXTRA);
                    // There are no UTF-16 encoders and even if there were,
                    // they'd never have unmappables.
                    debug_assert_ne!(self.encoding(), UTF_16BE);
                    debug_assert_ne!(self.encoding(), UTF_16LE);
                    // Additionally, Iso2022JpEncoder is responsible for
                    // transitioning to ASCII when returning with Unmappable
                    // from the jis0208 state. That is, when we encode
                    // ISO-2022-JP and come here, the encoder is in either the
                    // ASCII or the Roman state. We are allowed to generate any
                    // printable ASCII excluding \ and ~.
                    total_written += write_ncr(unmappable, &mut dst[total_written..]);
                    if total_written >= effective_dst_len {
                        if total_read == src.len() && !(last && self.has_pending_state()) {
                            return (
                                CoderResult::InputEmpty,
                                total_read,
                                total_written,
                                had_unmappables,
                            );
                        }
                        return (
                            CoderResult::OutputFull,
                            total_read,
                            total_written,
                            had_unmappables,
                        );
                    }
                }
            }
        }
    }

    /// Incrementally encode into byte stream from UTF-16 _without replacement_.
    ///
    /// See the documentation of the struct for documentation for `encode_*`
    /// methods collectively.
    ///
    /// Available via the C wrapper.
    pub fn encode_from_utf16_without_replacement(
        &mut self,
        src: &[u16],
        dst: &mut [u8],
        last: bool,
    ) -> (EncoderResult, usize, usize) {
        self.variant.encode_from_utf16_raw(src, dst, last)
    }
}

/// Format an unmappable as NCR without heap allocation.
fn write_ncr(unmappable: char, dst: &mut [u8]) -> usize {
    // len is the number of decimal digits needed to represent unmappable plus
    // 3 (the length of "&#" and ";").
    let mut number = unmappable as u32;
    let len = if number >= 1_000_000u32 {
        10usize
    } else if number >= 100_000u32 {
        9usize
    } else if number >= 10_000u32 {
        8usize
    } else if number >= 1_000u32 {
        7usize
    } else if number >= 100u32 {
        6usize
    } else {
        // Review the outcome of https://github.com/whatwg/encoding/issues/15
        // to see if this case is possible
        5usize
    };
    debug_assert!(number >= 10u32);
    debug_assert!(len <= dst.len());
    let mut pos = len - 1;
    dst[pos] = b';';
    pos -= 1;
    loop {
        let rightmost = number % 10;
        dst[pos] = rightmost as u8 + b'0';
        pos -= 1;
        if number < 10 {
            break;
        }
        number /= 10;
    }
    dst[1] = b'#';
    dst[0] = b'&';
    len
}

#[inline(always)]
fn in_range16(i: u16, start: u16, end: u16) -> bool {
    i.wrapping_sub(start) < (end - start)
}

#[inline(always)]
fn in_range32(i: u32, start: u32, end: u32) -> bool {
    i.wrapping_sub(start) < (end - start)
}

#[inline(always)]
fn in_inclusive_range8(i: u8, start: u8, end: u8) -> bool {
    i.wrapping_sub(start) <= (end - start)
}

#[inline(always)]
fn in_inclusive_range16(i: u16, start: u16, end: u16) -> bool {
    i.wrapping_sub(start) <= (end - start)
}

#[inline(always)]
fn in_inclusive_range32(i: u32, start: u32, end: u32) -> bool {
    i.wrapping_sub(start) <= (end - start)
}

#[inline(always)]
fn in_inclusive_range(i: usize, start: usize, end: usize) -> bool {
    i.wrapping_sub(start) <= (end - start)
}

#[inline(always)]
fn checked_add(num: usize, opt: Option<usize>) -> Option<usize> {
    if let Some(n) = opt {
        n.checked_add(num)
    } else {
        None
    }
}

#[inline(always)]
fn checked_add_opt(one: Option<usize>, other: Option<usize>) -> Option<usize> {
    if let Some(n) = one {
        checked_add(n, other)
    } else {
        None
    }
}

#[inline(always)]
fn checked_mul(num: usize, opt: Option<usize>) -> Option<usize> {
    if let Some(n) = opt {
        n.checked_mul(num)
    } else {
        None
    }
}

#[inline(always)]
fn checked_div(opt: Option<usize>, num: usize) -> Option<usize> {
    if let Some(n) = opt {
        n.checked_div(num)
    } else {
        None
    }
}

#[inline(always)]
fn checked_next_power_of_two(opt: Option<usize>) -> Option<usize> {
    opt.map(|n| n.next_power_of_two())
}

#[inline(always)]
fn checked_min(one: Option<usize>, other: Option<usize>) -> Option<usize> {
    if let Some(a) = one {
        if let Some(b) = other {
            Some(::std::cmp::min(a, b))
        } else {
            Some(a)
        }
    } else {
        other
    }
}

// ############## TESTS ###############

#[cfg(all(test, feature = "serde"))]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Demo {
    num: u32,
    name: String,
    enc: &'static Encoding,
}

#[cfg(test)]
mod test_labels_names;

#[cfg(test)]
mod tests {
    use super::*;
    use std::borrow::Cow;

    fn sniff_to_utf16(
        initial_encoding: &'static Encoding,
        expected_encoding: &'static Encoding,
        bytes: &[u8],
        expect: &[u16],
        breaks: &[usize],
    ) {
        let mut decoder = initial_encoding.new_decoder();

        let mut dest: Vec<u16> =
            Vec::with_capacity(decoder.max_utf16_buffer_length(bytes.len()).unwrap());
        let capacity = dest.capacity();
        dest.resize(capacity, 0u16);

        let mut total_written = 0usize;
        let mut start = 0usize;
        for br in breaks {
            let (result, read, written, _) =
                decoder.decode_to_utf16(&bytes[start..*br], &mut dest[total_written..], false);
            total_written += written;
            assert_eq!(read, *br - start);
            match result {
                CoderResult::InputEmpty => {}
                CoderResult::OutputFull => {
                    unreachable!();
                }
            }
            start = *br;
        }
        let (result, read, written, _) =
            decoder.decode_to_utf16(&bytes[start..], &mut dest[total_written..], true);
        total_written += written;
        match result {
            CoderResult::InputEmpty => {}
            CoderResult::OutputFull => {
                unreachable!();
            }
        }
        assert_eq!(read, bytes.len() - start);
        assert_eq!(total_written, expect.len());
        assert_eq!(&dest[..total_written], expect);
        assert_eq!(decoder.encoding(), expected_encoding);
    }

    // Any copyright to the test code below this comment is dedicated to the
    // Public Domain. http://creativecommons.org/publicdomain/zero/1.0/

    #[test]
    fn test_bom_sniffing() {
        // ASCII
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[],
        );
        // UTF-8
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[1],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[2],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[3],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[4],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[2, 3],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[1, 2],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[1, 3],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            UTF_8,
            b"\xEF\xBB\xBF\x61\x62",
            &[0x0061u16, 0x0062u16],
            &[1, 2, 3, 4],
        );
        sniff_to_utf16(WINDOWS_1252, UTF_8, b"\xEF\xBB\xBF", &[], &[]);
        // Not UTF-8
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\xBB\x61\x62",
            &[0x00EFu16, 0x00BBu16, 0x0061u16, 0x0062u16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\xBB\x61\x62",
            &[0x00EFu16, 0x00BBu16, 0x0061u16, 0x0062u16],
            &[1],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\x61\x62",
            &[0x00EFu16, 0x0061u16, 0x0062u16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\x61\x62",
            &[0x00EFu16, 0x0061u16, 0x0062u16],
            &[1],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\xBB",
            &[0x00EFu16, 0x00BBu16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xEF\xBB",
            &[0x00EFu16, 0x00BBu16],
            &[1],
        );
        sniff_to_utf16(WINDOWS_1252, WINDOWS_1252, b"\xEF", &[0x00EFu16], &[]);
        // Not UTF-16
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xFE\x61\x62",
            &[0x00FEu16, 0x0061u16, 0x0062u16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xFE\x61\x62",
            &[0x00FEu16, 0x0061u16, 0x0062u16],
            &[1],
        );
        sniff_to_utf16(WINDOWS_1252, WINDOWS_1252, b"\xFE", &[0x00FEu16], &[]);
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xFF\x61\x62",
            &[0x00FFu16, 0x0061u16, 0x0062u16],
            &[],
        );
        sniff_to_utf16(
            WINDOWS_1252,
            WINDOWS_1252,
            b"\xFF\x61\x62",
            &[0x00FFu16, 0x0061u16, 0x0062u16],
            &[1],
        );
        sniff_to_utf16(WINDOWS_1252, WINDOWS_1252, b"\xFF", &[0x00FFu16], &[]);
        // UTF-16
        sniff_to_utf16(WINDOWS_1252, UTF_16BE, b"\xFE\xFF", &[], &[]);
        sniff_to_utf16(WINDOWS_1252, UTF_16BE, b"\xFE\xFF", &[], &[1]);
        sniff_to_utf16(WINDOWS_1252, UTF_16LE, b"\xFF\xFE", &[], &[]);
        sniff_to_utf16(WINDOWS_1252, UTF_16LE, b"\xFF\xFE", &[], &[1]);
    }

    #[test]
    fn test_output_encoding() {
        assert_eq!(REPLACEMENT.output_encoding(), UTF_8);
        assert_eq!(UTF_16BE.output_encoding(), UTF_8);
        assert_eq!(UTF_16LE.output_encoding(), UTF_8);
        assert_eq!(UTF_8.output_encoding(), UTF_8);
        assert_eq!(WINDOWS_1252.output_encoding(), WINDOWS_1252);
        assert_eq!(REPLACEMENT.new_encoder().encoding(), UTF_8);
        assert_eq!(UTF_16BE.new_encoder().encoding(), UTF_8);
        assert_eq!(UTF_16LE.new_encoder().encoding(), UTF_8);
        assert_eq!(UTF_8.new_encoder().encoding(), UTF_8);
        assert_eq!(WINDOWS_1252.new_encoder().encoding(), WINDOWS_1252);
    }

    #[test]
    fn test_label_resolution() {
        assert_eq!(Encoding::for_label(b"utf-8"), Some(UTF_8));
        assert_eq!(Encoding::for_label(b"UTF-8"), Some(UTF_8));
        assert_eq!(
            Encoding::for_label(b" \t \n \x0C \n utf-8 \r \n \t \x0C "),
            Some(UTF_8)
        );
        assert_eq!(Encoding::for_label(b"utf-8 _"), None);
        assert_eq!(Encoding::for_label(b"bogus"), None);
        assert_eq!(Encoding::for_label(b"bogusbogusbogusbogus"), None);
    }

    #[test]
    fn test_decode_valid_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.decode(b"abc\x80\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{00E4}");
            }
        }
        assert_eq!(encoding, WINDOWS_1257);
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_invalid_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.decode(b"abc\x80\xA1\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert_eq!(encoding, WINDOWS_1257);
        assert!(had_errors);
    }

    #[test]
    fn test_decode_ascii_only_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.decode(b"abc");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "abc");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert_eq!(encoding, WINDOWS_1257);
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_as_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.decode(b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "\u{20AC}\u{00E4}");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert_eq!(encoding, UTF_8);
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_invalid_utf8_as_windows_1257_to_cow() {
        let (cow, encoding, had_errors) =
            WINDOWS_1257.decode(b"\xEF\xBB\xBF\xE2\x82\xAC\x80\xC3\xA4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert_eq!(encoding, UTF_8);
        assert!(had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_as_utf_8_to_cow() {
        let (cow, encoding, had_errors) = UTF_8.decode(b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "\u{20AC}\u{00E4}");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert_eq!(encoding, UTF_8);
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_invalid_utf8_as_utf_8_to_cow() {
        let (cow, encoding, had_errors) = UTF_8.decode(b"\xEF\xBB\xBF\xE2\x82\xAC\x80\xC3\xA4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert_eq!(encoding, UTF_8);
        assert!(had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_as_utf_8_to_cow_with_bom_removal() {
        let (cow, had_errors) = UTF_8.decode_with_bom_removal(b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "\u{20AC}\u{00E4}");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_as_windows_1257_to_cow_with_bom_removal() {
        let (cow, had_errors) =
            WINDOWS_1257.decode_with_bom_removal(b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(
                    s,
                    "\u{013C}\u{00BB}\u{00E6}\u{0101}\u{201A}\u{00AC}\u{0106}\u{00A4}"
                );
            }
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_valid_windows_1257_to_cow_with_bom_removal() {
        let (cow, had_errors) = WINDOWS_1257.decode_with_bom_removal(b"abc\x80\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{00E4}");
            }
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_invalid_windows_1257_to_cow_with_bom_removal() {
        let (cow, had_errors) = WINDOWS_1257.decode_with_bom_removal(b"abc\x80\xA1\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert!(had_errors);
    }

    #[test]
    fn test_decode_ascii_only_windows_1257_to_cow_with_bom_removal() {
        let (cow, had_errors) = WINDOWS_1257.decode_with_bom_removal(b"abc");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "abc");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_to_cow_without_bom_handling() {
        let (cow, had_errors) =
            UTF_8.decode_without_bom_handling(b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "\u{FEFF}\u{20AC}\u{00E4}");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_invalid_utf8_to_cow_without_bom_handling() {
        let (cow, had_errors) =
            UTF_8.decode_without_bom_handling(b"\xEF\xBB\xBF\xE2\x82\xAC\x80\xC3\xA4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "\u{FEFF}\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert!(had_errors);
    }

    #[test]
    fn test_decode_valid_windows_1257_to_cow_without_bom_handling() {
        let (cow, had_errors) = WINDOWS_1257.decode_without_bom_handling(b"abc\x80\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{00E4}");
            }
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_invalid_windows_1257_to_cow_without_bom_handling() {
        let (cow, had_errors) = WINDOWS_1257.decode_without_bom_handling(b"abc\x80\xA1\xE4");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, "abc\u{20AC}\u{FFFD}\u{00E4}");
            }
        }
        assert!(had_errors);
    }

    #[test]
    fn test_decode_ascii_only_windows_1257_to_cow_without_bom_handling() {
        let (cow, had_errors) = WINDOWS_1257.decode_without_bom_handling(b"abc");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, "abc");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert!(!had_errors);
    }

    #[test]
    fn test_decode_bomful_valid_utf8_to_cow_without_bom_handling_and_without_replacement() {
        match UTF_8.decode_without_bom_handling_and_without_replacement(
            b"\xEF\xBB\xBF\xE2\x82\xAC\xC3\xA4",
        ) {
            Some(cow) => match cow {
                Cow::Borrowed(s) => {
                    assert_eq!(s, "\u{FEFF}\u{20AC}\u{00E4}");
                }
                Cow::Owned(_) => unreachable!(),
            },
            None => unreachable!(),
        }
    }

    #[test]
    fn test_decode_bomful_invalid_utf8_to_cow_without_bom_handling_and_without_replacement() {
        assert!(UTF_8
            .decode_without_bom_handling_and_without_replacement(
                b"\xEF\xBB\xBF\xE2\x82\xAC\x80\xC3\xA4"
            )
            .is_none());
    }

    #[test]
    fn test_decode_valid_windows_1257_to_cow_without_bom_handling_and_without_replacement() {
        match WINDOWS_1257.decode_without_bom_handling_and_without_replacement(b"abc\x80\xE4") {
            Some(cow) => match cow {
                Cow::Borrowed(_) => unreachable!(),
                Cow::Owned(s) => {
                    assert_eq!(s, "abc\u{20AC}\u{00E4}");
                }
            },
            None => unreachable!(),
        }
    }

    #[test]
    fn test_decode_invalid_windows_1257_to_cow_without_bom_handling_and_without_replacement() {
        assert!(WINDOWS_1257
            .decode_without_bom_handling_and_without_replacement(b"abc\x80\xA1\xE4")
            .is_none());
    }

    #[test]
    fn test_decode_ascii_only_windows_1257_to_cow_without_bom_handling_and_without_replacement() {
        match WINDOWS_1257.decode_without_bom_handling_and_without_replacement(b"abc") {
            Some(cow) => match cow {
                Cow::Borrowed(s) => {
                    assert_eq!(s, "abc");
                }
                Cow::Owned(_) => unreachable!(),
            },
            None => unreachable!(),
        }
    }

    #[test]
    fn test_encode_ascii_only_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.encode("abc");
        match cow {
            Cow::Borrowed(s) => {
                assert_eq!(s, b"abc");
            }
            Cow::Owned(_) => unreachable!(),
        }
        assert_eq!(encoding, WINDOWS_1257);
        assert!(!had_errors);
    }

    #[test]
    fn test_encode_valid_windows_1257_to_cow() {
        let (cow, encoding, had_errors) = WINDOWS_1257.encode("abc\u{20AC}\u{00E4}");
        match cow {
            Cow::Borrowed(_) => unreachable!(),
            Cow::Owned(s) => {
                assert_eq!(s, b"abc\x80\xE4");
            }
        }
        assert_eq!(encoding, WINDOWS_1257);
        assert!(!had_errors);
    }

    #[test]
    fn test_utf16_space_with_one_bom_byte() {
        let mut decoder = UTF_16LE.new_decoder();
        let mut dst = [0u16; 12];
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_utf8_space_with_one_bom_byte() {
        let mut decoder = UTF_8.new_decoder();
        let mut dst = [0u16; 12];
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_utf16_space_with_two_bom_bytes() {
        let mut decoder = UTF_16LE.new_decoder();
        let mut dst = [0u16; 12];
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xEF", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xBB", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_utf8_space_with_two_bom_bytes() {
        let mut decoder = UTF_8.new_decoder();
        let mut dst = [0u16; 12];
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xEF", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xBB", &mut dst[..needed], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let needed = decoder.max_utf16_buffer_length(1).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF", &mut dst[..needed], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_utf16_space_with_one_bom_byte_and_a_second_byte_in_same_call() {
        let mut decoder = UTF_16LE.new_decoder();
        let mut dst = [0u16; 12];
        {
            let needed = decoder.max_utf16_buffer_length(2).unwrap();
            let (result, _, _, _) = decoder.decode_to_utf16(b"\xFF\xFF", &mut dst[..needed], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_too_short_buffer_with_iso_2022_jp_ascii_from_utf8() {
        let mut dst = [0u8; 8];
        let mut encoder = ISO_2022_JP.new_encoder();
        {
            let (result, _, _, _) = encoder.encode_from_utf8("", &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf8("", &mut dst[..], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_too_short_buffer_with_iso_2022_jp_roman_from_utf8() {
        let mut dst = [0u8; 16];
        let mut encoder = ISO_2022_JP.new_encoder();
        {
            let (result, _, _, _) = encoder.encode_from_utf8("\u{A5}", &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf8("", &mut dst[..8], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf8("", &mut dst[..8], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
    }

    #[test]
    fn test_buffer_end_iso_2022_jp_from_utf8() {
        let mut dst = [0u8; 18];
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf8("\u{A5}\u{1F4A9}", &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) = encoder.encode_from_utf8("\u{A5}\u{1F4A9}", &mut dst[..], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) = encoder.encode_from_utf8("\u{1F4A9}", &mut dst[..13], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) = encoder.encode_from_utf8("\u{1F4A9}", &mut dst[..13], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_too_short_buffer_with_iso_2022_jp_ascii_from_utf16() {
        let mut dst = [0u8; 8];
        let mut encoder = ISO_2022_JP.new_encoder();
        {
            let (result, _, _, _) = encoder.encode_from_utf16(&[0u16; 0], &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf16(&[0u16; 0], &mut dst[..], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_too_short_buffer_with_iso_2022_jp_roman_from_utf16() {
        let mut dst = [0u8; 16];
        let mut encoder = ISO_2022_JP.new_encoder();
        {
            let (result, _, _, _) = encoder.encode_from_utf16(&[0xA5u16], &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf16(&[0u16; 0], &mut dst[..8], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let (result, _, _, _) = encoder.encode_from_utf16(&[0u16; 0], &mut dst[..8], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
    }

    #[test]
    fn test_buffer_end_iso_2022_jp_from_utf16() {
        let mut dst = [0u8; 18];
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf16(&[0xA5u16, 0xD83Du16, 0xDCA9u16], &mut dst[..], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf16(&[0xA5u16, 0xD83Du16, 0xDCA9u16], &mut dst[..], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf16(&[0xD83Du16, 0xDCA9u16], &mut dst[..13], false);
            assert_eq!(result, CoderResult::InputEmpty);
        }
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf16(&[0xD83Du16, 0xDCA9u16], &mut dst[..13], true);
            assert_eq!(result, CoderResult::InputEmpty);
        }
    }

    #[test]
    fn test_buffer_end_utf16be() {
        let mut decoder = UTF_16BE.new_decoder_without_bom_handling();
        let mut dest = [0u8; 4];

        assert_eq!(
            decoder.decode_to_utf8(&[0xD8, 0x00], &mut dest, false),
            (CoderResult::InputEmpty, 2, 0, false)
        );

        let _ = decoder.decode_to_utf8(&[0xD8, 0x00], &mut dest, true);
    }

    #[test]
    fn test_hash() {
        let mut encodings = ::std::collections::HashSet::new();
        encodings.insert(UTF_8);
        encodings.insert(ISO_2022_JP);
        assert!(encodings.contains(UTF_8));
        assert!(encodings.contains(ISO_2022_JP));
        assert!(!encodings.contains(WINDOWS_1252));
        encodings.remove(ISO_2022_JP);
        assert!(!encodings.contains(ISO_2022_JP));
    }

    #[test]
    fn test_iso_2022_jp_ncr_extra_from_utf16() {
        let mut dst = [0u8; 17];
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf16(&[0x3041u16, 0xFFFFu16], &mut dst[..], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
    }

    #[test]
    fn test_iso_2022_jp_ncr_extra_from_utf8() {
        let mut dst = [0u8; 17];
        {
            let mut encoder = ISO_2022_JP.new_encoder();
            let (result, _, _, _) =
                encoder.encode_from_utf8("\u{3041}\u{FFFF}", &mut dst[..], true);
            assert_eq!(result, CoderResult::OutputFull);
        }
    }

    #[test]
    fn test_max_length_with_bom_to_utf8() {
        let mut output = [0u8; 20];
        let mut decoder = REPLACEMENT.new_decoder();
        let input = b"\xEF\xBB\xBFA";
        {
            let needed = decoder
                .max_utf8_buffer_length_without_replacement(input.len())
                .unwrap();
            let (result, read, written) =
                decoder.decode_to_utf8_without_replacement(input, &mut output[..needed], true);
            assert_eq!(result, DecoderResult::InputEmpty);
            assert_eq!(read, input.len());
            assert_eq!(written, 1);
            assert_eq!(output[0], 0x41);
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde() {
        let demo = Demo {
            num: 42,
            name: "foo".into(),
            enc: UTF_8,
        };

        let serialized = serde_json::to_string(&demo).unwrap();

        let deserialized: Demo = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, demo);

        let bincoded = bincode::serialize(&demo).unwrap();
        let debincoded: Demo = bincode::deserialize(&bincoded[..]).unwrap();
        assert_eq!(debincoded, demo);
    }

    #[test]
    fn test_is_single_byte() {
        assert!(!BIG5.is_single_byte());
        assert!(!EUC_JP.is_single_byte());
        assert!(!EUC_KR.is_single_byte());
        assert!(!GB18030.is_single_byte());
        assert!(!GBK.is_single_byte());
        assert!(!REPLACEMENT.is_single_byte());
        assert!(!SHIFT_JIS.is_single_byte());
        assert!(!UTF_8.is_single_byte());
        assert!(!UTF_16BE.is_single_byte());
        assert!(!UTF_16LE.is_single_byte());
        assert!(!ISO_2022_JP.is_single_byte());

        assert!(IBM866.is_single_byte());
        assert!(ISO_8859_2.is_single_byte());
        assert!(ISO_8859_3.is_single_byte());
        assert!(ISO_8859_4.is_single_byte());
        assert!(ISO_8859_5.is_single_byte());
        assert!(ISO_8859_6.is_single_byte());
        assert!(ISO_8859_7.is_single_byte());
        assert!(ISO_8859_8.is_single_byte());
        assert!(ISO_8859_10.is_single_byte());
        assert!(ISO_8859_13.is_single_byte());
        assert!(ISO_8859_14.is_single_byte());
        assert!(ISO_8859_15.is_single_byte());
        assert!(ISO_8859_16.is_single_byte());
        assert!(ISO_8859_8_I.is_single_byte());
        assert!(KOI8_R.is_single_byte());
        assert!(KOI8_U.is_single_byte());
        assert!(MACINTOSH.is_single_byte());
        assert!(WINDOWS_874.is_single_byte());
        assert!(WINDOWS_1250.is_single_byte());
        assert!(WINDOWS_1251.is_single_byte());
        assert!(WINDOWS_1252.is_single_byte());
        assert!(WINDOWS_1253.is_single_byte());
        assert!(WINDOWS_1254.is_single_byte());
        assert!(WINDOWS_1255.is_single_byte());
        assert!(WINDOWS_1256.is_single_byte());
        assert!(WINDOWS_1257.is_single_byte());
        assert!(WINDOWS_1258.is_single_byte());
        assert!(X_MAC_CYRILLIC.is_single_byte());
        assert!(X_USER_DEFINED.is_single_byte());
    }

    #[test]
    fn test_latin1_byte_compatible_up_to() {
        let buffer = b"a\x81\xB6\xF6\xF0\x82\xB4";
        assert_eq!(
            BIG5.new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            EUC_JP
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            EUC_KR
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            GB18030
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            GBK.new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert!(REPLACEMENT
            .new_decoder_without_bom_handling()
            .latin1_byte_compatible_up_to(buffer)
            .is_none());
        assert_eq!(
            SHIFT_JIS
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            UTF_8
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert!(UTF_16BE
            .new_decoder_without_bom_handling()
            .latin1_byte_compatible_up_to(buffer)
            .is_none());
        assert!(UTF_16LE
            .new_decoder_without_bom_handling()
            .latin1_byte_compatible_up_to(buffer)
            .is_none());
        assert_eq!(
            ISO_2022_JP
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );

        assert_eq!(
            IBM866
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            ISO_8859_2
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_3
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_4
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_5
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_6
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_7
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_8
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            3
        );
        assert_eq!(
            ISO_8859_10
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            ISO_8859_13
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            ISO_8859_14
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            ISO_8859_15
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            6
        );
        assert_eq!(
            ISO_8859_16
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            ISO_8859_8_I
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            3
        );
        assert_eq!(
            KOI8_R
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            KOI8_U
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            MACINTOSH
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            WINDOWS_874
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            2
        );
        assert_eq!(
            WINDOWS_1250
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            WINDOWS_1251
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            WINDOWS_1252
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            5
        );
        assert_eq!(
            WINDOWS_1253
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            3
        );
        assert_eq!(
            WINDOWS_1254
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            WINDOWS_1255
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            3
        );
        assert_eq!(
            WINDOWS_1256
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            WINDOWS_1257
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            WINDOWS_1258
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            4
        );
        assert_eq!(
            X_MAC_CYRILLIC
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );
        assert_eq!(
            X_USER_DEFINED
                .new_decoder_without_bom_handling()
                .latin1_byte_compatible_up_to(buffer)
                .unwrap(),
            1
        );

        assert!(UTF_8
            .new_decoder()
            .latin1_byte_compatible_up_to(buffer)
            .is_none());

        let mut decoder = UTF_8.new_decoder();
        let mut output = [0u16; 4];
        let _ = decoder.decode_to_utf16(b"\xEF", &mut output, false);
        assert!(decoder.latin1_byte_compatible_up_to(buffer).is_none());
        let _ = decoder.decode_to_utf16(b"\xBB\xBF", &mut output, false);
        assert_eq!(decoder.latin1_byte_compatible_up_to(buffer), Some(1));
        let _ = decoder.decode_to_utf16(b"\xEF", &mut output, false);
        assert_eq!(decoder.latin1_byte_compatible_up_to(buffer), None);
    }
}