encoding_rs/mem.rs
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
// 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.
//! Functions for converting between different in-RAM representations of text
//! and for quickly checking if the Unicode Bidirectional Algorithm can be
//! avoided.
//!
//! By using slices for output, the functions here seek to enable by-register
//! (ALU register or SIMD register as available) operations in order to
//! outperform iterator-based conversions available in the Rust standard
//! library.
//!
//! _Note:_ "Latin1" in this module refers to the Unicode range from U+0000 to
//! U+00FF, inclusive, and does not refer to the windows-1252 range. This
//! in-memory encoding is sometimes used as a storage optimization of text
//! when UTF-16 indexing and length semantics are exposed.
//!
//! The FFI binding for this module are in the
//! [encoding_c_mem crate](https://github.com/hsivonen/encoding_c_mem).
#[cfg(feature = "alloc")]
use alloc::borrow::Cow;
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use super::in_inclusive_range16;
use super::in_inclusive_range32;
use super::in_inclusive_range8;
use super::in_range16;
use super::in_range32;
use super::DecoderResult;
use crate::ascii::*;
use crate::utf_8::*;
macro_rules! non_fuzz_debug_assert {
($($arg:tt)*) => (if !cfg!(fuzzing) { debug_assert!($($arg)*); })
}
cfg_if! {
if #[cfg(feature = "simd-accel")] {
use ::core::intrinsics::likely;
use ::core::intrinsics::unlikely;
} else {
#[inline(always)]
fn likely(b: bool) -> bool {
b
}
#[inline(always)]
fn unlikely(b: bool) -> bool {
b
}
}
}
/// Classification of text as Latin1 (all code points are below U+0100),
/// left-to-right with some non-Latin1 characters or as containing at least
/// some right-to-left characters.
#[must_use]
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub enum Latin1Bidi {
/// Every character is below U+0100.
Latin1 = 0,
/// There is at least one character that's U+0100 or higher, but there
/// are no right-to-left characters.
LeftToRight = 1,
/// There is at least one right-to-left character.
Bidi = 2,
}
// `as` truncates, so works on 32-bit, too.
#[allow(dead_code)]
const LATIN1_MASK: usize = 0xFF00_FF00_FF00_FF00u64 as usize;
#[allow(unused_macros)]
macro_rules! by_unit_check_alu {
($name:ident, $unit:ty, $bound:expr, $mask:ident) => {
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
#[inline(always)]
fn $name(buffer: &[$unit]) -> bool {
let mut offset = 0usize;
let mut accu = 0usize;
let unit_size = ::core::mem::size_of::<$unit>();
let len = buffer.len();
if len >= ALU_ALIGNMENT / unit_size {
// The most common reason to return `false` is for the first code
// unit to fail the test, so check that first.
if buffer[0] >= $bound {
return false;
}
let src = buffer.as_ptr();
let mut until_alignment = ((ALU_ALIGNMENT - ((src as usize) & ALU_ALIGNMENT_MASK))
& ALU_ALIGNMENT_MASK)
/ unit_size;
if until_alignment + ALU_ALIGNMENT / unit_size <= len {
if until_alignment != 0 {
accu |= buffer[offset] as usize;
offset += 1;
until_alignment -= 1;
while until_alignment != 0 {
accu |= buffer[offset] as usize;
offset += 1;
until_alignment -= 1;
}
if accu >= $bound {
return false;
}
}
let len_minus_stride = len - ALU_ALIGNMENT / unit_size;
if offset + (4 * (ALU_ALIGNMENT / unit_size)) <= len {
// Safety: the above check lets us perform 4 consecutive reads of
// length ALU_ALIGNMENT / unit_size. ALU_ALIGNMENT is the size of usize, and unit_size
// is the size of the `src` pointer, so this is equal to performing four usize reads.
//
// This invariant is upheld on all loop iterations
let len_minus_unroll = len - (4 * (ALU_ALIGNMENT / unit_size));
loop {
let unroll_accu = unsafe { *(src.add(offset) as *const usize) }
| unsafe {
*(src.add(offset + (ALU_ALIGNMENT / unit_size)) as *const usize)
}
| unsafe {
*(src.add(offset + (2 * (ALU_ALIGNMENT / unit_size)))
as *const usize)
}
| unsafe {
*(src.add(offset + (3 * (ALU_ALIGNMENT / unit_size)))
as *const usize)
};
if unroll_accu & $mask != 0 {
return false;
}
offset += 4 * (ALU_ALIGNMENT / unit_size);
// Safety: this check lets us continue to perform the 4 reads earlier
if offset > len_minus_unroll {
break;
}
}
}
while offset <= len_minus_stride {
// Safety: the above check lets us perform one usize read.
accu |= unsafe { *(src.add(offset) as *const usize) };
offset += ALU_ALIGNMENT / unit_size;
}
}
}
for &unit in &buffer[offset..] {
accu |= unit as usize;
}
accu & $mask == 0
}
};
}
#[allow(unused_macros)]
macro_rules! by_unit_check_simd {
($name:ident, $unit:ty, $splat:expr, $simd_ty:ty, $bound:expr, $func:ident) => {
#[inline(always)]
fn $name(buffer: &[$unit]) -> bool {
let mut offset = 0usize;
let mut accu = 0usize;
let unit_size = ::core::mem::size_of::<$unit>();
let len = buffer.len();
if len >= SIMD_STRIDE_SIZE / unit_size {
// The most common reason to return `false` is for the first code
// unit to fail the test, so check that first.
if buffer[0] >= $bound {
return false;
}
let src = buffer.as_ptr();
let mut until_alignment = ((SIMD_ALIGNMENT
- ((src as usize) & SIMD_ALIGNMENT_MASK))
& SIMD_ALIGNMENT_MASK)
/ unit_size;
if until_alignment + SIMD_STRIDE_SIZE / unit_size <= len {
if until_alignment != 0 {
accu |= buffer[offset] as usize;
offset += 1;
until_alignment -= 1;
while until_alignment != 0 {
accu |= buffer[offset] as usize;
offset += 1;
until_alignment -= 1;
}
if accu >= $bound {
return false;
}
}
let len_minus_stride = len - SIMD_STRIDE_SIZE / unit_size;
if offset + (4 * (SIMD_STRIDE_SIZE / unit_size)) <= len {
// Safety: the above check lets us perform 4 consecutive reads of
// length SIMD_STRIDE_SIZE / unit_size. SIMD_STRIDE_SIZE is the size of $simd_ty, and unit_size
// is the size of the `src` pointer, so this is equal to performing four $simd_ty reads.
//
// This invariant is upheld on all loop iterations
let len_minus_unroll = len - (4 * (SIMD_STRIDE_SIZE / unit_size));
loop {
let unroll_accu = unsafe { *(src.add(offset) as *const $simd_ty) }
| unsafe {
*(src.add(offset + (SIMD_STRIDE_SIZE / unit_size))
as *const $simd_ty)
}
| unsafe {
*(src.add(offset + (2 * (SIMD_STRIDE_SIZE / unit_size)))
as *const $simd_ty)
}
| unsafe {
*(src.add(offset + (3 * (SIMD_STRIDE_SIZE / unit_size)))
as *const $simd_ty)
};
if !$func(unroll_accu) {
return false;
}
offset += 4 * (SIMD_STRIDE_SIZE / unit_size);
// Safety: this check lets us continue to perform the 4 reads earlier
if offset > len_minus_unroll {
break;
}
}
}
let mut simd_accu = $splat;
while offset <= len_minus_stride {
// Safety: the above check lets us perform one $simd_ty read.
simd_accu = simd_accu | unsafe { *(src.add(offset) as *const $simd_ty) };
offset += SIMD_STRIDE_SIZE / unit_size;
}
if !$func(simd_accu) {
return false;
}
}
}
for &unit in &buffer[offset..] {
accu |= unit as usize;
}
accu < $bound
}
};
}
cfg_if! {
if #[cfg(all(feature = "simd-accel", any(target_feature = "sse2", all(target_endian = "little", target_arch = "aarch64"), all(target_endian = "little", target_feature = "neon"))))] {
use crate::simd_funcs::*;
use core::simd::u8x16;
use core::simd::u16x8;
const SIMD_ALIGNMENT: usize = 16;
const SIMD_ALIGNMENT_MASK: usize = 15;
by_unit_check_simd!(is_ascii_impl, u8, u8x16::splat(0), u8x16, 0x80, simd_is_ascii);
by_unit_check_simd!(is_basic_latin_impl, u16, u16x8::splat(0), u16x8, 0x80, simd_is_basic_latin);
by_unit_check_simd!(is_utf16_latin1_impl, u16, u16x8::splat(0), u16x8, 0x100, simd_is_latin1);
#[inline(always)]
fn utf16_valid_up_to_impl(buffer: &[u16]) -> usize {
// This function is a mess, because it simultaneously tries to do
// only aligned SIMD (perhaps misguidedly) and needs to deal with
// the last code unit in a SIMD stride being part of a valid
// surrogate pair.
let unit_size = ::core::mem::size_of::<u16>();
let src = buffer.as_ptr();
let len = buffer.len();
let mut offset = 0usize;
'outer: loop {
let until_alignment = ((SIMD_ALIGNMENT - ((unsafe { src.add(offset) } as usize) & SIMD_ALIGNMENT_MASK)) &
SIMD_ALIGNMENT_MASK) / unit_size;
if until_alignment == 0 {
if offset + SIMD_STRIDE_SIZE / unit_size > len {
break;
}
} else {
let offset_plus_until_alignment = offset + until_alignment;
let offset_plus_until_alignment_plus_one = offset_plus_until_alignment + 1;
if offset_plus_until_alignment_plus_one + SIMD_STRIDE_SIZE / unit_size > len {
break;
}
let (up_to, last_valid_low) = utf16_valid_up_to_alu(&buffer[offset..offset_plus_until_alignment_plus_one]);
if up_to < until_alignment {
return offset + up_to;
}
if last_valid_low {
offset = offset_plus_until_alignment_plus_one;
continue;
}
offset = offset_plus_until_alignment;
}
let len_minus_stride = len - SIMD_STRIDE_SIZE / unit_size;
loop {
let offset_plus_stride = offset + SIMD_STRIDE_SIZE / unit_size;
if contains_surrogates(unsafe { *(src.add(offset) as *const u16x8) }) {
if offset_plus_stride == len {
break 'outer;
}
let offset_plus_stride_plus_one = offset_plus_stride + 1;
let (up_to, last_valid_low) = utf16_valid_up_to_alu(&buffer[offset..offset_plus_stride_plus_one]);
if up_to < SIMD_STRIDE_SIZE / unit_size {
return offset + up_to;
}
if last_valid_low {
offset = offset_plus_stride_plus_one;
continue 'outer;
}
}
offset = offset_plus_stride;
if offset > len_minus_stride {
break 'outer;
}
}
}
let (up_to, _) = utf16_valid_up_to_alu(&buffer[offset..]);
offset + up_to
}
} else {
by_unit_check_alu!(is_ascii_impl, u8, 0x80, ASCII_MASK);
by_unit_check_alu!(is_basic_latin_impl, u16, 0x80, BASIC_LATIN_MASK);
by_unit_check_alu!(is_utf16_latin1_impl, u16, 0x100, LATIN1_MASK);
#[inline(always)]
fn utf16_valid_up_to_impl(buffer: &[u16]) -> usize {
let (up_to, _) = utf16_valid_up_to_alu(buffer);
up_to
}
}
}
/// The second return value is true iff the last code unit of the slice was
/// reached and turned out to be a low surrogate that is part of a valid pair.
#[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))]
#[inline(always)]
fn utf16_valid_up_to_alu(buffer: &[u16]) -> (usize, bool) {
let len = buffer.len();
if len == 0 {
return (0, false);
}
let mut offset = 0usize;
loop {
let unit = buffer[offset];
let next = offset + 1;
let unit_minus_surrogate_start = unit.wrapping_sub(0xD800);
if unit_minus_surrogate_start > (0xDFFF - 0xD800) {
// Not a surrogate
offset = next;
if offset == len {
return (offset, false);
}
continue;
}
if unit_minus_surrogate_start <= (0xDBFF - 0xD800) {
// high surrogate
if next < len {
let second = buffer[next];
let second_minus_low_surrogate_start = second.wrapping_sub(0xDC00);
if second_minus_low_surrogate_start <= (0xDFFF - 0xDC00) {
// The next code unit is a low surrogate. Advance position.
offset = next + 1;
if offset == len {
return (offset, true);
}
continue;
}
// The next code unit is not a low surrogate. Don't advance
// position and treat the high surrogate as unpaired.
// fall through
}
// Unpaired, fall through
}
// Unpaired surrogate
return (offset, false);
}
}
cfg_if! {
if #[cfg(all(feature = "simd-accel", any(target_feature = "sse2", all(target_endian = "little", target_arch = "aarch64"), all(target_endian = "little", target_feature = "neon"))))] {
#[inline(always)]
fn is_str_latin1_impl(buffer: &str) -> Option<usize> {
let mut offset = 0usize;
let bytes = buffer.as_bytes();
let len = bytes.len();
if len >= SIMD_STRIDE_SIZE {
let src = bytes.as_ptr();
let mut until_alignment = (SIMD_ALIGNMENT - ((src as usize) & SIMD_ALIGNMENT_MASK)) &
SIMD_ALIGNMENT_MASK;
if until_alignment + SIMD_STRIDE_SIZE <= len {
while until_alignment != 0 {
if bytes[offset] > 0xC3 {
return Some(offset);
}
offset += 1;
until_alignment -= 1;
}
let len_minus_stride = len - SIMD_STRIDE_SIZE;
loop {
if !simd_is_str_latin1(unsafe { *(src.add(offset) as *const u8x16) }) {
// TODO: Ensure this compiles away when inlined into `is_str_latin1()`.
while bytes[offset] & 0xC0 == 0x80 {
offset += 1;
}
return Some(offset);
}
offset += SIMD_STRIDE_SIZE;
if offset > len_minus_stride {
break;
}
}
}
}
for i in offset..len {
if bytes[i] > 0xC3 {
return Some(i);
}
}
None
}
} else {
#[inline(always)]
fn is_str_latin1_impl(buffer: &str) -> Option<usize> {
let mut bytes = buffer.as_bytes();
let mut total = 0;
loop {
if let Some((byte, offset)) = validate_ascii(bytes) {
total += offset;
if byte > 0xC3 {
return Some(total);
}
bytes = &bytes[offset + 2..];
total += 2;
} else {
return None;
}
}
}
}
}
#[inline(always)]
fn is_utf8_latin1_impl(buffer: &[u8]) -> Option<usize> {
let mut bytes = buffer;
let mut total = 0;
loop {
if let Some((byte, offset)) = validate_ascii(bytes) {
total += offset;
if in_inclusive_range8(byte, 0xC2, 0xC3) {
let next = offset + 1;
if next == bytes.len() {
return Some(total);
}
if bytes[next] & 0xC0 != 0x80 {
return Some(total);
}
bytes = &bytes[offset + 2..];
total += 2;
} else {
return Some(total);
}
} else {
return None;
}
}
}
cfg_if! {
if #[cfg(all(feature = "simd-accel", any(target_feature = "sse2", all(target_endian = "little", target_arch = "aarch64"), all(target_endian = "little", target_feature = "neon"))))] {
#[inline(always)]
fn is_utf16_bidi_impl(buffer: &[u16]) -> bool {
let mut offset = 0usize;
let len = buffer.len();
if len >= SIMD_STRIDE_SIZE / 2 {
let src = buffer.as_ptr();
let mut until_alignment = ((SIMD_ALIGNMENT - ((src as usize) & SIMD_ALIGNMENT_MASK)) &
SIMD_ALIGNMENT_MASK) / 2;
if until_alignment + (SIMD_STRIDE_SIZE / 2) <= len {
while until_alignment != 0 {
if is_utf16_code_unit_bidi(buffer[offset]) {
return true;
}
offset += 1;
until_alignment -= 1;
}
let len_minus_stride = len - (SIMD_STRIDE_SIZE / 2);
loop {
if is_u16x8_bidi(unsafe { *(src.add(offset) as *const u16x8) }) {
return true;
}
offset += SIMD_STRIDE_SIZE / 2;
if offset > len_minus_stride {
break;
}
}
}
}
for &u in &buffer[offset..] {
if is_utf16_code_unit_bidi(u) {
return true;
}
}
false
}
} else {
#[inline(always)]
fn is_utf16_bidi_impl(buffer: &[u16]) -> bool {
for &u in buffer {
if is_utf16_code_unit_bidi(u) {
return true;
}
}
false
}
}
}
cfg_if! {
if #[cfg(all(feature = "simd-accel", any(target_feature = "sse2", all(target_endian = "little", target_arch = "aarch64"), all(target_endian = "little", target_feature = "neon"))))] {
#[inline(always)]
fn check_utf16_for_latin1_and_bidi_impl(buffer: &[u16]) -> Latin1Bidi {
let mut offset = 0usize;
let len = buffer.len();
if len >= SIMD_STRIDE_SIZE / 2 {
let src = buffer.as_ptr();
let mut until_alignment = ((SIMD_ALIGNMENT - ((src as usize) & SIMD_ALIGNMENT_MASK)) &
SIMD_ALIGNMENT_MASK) / 2;
if until_alignment + (SIMD_STRIDE_SIZE / 2) <= len {
while until_alignment != 0 {
if buffer[offset] > 0xFF {
// This transition isn't optimal, since the aligment is recomputing
// but not tweaking further today.
if is_utf16_bidi_impl(&buffer[offset..]) {
return Latin1Bidi::Bidi;
}
return Latin1Bidi::LeftToRight;
}
offset += 1;
until_alignment -= 1;
}
let len_minus_stride = len - (SIMD_STRIDE_SIZE / 2);
loop {
let mut s = unsafe { *(src.add(offset) as *const u16x8) };
if !simd_is_latin1(s) {
loop {
if is_u16x8_bidi(s) {
return Latin1Bidi::Bidi;
}
offset += SIMD_STRIDE_SIZE / 2;
if offset > len_minus_stride {
for &u in &buffer[offset..] {
if is_utf16_code_unit_bidi(u) {
return Latin1Bidi::Bidi;
}
}
return Latin1Bidi::LeftToRight;
}
s = unsafe { *(src.add(offset) as *const u16x8) };
}
}
offset += SIMD_STRIDE_SIZE / 2;
if offset > len_minus_stride {
break;
}
}
}
}
let mut iter = (&buffer[offset..]).iter();
loop {
if let Some(&u) = iter.next() {
if u > 0xFF {
let mut inner_u = u;
loop {
if is_utf16_code_unit_bidi(inner_u) {
return Latin1Bidi::Bidi;
}
if let Some(&code_unit) = iter.next() {
inner_u = code_unit;
} else {
return Latin1Bidi::LeftToRight;
}
}
}
} else {
return Latin1Bidi::Latin1;
}
}
}
} else {
#[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
#[inline(always)]
fn check_utf16_for_latin1_and_bidi_impl(buffer: &[u16]) -> Latin1Bidi {
let mut offset = 0usize;
let len = buffer.len();
if len >= ALU_ALIGNMENT / 2 {
let src = buffer.as_ptr();
let mut until_alignment = ((ALU_ALIGNMENT - ((src as usize) & ALU_ALIGNMENT_MASK)) &
ALU_ALIGNMENT_MASK) / 2;
if until_alignment + ALU_ALIGNMENT / 2 <= len {
while until_alignment != 0 {
if buffer[offset] > 0xFF {
if is_utf16_bidi_impl(&buffer[offset..]) {
return Latin1Bidi::Bidi;
}
return Latin1Bidi::LeftToRight;
}
offset += 1;
until_alignment -= 1;
}
let len_minus_stride = len - ALU_ALIGNMENT / 2;
loop {
if unsafe { *(src.add(offset) as *const usize) } & LATIN1_MASK != 0 {
if is_utf16_bidi_impl(&buffer[offset..]) {
return Latin1Bidi::Bidi;
}
return Latin1Bidi::LeftToRight;
}
offset += ALU_ALIGNMENT / 2;
if offset > len_minus_stride {
break;
}
}
}
}
let mut iter = (&buffer[offset..]).iter();
loop {
if let Some(&u) = iter.next() {
if u > 0xFF {
let mut inner_u = u;
loop {
if is_utf16_code_unit_bidi(inner_u) {
return Latin1Bidi::Bidi;
}
if let Some(&code_unit) = iter.next() {
inner_u = code_unit;
} else {
return Latin1Bidi::LeftToRight;
}
}
}
} else {
return Latin1Bidi::Latin1;
}
}
}
}
}
/// Checks whether the buffer is all-ASCII.
///
/// May read the entire buffer even if it isn't all-ASCII. (I.e. the function
/// is not guaranteed to fail fast.)
pub fn is_ascii(buffer: &[u8]) -> bool {
is_ascii_impl(buffer)
}
/// Checks whether the buffer is all-Basic Latin (i.e. UTF-16 representing
/// only ASCII characters).
///
/// May read the entire buffer even if it isn't all-ASCII. (I.e. the function
/// is not guaranteed to fail fast.)
pub fn is_basic_latin(buffer: &[u16]) -> bool {
is_basic_latin_impl(buffer)
}
/// Checks whether the buffer is valid UTF-8 representing only code points
/// less than or equal to U+00FF.
///
/// Fails fast. (I.e. returns before having read the whole buffer if UTF-8
/// invalidity or code points above U+00FF are discovered.
pub fn is_utf8_latin1(buffer: &[u8]) -> bool {
is_utf8_latin1_impl(buffer).is_none()
}
/// Checks whether the buffer represents only code points less than or equal
/// to U+00FF.
///
/// Fails fast. (I.e. returns before having read the whole buffer if code
/// points above U+00FF are discovered.
pub fn is_str_latin1(buffer: &str) -> bool {
is_str_latin1_impl(buffer).is_none()
}
/// Checks whether the buffer represents only code point less than or equal
/// to U+00FF.
///
/// May read the entire buffer even if it isn't all-Latin1. (I.e. the function
/// is not guaranteed to fail fast.)
pub fn is_utf16_latin1(buffer: &[u16]) -> bool {
is_utf16_latin1_impl(buffer)
}
/// Checks whether a potentially-invalid UTF-8 buffer contains code points
/// that trigger right-to-left processing.
///
/// The check is done on a Unicode block basis without regard to assigned
/// vs. unassigned code points in the block. Hebrew presentation forms in
/// the Alphabetic Presentation Forms block are treated as if they formed
/// a block on their own (i.e. it treated as right-to-left). Additionally,
/// the four RIGHT-TO-LEFT FOO controls in General Punctuation are checked
/// for. Control characters that are technically bidi controls but do not
/// cause right-to-left behavior without the presence of right-to-left
/// characters or right-to-left controls are not checked for. As a special
/// case, U+FEFF is excluded from Arabic Presentation Forms-B.
///
/// Returns `true` if the input is invalid UTF-8 or the input contains an
/// RTL character. Returns `false` if the input is valid UTF-8 and contains
/// no RTL characters.
#[cfg_attr(feature = "cargo-clippy", allow(collapsible_if, cyclomatic_complexity))]
#[inline]
pub fn is_utf8_bidi(buffer: &[u8]) -> bool {
// As of rustc 1.25.0-nightly (73ac5d6a8 2018-01-11), this is faster
// than UTF-8 validation followed by `is_str_bidi()` for German,
// Russian and Japanese. However, this is considerably slower for Thai.
// Chances are that the compiler makes some branch predictions that are
// unfortunate for Thai. Not spending the time to manually optimize
// further at this time, since it's unclear if this variant even has
// use cases. However, this is worth revisiting once Rust gets the
// ability to annotate relative priorities of match arms.
// U+058F: D6 8F
// U+0590: D6 90
// U+08FF: E0 A3 BF
// U+0900: E0 A4 80
//
// U+200F: E2 80 8F
// U+202B: E2 80 AB
// U+202E: E2 80 AE
// U+2067: E2 81 A7
//
// U+FB1C: EF AC 9C
// U+FB1D: EF AC 9D
// U+FDFF: EF B7 BF
// U+FE00: EF B8 80
//
// U+FE6F: EF B9 AF
// U+FE70: EF B9 B0
// U+FEFE: EF BB BE
// U+FEFF: EF BB BF
//
// U+107FF: F0 90 9F BF
// U+10800: F0 90 A0 80
// U+10FFF: F0 90 BF BF
// U+11000: F0 91 80 80
//
// U+1E7FF: F0 9E 9F BF
// U+1E800: F0 9E A0 80
// U+1EFFF: F0 9E BF BF
// U+1F000: F0 9F 80 80
let mut src = buffer;
'outer: loop {
if let Some((mut byte, mut read)) = validate_ascii(src) {
// Check for the longest sequence to avoid checking twice for the
// multi-byte sequences.
if read + 4 <= src.len() {
'inner: loop {
// At this point, `byte` is not included in `read`.
match byte {
0..=0x7F => {
// ASCII: go back to SIMD.
read += 1;
src = &src[read..];
continue 'outer;
}
0xC2..=0xD5 => {
// Two-byte
let second = unsafe { *(src.get_unchecked(read + 1)) };
if !in_inclusive_range8(second, 0x80, 0xBF) {
return true;
}
read += 2;
}
0xD6 => {
// Two-byte
let second = unsafe { *(src.get_unchecked(read + 1)) };
if !in_inclusive_range8(second, 0x80, 0xBF) {
return true;
}
// XXX consider folding the above and below checks
if second > 0x8F {
return true;
}
read += 2;
}
// two-byte starting with 0xD7 and above is bidi
0xE1 | 0xE3..=0xEC | 0xEE => {
// Three-byte normal
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
})
| (third >> 6))
!= 2
{
return true;
}
read += 3;
}
0xE2 => {
// Three-byte normal, potentially bidi
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
})
| (third >> 6))
!= 2
{
return true;
}
if second == 0x80 {
if third == 0x8F || third == 0xAB || third == 0xAE {
return true;
}
} else if second == 0x81 {
if third == 0xA7 {
return true;
}
}
read += 3;
}
0xEF => {
// Three-byte normal, potentially bidi
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
})
| (third >> 6))
!= 2
{
return true;
}
if in_inclusive_range8(second, 0xAC, 0xB7) {
if second == 0xAC {
if third > 0x9C {
return true;
}
} else {
return true;
}
} else if in_inclusive_range8(second, 0xB9, 0xBB) {
if second == 0xB9 {
if third > 0xAF {
return true;
}
} else if second == 0xBB {
if third != 0xBF {
return true;
}
} else {
return true;
}
}
read += 3;
}
0xE0 => {
// Three-byte special lower bound, potentially bidi
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
})
| (third >> 6))
!= 2
{
return true;
}
// XXX can this be folded into the above validity check
if second < 0xA4 {
return true;
}
read += 3;
}
0xED => {
// Three-byte special upper bound
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
})
| (third >> 6))
!= 2
{
return true;
}
read += 3;
}
0xF1..=0xF4 => {
// Four-byte normal
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
let fourth = unsafe { *(src.get_unchecked(read + 3)) };
if (u16::from(
UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
},
) | u16::from(third >> 6)
| (u16::from(fourth & 0xC0) << 2))
!= 0x202
{
return true;
}
read += 4;
}
0xF0 => {
// Four-byte special lower bound, potentially bidi
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
let fourth = unsafe { *(src.get_unchecked(read + 3)) };
if (u16::from(
UTF8_DATA.table[usize::from(second)]
& unsafe {
*(UTF8_DATA.table.get_unchecked(byte as usize + 0x80))
},
) | u16::from(third >> 6)
| (u16::from(fourth & 0xC0) << 2))
!= 0x202
{
return true;
}
if unlikely(second == 0x90 || second == 0x9E) {
let third = src[read + 2];
if third >= 0xA0 {
return true;
}
}
read += 4;
}
_ => {
// Invalid lead or bidi-only lead
return true;
}
}
if read + 4 > src.len() {
if read == src.len() {
return false;
}
byte = src[read];
break 'inner;
}
byte = src[read];
continue 'inner;
}
}
// We can't have a complete 4-byte sequence, but we could still have
// a complete shorter sequence.
// At this point, `byte` is not included in `read`.
match byte {
0..=0x7F => {
// ASCII: go back to SIMD.
read += 1;
src = &src[read..];
continue 'outer;
}
0xC2..=0xD5 => {
// Two-byte
let new_read = read + 2;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
if !in_inclusive_range8(second, 0x80, 0xBF) {
return true;
}
read = new_read;
// We need to deal with the case where we came here with 3 bytes
// left, so we need to take a look at the last one.
src = &src[read..];
continue 'outer;
}
0xD6 => {
// Two-byte, potentially bidi
let new_read = read + 2;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
if !in_inclusive_range8(second, 0x80, 0xBF) {
return true;
}
// XXX consider folding the above and below checks
if second > 0x8F {
return true;
}
read = new_read;
// We need to deal with the case where we came here with 3 bytes
// left, so we need to take a look at the last one.
src = &src[read..];
continue 'outer;
}
// two-byte starting with 0xD7 and above is bidi
0xE1 | 0xE3..=0xEC | 0xEE => {
// Three-byte normal
let new_read = read + 3;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
| (third >> 6))
!= 2
{
return true;
}
}
0xE2 => {
// Three-byte normal, potentially bidi
let new_read = read + 3;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
| (third >> 6))
!= 2
{
return true;
}
if second == 0x80 {
if third == 0x8F || third == 0xAB || third == 0xAE {
return true;
}
} else if second == 0x81 {
if third == 0xA7 {
return true;
}
}
}
0xEF => {
// Three-byte normal, potentially bidi
let new_read = read + 3;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
| (third >> 6))
!= 2
{
return true;
}
if in_inclusive_range8(second, 0xAC, 0xB7) {
if second == 0xAC {
if third > 0x9C {
return true;
}
} else {
return true;
}
} else if in_inclusive_range8(second, 0xB9, 0xBB) {
if second == 0xB9 {
if third > 0xAF {
return true;
}
} else if second == 0xBB {
if third != 0xBF {
return true;
}
} else {
return true;
}
}
}
0xE0 => {
// Three-byte special lower bound, potentially bidi
let new_read = read + 3;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
| (third >> 6))
!= 2
{
return true;
}
// XXX can this be folded into the above validity check
if second < 0xA4 {
return true;
}
}
0xED => {
// Three-byte special upper bound
let new_read = read + 3;
if new_read > src.len() {
return true;
}
let second = unsafe { *(src.get_unchecked(read + 1)) };
let third = unsafe { *(src.get_unchecked(read + 2)) };
if ((UTF8_DATA.table[usize::from(second)]
& unsafe { *(UTF8_DATA.table.get_unchecked(byte as usize + 0x80)) })
| (third >> 6))
!= 2
{
return true;
}
}
_ => {
// Invalid lead, 4-byte lead or 2-byte bidi-only lead
return true;
}
}
return false;
} else {
return false;
}
}
}
/// Checks whether a valid UTF-8 buffer contains code points that trigger
/// right-to-left processing.
///
/// The check is done on a Unicode block basis without regard to assigned
/// vs. unassigned code points in the block. Hebrew presentation forms in
/// the Alphabetic Presentation Forms block are treated as if they formed
/// a block on their own (i.e. it treated as right-to-left). Additionally,
/// the four RIGHT-TO-LEFT FOO controls in General Punctuation are checked
/// for. Control characters that are technically bidi controls but do not
/// cause right-to-left behavior without the presence of right-to-left
/// characters or right-to-left controls are not checked for. As a special
/// case, U+FEFF is excluded from Arabic Presentation Forms-B.
#[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))]
#[inline]
pub fn is_str_bidi(buffer: &str) -> bool {
// U+058F: D6 8F
// U+0590: D6 90
// U+08FF: E0 A3 BF
// U+0900: E0 A4 80
//
// U+200F: E2 80 8F
// U+202B: E2 80 AB
// U+202E: E2 80 AE
// U+2067: E2 81 A7
//
// U+FB1C: EF AC 9C
// U+FB1D: EF AC 9D
// U+FDFF: EF B7 BF
// U+FE00: EF B8 80
//
// U+FE6F: EF B9 AF
// U+FE70: EF B9 B0
// U+FEFE: EF BB BE
// U+FEFF: EF BB BF
//
// U+107FF: F0 90 9F BF
// U+10800: F0 90 A0 80
// U+10FFF: F0 90 BF BF
// U+11000: F0 91 80 80
//
// U+1E7FF: F0 9E 9F BF
// U+1E800: F0 9E A0 80
// U+1EFFF: F0 9E BF BF
// U+1F000: F0 9F 80 80
let mut bytes = buffer.as_bytes();
'outer: loop {
// TODO: Instead of just validating ASCII using SIMD, use SIMD
// to check for non-ASCII lead bytes, too, to quickly conclude
// that the vector consist entirely of CJK and below-Hebrew
// code points.
// Unfortunately, scripts above Arabic but below CJK share
// lead bytes with RTL.
if let Some((mut byte, mut read)) = validate_ascii(bytes) {
'inner: loop {
// At this point, `byte` is not included in `read`.
if byte < 0xE0 {
if byte >= 0x80 {
// Two-byte
// Adding `unlikely` here improved throughput on
// Russian plain text by 33%!
if unlikely(byte >= 0xD6) {
if byte == 0xD6 {
let second = bytes[read + 1];
if second > 0x8F {
return true;
}
} else {
return true;
}
}
read += 2;
} else {
// ASCII: write and go back to SIMD.
read += 1;
// Intuitively, we should go back to the outer loop only
// if byte is 0x30 or above, so as to avoid trashing on
// ASCII space, comma and period in non-Latin context.
// However, the extra branch seems to cost more than it's
// worth.
bytes = &bytes[read..];
continue 'outer;
}
} else if byte < 0xF0 {
// Three-byte
if unlikely(!in_inclusive_range8(byte, 0xE3, 0xEE) && byte != 0xE1) {
let second = bytes[read + 1];
if byte == 0xE0 {
if second < 0xA4 {
return true;
}
} else if byte == 0xE2 {
let third = bytes[read + 2];
if second == 0x80 {
if third == 0x8F || third == 0xAB || third == 0xAE {
return true;
}
} else if second == 0x81 {
if third == 0xA7 {
return true;
}
}
} else {
debug_assert_eq!(byte, 0xEF);
if in_inclusive_range8(second, 0xAC, 0xB7) {
if second == 0xAC {
let third = bytes[read + 2];
if third > 0x9C {
return true;
}
} else {
return true;
}
} else if in_inclusive_range8(second, 0xB9, 0xBB) {
if second == 0xB9 {
let third = bytes[read + 2];
if third > 0xAF {
return true;
}
} else if second == 0xBB {
let third = bytes[read + 2];
if third != 0xBF {
return true;
}
} else {
return true;
}
}
}
}
read += 3;
} else {
// Four-byte
let second = bytes[read + 1];
if unlikely(byte == 0xF0 && (second == 0x90 || second == 0x9E)) {
let third = bytes[read + 2];
if third >= 0xA0 {
return true;
}
}
read += 4;
}
// The comparison is always < or == and never >, but including
// > here to let the compiler assume that < is true if this
// comparison is false.
if read >= bytes.len() {
return false;
}
byte = bytes[read];
continue 'inner;
}
} else {
return false;
}
}
}
/// Checks whether a UTF-16 buffer contains code points that trigger
/// right-to-left processing.
///
/// The check is done on a Unicode block basis without regard to assigned
/// vs. unassigned code points in the block. Hebrew presentation forms in
/// the Alphabetic Presentation Forms block are treated as if they formed
/// a block on their own (i.e. it treated as right-to-left). Additionally,
/// the four RIGHT-TO-LEFT FOO controls in General Punctuation are checked
/// for. Control characters that are technically bidi controls but do not
/// cause right-to-left behavior without the presence of right-to-left
/// characters or right-to-left controls are not checked for. As a special
/// case, U+FEFF is excluded from Arabic Presentation Forms-B.
///
/// Returns `true` if the input contains an RTL character or an unpaired
/// high surrogate that could be the high half of an RTL character.
/// Returns `false` if the input contains neither RTL characters nor
/// unpaired high surrogates that could be higher halves of RTL characters.
pub fn is_utf16_bidi(buffer: &[u16]) -> bool {
is_utf16_bidi_impl(buffer)
}
/// Checks whether a scalar value triggers right-to-left processing.
///
/// The check is done on a Unicode block basis without regard to assigned
/// vs. unassigned code points in the block. Hebrew presentation forms in
/// the Alphabetic Presentation Forms block are treated as if they formed
/// a block on their own (i.e. it treated as right-to-left). Additionally,
/// the four RIGHT-TO-LEFT FOO controls in General Punctuation are checked
/// for. Control characters that are technically bidi controls but do not
/// cause right-to-left behavior without the presence of right-to-left
/// characters or right-to-left controls are not checked for. As a special
/// case, U+FEFF is excluded from Arabic Presentation Forms-B.
#[inline(always)]
pub fn is_char_bidi(c: char) -> bool {
// Controls:
// Every control with RIGHT-TO-LEFT in its name in
// https://www.unicode.org/charts/PDF/U2000.pdf
// U+200F RLM
// U+202B RLE
// U+202E RLO
// U+2067 RLI
//
// BMP RTL:
// https://www.unicode.org/roadmaps/bmp/
// U+0590...U+08FF
// U+FB1D...U+FDFF Hebrew presentation forms and
// Arabic Presentation Forms A
// U+FE70...U+FEFE Arabic Presentation Forms B (excl. BOM)
//
// Supplementary RTL:
// https://www.unicode.org/roadmaps/smp/
// U+10800...U+10FFF (Lead surrogate U+D802 or U+D803)
// U+1E800...U+1EFFF (Lead surrogate U+D83A or U+D83B)
let code_point = u32::from(c);
if code_point < 0x0590 {
// Below Hebrew
return false;
}
if in_range32(code_point, 0x0900, 0xFB1D) {
// Above Arabic Extended-A and below Hebrew presentation forms
if in_inclusive_range32(code_point, 0x200F, 0x2067) {
// In the range that contains the RTL controls
return code_point == 0x200F
|| code_point == 0x202B
|| code_point == 0x202E
|| code_point == 0x2067;
}
return false;
}
if code_point > 0x1EFFF {
// Above second astral RTL. (Emoji is here.)
return false;
}
if in_range32(code_point, 0x11000, 0x1E800) {
// Between astral RTL blocks
return false;
}
if in_range32(code_point, 0xFEFF, 0x10800) {
// Above Arabic Presentations Forms B (excl. BOM) and below first
// astral RTL
return false;
}
if in_range32(code_point, 0xFE00, 0xFE70) {
// Between Arabic Presentations Forms
return false;
}
true
}
/// Checks whether a UTF-16 code unit triggers right-to-left processing.
///
/// The check is done on a Unicode block basis without regard to assigned
/// vs. unassigned code points in the block. Hebrew presentation forms in
/// the Alphabetic Presentation Forms block are treated as if they formed
/// a block on their own (i.e. it treated as right-to-left). Additionally,
/// the four RIGHT-TO-LEFT FOO controls in General Punctuation are checked
/// for. Control characters that are technically bidi controls but do not
/// cause right-to-left behavior without the presence of right-to-left
/// characters or right-to-left controls are not checked for. As a special
/// case, U+FEFF is excluded from Arabic Presentation Forms-B.
///
/// Since supplementary-plane right-to-left blocks are identifiable from the
/// high surrogate without examining the low surrogate, this function returns
/// `true` for such high surrogates making the function suitable for handling
/// supplementary-plane text without decoding surrogate pairs to scalar
/// values. Obviously, such high surrogates are then reported as right-to-left
/// even if actually unpaired.
#[inline(always)]
pub fn is_utf16_code_unit_bidi(u: u16) -> bool {
if u < 0x0590 {
// Below Hebrew
return false;
}
if in_range16(u, 0x0900, 0xD802) {
// Above Arabic Extended-A and below first RTL surrogate
if in_inclusive_range16(u, 0x200F, 0x2067) {
// In the range that contains the RTL controls
return u == 0x200F || u == 0x202B || u == 0x202E || u == 0x2067;
}
return false;
}
if in_range16(u, 0xD83C, 0xFB1D) {
// Between astral RTL high surrogates and Hebrew presentation forms
// (Emoji is here)
return false;
}
if in_range16(u, 0xD804, 0xD83A) {
// Between RTL high surragates
return false;
}
if u > 0xFEFE {
// Above Arabic Presentation Forms (excl. BOM)
return false;
}
if in_range16(u, 0xFE00, 0xFE70) {
// Between Arabic Presentations Forms
return false;
}
true
}
/// Checks whether a potentially invalid UTF-8 buffer contains code points
/// that trigger right-to-left processing or is all-Latin1.
///
/// Possibly more efficient than performing the checks separately.
///
/// Returns `Latin1Bidi::Latin1` if `is_utf8_latin1()` would return `true`.
/// Otherwise, returns `Latin1Bidi::Bidi` if `is_utf8_bidi()` would return
/// `true`. Otherwise, returns `Latin1Bidi::LeftToRight`.
pub fn check_utf8_for_latin1_and_bidi(buffer: &[u8]) -> Latin1Bidi {
if let Some(offset) = is_utf8_latin1_impl(buffer) {
if is_utf8_bidi(&buffer[offset..]) {
Latin1Bidi::Bidi
} else {
Latin1Bidi::LeftToRight
}
} else {
Latin1Bidi::Latin1
}
}
/// Checks whether a valid UTF-8 buffer contains code points
/// that trigger right-to-left processing or is all-Latin1.
///
/// Possibly more efficient than performing the checks separately.
///
/// Returns `Latin1Bidi::Latin1` if `is_str_latin1()` would return `true`.
/// Otherwise, returns `Latin1Bidi::Bidi` if `is_str_bidi()` would return
/// `true`. Otherwise, returns `Latin1Bidi::LeftToRight`.
pub fn check_str_for_latin1_and_bidi(buffer: &str) -> Latin1Bidi {
// The transition from the latin1 check to the bidi check isn't
// optimal but not tweaking it to perfection today.
if let Some(offset) = is_str_latin1_impl(buffer) {
if is_str_bidi(&buffer[offset..]) {
Latin1Bidi::Bidi
} else {
Latin1Bidi::LeftToRight
}
} else {
Latin1Bidi::Latin1
}
}
/// Checks whether a potentially invalid UTF-16 buffer contains code points
/// that trigger right-to-left processing or is all-Latin1.
///
/// Possibly more efficient than performing the checks separately.
///
/// Returns `Latin1Bidi::Latin1` if `is_utf16_latin1()` would return `true`.
/// Otherwise, returns `Latin1Bidi::Bidi` if `is_utf16_bidi()` would return
/// `true`. Otherwise, returns `Latin1Bidi::LeftToRight`.
pub fn check_utf16_for_latin1_and_bidi(buffer: &[u16]) -> Latin1Bidi {
check_utf16_for_latin1_and_bidi_impl(buffer)
}
/// Converts potentially-invalid UTF-8 to valid UTF-16 with errors replaced
/// with the REPLACEMENT CHARACTER.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer _plus one_.
///
/// Returns the number of `u16`s written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn convert_utf8_to_utf16(src: &[u8], dst: &mut [u16]) -> usize {
// TODO: Can the requirement for dst to be at least one unit longer
// be eliminated?
assert!(dst.len() > src.len());
let mut decoder = Utf8Decoder::new_inner();
let mut total_read = 0usize;
let mut total_written = 0usize;
loop {
let (result, read, written) =
decoder.decode_to_utf16_raw(&src[total_read..], &mut dst[total_written..], true);
total_read += read;
total_written += written;
match result {
DecoderResult::InputEmpty => {
return total_written;
}
DecoderResult::OutputFull => {
unreachable!("The assert at the top of the function should have caught this.");
}
DecoderResult::Malformed(_, _) => {
// There should always be space for the U+FFFD, because
// otherwise we'd have gotten OutputFull already.
dst[total_written] = 0xFFFD;
total_written += 1;
}
}
}
}
/// Converts valid UTF-8 to valid UTF-16.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of `u16`s written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn convert_str_to_utf16(src: &str, dst: &mut [u16]) -> usize {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
let bytes = src.as_bytes();
let mut read = 0;
let mut written = 0;
'outer: loop {
let mut byte = {
let src_remaining = &bytes[read..];
let dst_remaining = &mut dst[written..];
let length = src_remaining.len();
match unsafe {
ascii_to_basic_latin(src_remaining.as_ptr(), dst_remaining.as_mut_ptr(), length)
} {
None => {
written += length;
return written;
}
Some((non_ascii, consumed)) => {
read += consumed;
written += consumed;
non_ascii
}
}
};
'inner: loop {
// At this point, `byte` is not included in `read`.
if byte < 0xE0 {
if byte >= 0x80 {
// Two-byte
let second = unsafe { *(bytes.get_unchecked(read + 1)) };
let point = ((u16::from(byte) & 0x1F) << 6) | (u16::from(second) & 0x3F);
unsafe { *(dst.get_unchecked_mut(written)) = point };
read += 2;
written += 1;
} else {
// ASCII: write and go back to SIMD.
unsafe { *(dst.get_unchecked_mut(written)) = u16::from(byte) };
read += 1;
written += 1;
// Intuitively, we should go back to the outer loop only
// if byte is 0x30 or above, so as to avoid trashing on
// ASCII space, comma and period in non-Latin context.
// However, the extra branch seems to cost more than it's
// worth.
continue 'outer;
}
} else if byte < 0xF0 {
// Three-byte
let second = unsafe { *(bytes.get_unchecked(read + 1)) };
let third = unsafe { *(bytes.get_unchecked(read + 2)) };
let point = ((u16::from(byte) & 0xF) << 12)
| ((u16::from(second) & 0x3F) << 6)
| (u16::from(third) & 0x3F);
unsafe { *(dst.get_unchecked_mut(written)) = point };
read += 3;
written += 1;
} else {
// Four-byte
let second = unsafe { *(bytes.get_unchecked(read + 1)) };
let third = unsafe { *(bytes.get_unchecked(read + 2)) };
let fourth = unsafe { *(bytes.get_unchecked(read + 3)) };
let point = ((u32::from(byte) & 0x7) << 18)
| ((u32::from(second) & 0x3F) << 12)
| ((u32::from(third) & 0x3F) << 6)
| (u32::from(fourth) & 0x3F);
unsafe { *(dst.get_unchecked_mut(written)) = (0xD7C0 + (point >> 10)) as u16 };
unsafe {
*(dst.get_unchecked_mut(written + 1)) = (0xDC00 + (point & 0x3FF)) as u16
};
read += 4;
written += 2;
}
// The comparison is always < or == and never >, but including
// > here to let the compiler assume that < is true if this
// comparison is false.
if read >= src.len() {
return written;
}
byte = bytes[read];
continue 'inner;
}
}
}
/// Converts potentially-invalid UTF-8 to valid UTF-16 signaling on error.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of `u16`s written or `None` if the input was invalid.
///
/// When the input was invalid, some output may have been written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn convert_utf8_to_utf16_without_replacement(src: &[u8], dst: &mut [u16]) -> Option<usize> {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
let (read, written) = convert_utf8_to_utf16_up_to_invalid(src, dst);
if read == src.len() {
return Some(written);
}
None
}
/// Converts potentially-invalid UTF-16 to valid UTF-8 with errors replaced
/// with the REPLACEMENT CHARACTER with potentially insufficient output
/// space.
///
/// Returns the number of code units read and the number of bytes written.
///
/// Guarantees that the bytes in the destination beyond the number of
/// bytes claimed as written by the second item of the return tuple
/// are left unmodified.
///
/// Not all code units are read if there isn't enough output space.
///
/// Note that this method isn't designed for general streamability but for
/// not allocating memory for the worst case up front. Specifically,
/// if the input starts with or ends with an unpaired surrogate, those are
/// replaced with the REPLACEMENT CHARACTER.
///
/// Matches the semantics of `TextEncoder.encodeInto()` from the
/// Encoding Standard.
///
/// # Safety
///
/// If you want to convert into a `&mut str`, use
/// `convert_utf16_to_str_partial()` instead of using this function
/// together with the `unsafe` method `as_bytes_mut()` on `&mut str`.
#[inline(always)]
pub fn convert_utf16_to_utf8_partial(src: &[u16], dst: &mut [u8]) -> (usize, usize) {
// The two functions called below are marked `inline(never)` to make
// transitions from the hot part (first function) into the cold part
// (second function) go through a return and another call to discouge
// the CPU from speculating from the hot code into the cold code.
// Letting the transitions be mere intra-function jumps, even to
// basic blocks out-of-lined to the end of the function would wipe
// away a quarter of Arabic encode performance on Haswell!
let (read, written) = convert_utf16_to_utf8_partial_inner(src, dst);
if likely(read == src.len()) {
return (read, written);
}
let (tail_read, tail_written) =
convert_utf16_to_utf8_partial_tail(&src[read..], &mut dst[written..]);
(read + tail_read, written + tail_written)
}
/// Converts potentially-invalid UTF-16 to valid UTF-8 with errors replaced
/// with the REPLACEMENT CHARACTER.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer times three.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
///
/// # Safety
///
/// If you want to convert into a `&mut str`, use `convert_utf16_to_str()`
/// instead of using this function together with the `unsafe` method
/// `as_bytes_mut()` on `&mut str`.
#[inline(always)]
pub fn convert_utf16_to_utf8(src: &[u16], dst: &mut [u8]) -> usize {
assert!(dst.len() >= src.len() * 3);
let (read, written) = convert_utf16_to_utf8_partial(src, dst);
debug_assert_eq!(read, src.len());
written
}
/// Converts potentially-invalid UTF-16 to valid UTF-8 with errors replaced
/// with the REPLACEMENT CHARACTER such that the validity of the output is
/// signaled using the Rust type system with potentially insufficient output
/// space.
///
/// Returns the number of code units read and the number of bytes written.
///
/// Not all code units are read if there isn't enough output space.
///
/// Note that this method isn't designed for general streamability but for
/// not allocating memory for the worst case up front. Specifically,
/// if the input starts with or ends with an unpaired surrogate, those are
/// replaced with the REPLACEMENT CHARACTER.
pub fn convert_utf16_to_str_partial(src: &[u16], dst: &mut str) -> (usize, usize) {
let bytes: &mut [u8] = unsafe { dst.as_bytes_mut() };
let (read, written) = convert_utf16_to_utf8_partial(src, bytes);
let len = bytes.len();
let mut trail = written;
while trail < len && ((bytes[trail] & 0xC0) == 0x80) {
bytes[trail] = 0;
trail += 1;
}
(read, written)
}
/// Converts potentially-invalid UTF-16 to valid UTF-8 with errors replaced
/// with the REPLACEMENT CHARACTER such that the validity of the output is
/// signaled using the Rust type system.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer times three.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
#[inline(always)]
pub fn convert_utf16_to_str(src: &[u16], dst: &mut str) -> usize {
assert!(dst.len() >= src.len() * 3);
let (read, written) = convert_utf16_to_str_partial(src, dst);
debug_assert_eq!(read, src.len());
written
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-16.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// The number of `u16`s written equals the length of the source buffer.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn convert_latin1_to_utf16(src: &[u8], dst: &mut [u16]) {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
// TODO: On aarch64, the safe version autovectorizes to the same unpacking
// instructions and this code, but, yet, the autovectorized version is
// faster.
unsafe {
unpack_latin1(src.as_ptr(), dst.as_mut_ptr(), src.len());
}
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-8 with potentially insufficient
/// output space.
///
/// Returns the number of bytes read and the number of bytes written.
///
/// If the output isn't large enough, not all input is consumed.
///
/// # Safety
///
/// If you want to convert into a `&mut str`, use
/// `convert_utf16_to_str_partial()` instead of using this function
/// together with the `unsafe` method `as_bytes_mut()` on `&mut str`.
pub fn convert_latin1_to_utf8_partial(src: &[u8], dst: &mut [u8]) -> (usize, usize) {
let src_len = src.len();
let src_ptr = src.as_ptr();
let dst_ptr = dst.as_mut_ptr();
let dst_len = dst.len();
let mut total_read = 0usize;
let mut total_written = 0usize;
loop {
// src can't advance more than dst
let src_left = src_len - total_read;
let dst_left = dst_len - total_written;
let min_left = ::core::cmp::min(src_left, dst_left);
if let Some((non_ascii, consumed)) = unsafe {
ascii_to_ascii(
src_ptr.add(total_read),
dst_ptr.add(total_written),
min_left,
)
} {
total_read += consumed;
total_written += consumed;
if total_written.checked_add(2).unwrap() > dst_len {
return (total_read, total_written);
}
total_read += 1; // consume `non_ascii`
dst[total_written] = (non_ascii >> 6) | 0xC0;
total_written += 1;
dst[total_written] = (non_ascii & 0x3F) | 0x80;
total_written += 1;
continue;
}
return (total_read + min_left, total_written + min_left);
}
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-8.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer times two.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
///
/// # Safety
///
/// Note that this function may write garbage beyond the number of bytes
/// indicated by the return value, so using a `&mut str` interpreted as
/// `&mut [u8]` as the destination is not safe. If you want to convert into
/// a `&mut str`, use `convert_utf16_to_str()` instead of this function.
#[inline]
pub fn convert_latin1_to_utf8(src: &[u8], dst: &mut [u8]) -> usize {
assert!(
dst.len() >= src.len() * 2,
"Destination must not be shorter than the source times two."
);
let (read, written) = convert_latin1_to_utf8_partial(src, dst);
debug_assert_eq!(read, src.len());
written
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-8 such that the validity of the
/// output is signaled using the Rust type system with potentially insufficient
/// output space.
///
/// Returns the number of bytes read and the number of bytes written.
///
/// If the output isn't large enough, not all input is consumed.
#[inline]
pub fn convert_latin1_to_str_partial(src: &[u8], dst: &mut str) -> (usize, usize) {
let bytes: &mut [u8] = unsafe { dst.as_bytes_mut() };
let (read, written) = convert_latin1_to_utf8_partial(src, bytes);
let len = bytes.len();
let mut trail = written;
let max = ::core::cmp::min(len, trail + MAX_STRIDE_SIZE);
while trail < max {
bytes[trail] = 0;
trail += 1;
}
while trail < len && ((bytes[trail] & 0xC0) == 0x80) {
bytes[trail] = 0;
trail += 1;
}
(read, written)
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-8 such that the validity of the
/// output is signaled using the Rust type system.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer times two.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
#[inline]
pub fn convert_latin1_to_str(src: &[u8], dst: &mut str) -> usize {
assert!(
dst.len() >= src.len() * 2,
"Destination must not be shorter than the source times two."
);
let (read, written) = convert_latin1_to_str_partial(src, dst);
debug_assert_eq!(read, src.len());
written
}
/// If the input is valid UTF-8 representing only Unicode code points from
/// U+0000 to U+00FF, inclusive, converts the input into output that
/// represents the value of each code point as the unsigned byte value of
/// each output byte.
///
/// If the input does not fulfill the condition stated above, this function
/// panics if debug assertions are enabled (and fuzzing isn't) and otherwise
/// does something that is memory-safe without any promises about any
/// properties of the output. In particular, callers shouldn't assume the
/// output to be the same across crate versions or CPU architectures and
/// should not assume that non-ASCII input can't map to ASCII output.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
///
/// If debug assertions are enabled (and not fuzzing) and the input is
/// not in the range U+0000 to U+00FF, inclusive.
pub fn convert_utf8_to_latin1_lossy(src: &[u8], dst: &mut [u8]) -> usize {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
non_fuzz_debug_assert!(is_utf8_latin1(src));
let src_len = src.len();
let src_ptr = src.as_ptr();
let dst_ptr = dst.as_mut_ptr();
let mut total_read = 0usize;
let mut total_written = 0usize;
loop {
// dst can't advance more than src
let src_left = src_len - total_read;
if let Some((non_ascii, consumed)) = unsafe {
ascii_to_ascii(
src_ptr.add(total_read),
dst_ptr.add(total_written),
src_left,
)
} {
total_read += consumed + 1;
total_written += consumed;
if total_read == src_len {
return total_written;
}
let trail = src[total_read];
total_read += 1;
dst[total_written] = ((non_ascii & 0x1F) << 6) | (trail & 0x3F);
total_written += 1;
continue;
}
return total_written + src_left;
}
}
/// If the input is valid UTF-16 representing only Unicode code points from
/// U+0000 to U+00FF, inclusive, converts the input into output that
/// represents the value of each code point as the unsigned byte value of
/// each output byte.
///
/// If the input does not fulfill the condition stated above, does something
/// that is memory-safe without any promises about any properties of the
/// output and will probably assert in debug builds in future versions.
/// In particular, callers shouldn't assume the output to be the same across
/// crate versions or CPU architectures and should not assume that non-ASCII
/// input can't map to ASCII output.
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// The number of bytes written equals the length of the source buffer.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
///
/// (Probably in future versions if debug assertions are enabled (and not
/// fuzzing) and the input is not in the range U+0000 to U+00FF, inclusive.)
pub fn convert_utf16_to_latin1_lossy(src: &[u16], dst: &mut [u8]) {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
// non_fuzz_debug_assert!(is_utf16_latin1(src));
unsafe {
pack_latin1(src.as_ptr(), dst.as_mut_ptr(), src.len());
}
}
/// Converts bytes whose unsigned value is interpreted as Unicode code point
/// (i.e. U+0000 to U+00FF, inclusive) to UTF-8.
///
/// Borrows if input is ASCII-only. Performs a single heap allocation
/// otherwise.
///
/// Only available if the `alloc` feature is enabled (enabled by default).
#[cfg(feature = "alloc")]
pub fn decode_latin1<'a>(bytes: &'a [u8]) -> Cow<'a, str> {
let up_to = ascii_valid_up_to(bytes);
// >= makes later things optimize better than ==
if up_to >= bytes.len() {
debug_assert_eq!(up_to, bytes.len());
let s: &str = unsafe { ::core::str::from_utf8_unchecked(bytes) };
return Cow::Borrowed(s);
}
let (head, tail) = bytes.split_at(up_to);
let capacity = head.len() + tail.len() * 2;
let mut vec = Vec::with_capacity(capacity);
unsafe {
vec.set_len(capacity);
}
(&mut vec[..up_to]).copy_from_slice(head);
let written = convert_latin1_to_utf8(tail, &mut vec[up_to..]);
vec.truncate(up_to + written);
Cow::Owned(unsafe { String::from_utf8_unchecked(vec) })
}
/// If the input is valid UTF-8 representing only Unicode code points from
/// U+0000 to U+00FF, inclusive, converts the input into output that
/// represents the value of each code point as the unsigned byte value of
/// each output byte.
///
/// If the input does not fulfill the condition stated above, this function
/// panics if debug assertions are enabled (and fuzzing isn't) and otherwise
/// does something that is memory-safe without any promises about any
/// properties of the output. In particular, callers shouldn't assume the
/// output to be the same across crate versions or CPU architectures and
/// should not assume that non-ASCII input can't map to ASCII output.
///
/// Borrows if input is ASCII-only. Performs a single heap allocation
/// otherwise.
///
/// Only available if the `alloc` feature is enabled (enabled by default).
#[cfg(feature = "alloc")]
pub fn encode_latin1_lossy<'a>(string: &'a str) -> Cow<'a, [u8]> {
let bytes = string.as_bytes();
let up_to = ascii_valid_up_to(bytes);
// >= makes later things optimize better than ==
if up_to >= bytes.len() {
debug_assert_eq!(up_to, bytes.len());
return Cow::Borrowed(bytes);
}
let (head, tail) = bytes.split_at(up_to);
let capacity = bytes.len();
let mut vec = Vec::with_capacity(capacity);
unsafe {
vec.set_len(capacity);
}
(&mut vec[..up_to]).copy_from_slice(head);
let written = convert_utf8_to_latin1_lossy(tail, &mut vec[up_to..]);
vec.truncate(up_to + written);
Cow::Owned(vec)
}
/// Returns the index of the first unpaired surrogate or, if the input is
/// valid UTF-16 in its entirety, the length of the input.
pub fn utf16_valid_up_to(buffer: &[u16]) -> usize {
utf16_valid_up_to_impl(buffer)
}
/// Returns the index of first byte that starts an invalid byte
/// sequence or a non-Latin1 byte sequence, or the length of the
/// string if there are neither.
pub fn utf8_latin1_up_to(buffer: &[u8]) -> usize {
is_utf8_latin1_impl(buffer).unwrap_or(buffer.len())
}
/// Returns the index of first byte that starts a non-Latin1 byte
/// sequence, or the length of the string if there are none.
pub fn str_latin1_up_to(buffer: &str) -> usize {
is_str_latin1_impl(buffer).unwrap_or_else(|| buffer.len())
}
/// Replaces unpaired surrogates in the input with the REPLACEMENT CHARACTER.
#[inline]
pub fn ensure_utf16_validity(buffer: &mut [u16]) {
let mut offset = 0;
loop {
offset += utf16_valid_up_to(&buffer[offset..]);
if offset == buffer.len() {
return;
}
buffer[offset] = 0xFFFD;
offset += 1;
}
}
/// Copies ASCII from source to destination up to the first non-ASCII byte
/// (or the end of the input if it is ASCII in its entirety).
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn copy_ascii_to_ascii(src: &[u8], dst: &mut [u8]) -> usize {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
if let Some((_, consumed)) =
unsafe { ascii_to_ascii(src.as_ptr(), dst.as_mut_ptr(), src.len()) }
{
consumed
} else {
src.len()
}
}
/// Copies ASCII from source to destination zero-extending it to UTF-16 up to
/// the first non-ASCII byte (or the end of the input if it is ASCII in its
/// entirety).
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of `u16`s written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn copy_ascii_to_basic_latin(src: &[u8], dst: &mut [u16]) -> usize {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
if let Some((_, consumed)) =
unsafe { ascii_to_basic_latin(src.as_ptr(), dst.as_mut_ptr(), src.len()) }
{
consumed
} else {
src.len()
}
}
/// Copies Basic Latin from source to destination narrowing it to ASCII up to
/// the first non-Basic Latin code unit (or the end of the input if it is
/// Basic Latin in its entirety).
///
/// The length of the destination buffer must be at least the length of the
/// source buffer.
///
/// Returns the number of bytes written.
///
/// # Panics
///
/// Panics if the destination buffer is shorter than stated above.
pub fn copy_basic_latin_to_ascii(src: &[u16], dst: &mut [u8]) -> usize {
assert!(
dst.len() >= src.len(),
"Destination must not be shorter than the source."
);
if let Some((_, consumed)) =
unsafe { basic_latin_to_ascii(src.as_ptr(), dst.as_mut_ptr(), src.len()) }
{
consumed
} else {
src.len()
}
}
// Any copyright to the test code below this comment is dedicated to the
// Public Domain. http://creativecommons.org/publicdomain/zero/1.0/
#[cfg(all(test, feature = "alloc"))]
mod tests {
use super::*;
#[test]
fn test_is_ascii_success() {
let mut src: Vec<u8> = Vec::with_capacity(128);
src.resize(128, 0);
for i in 0..src.len() {
src[i] = i as u8;
}
for i in 0..src.len() {
assert!(is_ascii(&src[i..]));
}
}
#[test]
fn test_is_ascii_fail() {
let mut src: Vec<u8> = Vec::with_capacity(128);
src.resize(128, 0);
for i in 0..src.len() {
src[i] = i as u8;
}
for i in 0..src.len() {
let tail = &mut src[i..];
for j in 0..tail.len() {
tail[j] = 0xA0;
assert!(!is_ascii(tail));
}
}
}
#[test]
fn test_is_basic_latin_success() {
let mut src: Vec<u16> = Vec::with_capacity(128);
src.resize(128, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
assert!(is_basic_latin(&src[i..]));
}
}
#[test]
fn test_is_basic_latin_fail() {
let mut src: Vec<u16> = Vec::with_capacity(128);
src.resize(128, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let tail = &mut src[i..];
for j in 0..tail.len() {
tail[j] = 0xA0;
assert!(!is_basic_latin(tail));
}
}
}
#[test]
fn test_is_utf16_latin1_success() {
let mut src: Vec<u16> = Vec::with_capacity(256);
src.resize(256, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
assert!(is_utf16_latin1(&src[i..]));
assert_eq!(
check_utf16_for_latin1_and_bidi(&src[i..]),
Latin1Bidi::Latin1
);
}
}
#[test]
fn test_is_utf16_latin1_fail() {
let len = if cfg!(miri) { 64 } else { 256 }; // Miri is too slow
let mut src: Vec<u16> = Vec::with_capacity(len);
src.resize(len, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let tail = &mut src[i..];
for j in 0..tail.len() {
tail[j] = 0x100 + j as u16;
assert!(!is_utf16_latin1(tail));
assert_ne!(check_utf16_for_latin1_and_bidi(tail), Latin1Bidi::Latin1);
}
}
}
#[test]
fn test_is_str_latin1_success() {
let len = if cfg!(miri) { 64 } else { 256 }; // Miri is too slow
let mut src: Vec<u16> = Vec::with_capacity(len);
src.resize(len, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let s = String::from_utf16(&src[i..]).unwrap();
assert!(is_str_latin1(&s[..]));
assert_eq!(check_str_for_latin1_and_bidi(&s[..]), Latin1Bidi::Latin1);
}
}
#[test]
fn test_is_str_latin1_fail() {
let len = if cfg!(miri) { 32 } else { 256 }; // Miri is too slow
let mut src: Vec<u16> = Vec::with_capacity(len);
src.resize(len, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let tail = &mut src[i..];
for j in 0..tail.len() {
tail[j] = 0x100 + j as u16;
let s = String::from_utf16(tail).unwrap();
assert!(!is_str_latin1(&s[..]));
assert_ne!(check_str_for_latin1_and_bidi(&s[..]), Latin1Bidi::Latin1);
}
}
}
#[test]
fn test_is_utf8_latin1_success() {
let len = if cfg!(miri) { 64 } else { 256 }; // Miri is too slow
let mut src: Vec<u16> = Vec::with_capacity(len);
src.resize(len, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let s = String::from_utf16(&src[i..]).unwrap();
assert!(is_utf8_latin1(s.as_bytes()));
assert_eq!(
check_utf8_for_latin1_and_bidi(s.as_bytes()),
Latin1Bidi::Latin1
);
}
}
#[test]
fn test_is_utf8_latin1_fail() {
let len = if cfg!(miri) { 32 } else { 256 }; // Miri is too slow
let mut src: Vec<u16> = Vec::with_capacity(len);
src.resize(len, 0);
for i in 0..src.len() {
src[i] = i as u16;
}
for i in 0..src.len() {
let tail = &mut src[i..];
for j in 0..tail.len() {
tail[j] = 0x100 + j as u16;
let s = String::from_utf16(tail).unwrap();
assert!(!is_utf8_latin1(s.as_bytes()));
assert_ne!(
check_utf8_for_latin1_and_bidi(s.as_bytes()),
Latin1Bidi::Latin1
);
}
}
}
#[test]
fn test_is_utf8_latin1_invalid() {
assert!(!is_utf8_latin1(b"\xC3"));
assert!(!is_utf8_latin1(b"a\xC3"));
assert!(!is_utf8_latin1(b"\xFF"));
assert!(!is_utf8_latin1(b"a\xFF"));
assert!(!is_utf8_latin1(b"\xC3\xFF"));
assert!(!is_utf8_latin1(b"a\xC3\xFF"));
}
#[test]
fn test_convert_utf8_to_utf16() {
let src = "abcdefghijklmnopqrstu\u{1F4A9}v\u{2603}w\u{00B6}xyzz";
let mut dst: Vec<u16> = Vec::with_capacity(src.len() + 1);
dst.resize(src.len() + 1, 0);
let len = convert_utf8_to_utf16(src.as_bytes(), &mut dst[..]);
dst.truncate(len);
let reference: Vec<u16> = src.encode_utf16().collect();
assert_eq!(dst, reference);
}
#[test]
fn test_convert_str_to_utf16() {
let src = "abcdefghijklmnopqrstu\u{1F4A9}v\u{2603}w\u{00B6}xyzz";
let mut dst: Vec<u16> = Vec::with_capacity(src.len());
dst.resize(src.len(), 0);
let len = convert_str_to_utf16(src, &mut dst[..]);
dst.truncate(len);
let reference: Vec<u16> = src.encode_utf16().collect();
assert_eq!(dst, reference);
}
#[test]
fn test_convert_utf16_to_utf8_partial() {
let reference = "abcdefghijklmnopqrstu\u{1F4A9}v\u{2603}w\u{00B6}xyzz";
let src: Vec<u16> = reference.encode_utf16().collect();
let mut dst: Vec<u8> = Vec::with_capacity(src.len() * 3 + 1);
dst.resize(src.len() * 3 + 1, 0);
let (read, written) = convert_utf16_to_utf8_partial(&src[..], &mut dst[..24]);
let len = written + convert_utf16_to_utf8(&src[read..], &mut dst[written..]);
dst.truncate(len);
assert_eq!(dst, reference.as_bytes());
}
#[test]
fn test_convert_utf16_to_utf8() {
let reference = "abcdefghijklmnopqrstu\u{1F4A9}v\u{2603}w\u{00B6}xyzz";
let src: Vec<u16> = reference.encode_utf16().collect();
let mut dst: Vec<u8> = Vec::with_capacity(src.len() * 3 + 1);
dst.resize(src.len() * 3 + 1, 0);
let len = convert_utf16_to_utf8(&src[..], &mut dst[..]);
dst.truncate(len);
assert_eq!(dst, reference.as_bytes());
}
#[test]
fn test_convert_latin1_to_utf16() {
let mut src: Vec<u8> = Vec::with_capacity(256);
src.resize(256, 0);
let mut reference: Vec<u16> = Vec::with_capacity(256);
reference.resize(256, 0);
for i in 0..256 {
src[i] = i as u8;
reference[i] = i as u16;
}
let mut dst: Vec<u16> = Vec::with_capacity(src.len());
dst.resize(src.len(), 0);
convert_latin1_to_utf16(&src[..], &mut dst[..]);
assert_eq!(dst, reference);
}
#[test]
fn test_convert_latin1_to_utf8_partial() {
let mut dst = [0u8, 2];
let (read, written) = convert_latin1_to_utf8_partial(b"a\xFF", &mut dst[..]);
assert_eq!(read, 1);
assert_eq!(written, 1);
}
#[test]
fn test_convert_latin1_to_utf8() {
let mut src: Vec<u8> = Vec::with_capacity(256);
src.resize(256, 0);
let mut reference: Vec<u16> = Vec::with_capacity(256);
reference.resize(256, 0);
for i in 0..256 {
src[i] = i as u8;
reference[i] = i as u16;
}
let s = String::from_utf16(&reference[..]).unwrap();
let mut dst: Vec<u8> = Vec::with_capacity(src.len() * 2);
dst.resize(src.len() * 2, 0);
let len = convert_latin1_to_utf8(&src[..], &mut dst[..]);
dst.truncate(len);
assert_eq!(&dst[..], s.as_bytes());
}
#[test]
fn test_convert_utf8_to_latin1_lossy() {
let mut reference: Vec<u8> = Vec::with_capacity(256);
reference.resize(256, 0);
let mut src16: Vec<u16> = Vec::with_capacity(256);
src16.resize(256, 0);
for i in 0..256 {
src16[i] = i as u16;
reference[i] = i as u8;
}
let src = String::from_utf16(&src16[..]).unwrap();
let mut dst: Vec<u8> = Vec::with_capacity(src.len());
dst.resize(src.len(), 0);
let len = convert_utf8_to_latin1_lossy(src.as_bytes(), &mut dst[..]);
dst.truncate(len);
assert_eq!(dst, reference);
}
#[cfg(all(debug_assertions, not(fuzzing)))]
#[test]
#[should_panic]
fn test_convert_utf8_to_latin1_lossy_panics() {
let mut dst = [0u8; 16];
let _ = convert_utf8_to_latin1_lossy("\u{100}".as_bytes(), &mut dst[..]);
}
#[test]
fn test_convert_utf16_to_latin1_lossy() {
let mut src: Vec<u16> = Vec::with_capacity(256);
src.resize(256, 0);
let mut reference: Vec<u8> = Vec::with_capacity(256);
reference.resize(256, 0);
for i in 0..256 {
src[i] = i as u16;
reference[i] = i as u8;
}
let mut dst: Vec<u8> = Vec::with_capacity(src.len());
dst.resize(src.len(), 0);
convert_utf16_to_latin1_lossy(&src[..], &mut dst[..]);
assert_eq!(dst, reference);
}
#[test]
// #[should_panic]
fn test_convert_utf16_to_latin1_lossy_panics() {
let mut dst = [0u8; 16];
let _ = convert_utf16_to_latin1_lossy(&[0x0100u16], &mut dst[..]);
}
#[test]
fn test_utf16_valid_up_to() {
let valid = vec![
0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0x2603u16,
0xD83Du16, 0xDCA9u16, 0x00B6u16,
];
assert_eq!(utf16_valid_up_to(&valid[..]), 16);
let lone_high = vec![
0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0x2603u16, 0xD83Du16, 0x00B6u16,
];
assert_eq!(utf16_valid_up_to(&lone_high[..]), 14);
let lone_low = vec![
0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0x2603u16, 0xDCA9u16, 0x00B6u16,
];
assert_eq!(utf16_valid_up_to(&lone_low[..]), 14);
let lone_high_at_end = vec![
0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0x2603u16, 0x00B6u16, 0xD83Du16,
];
assert_eq!(utf16_valid_up_to(&lone_high_at_end[..]), 15);
}
#[test]
fn test_ensure_utf16_validity() {
let mut src = vec![
0u16, 0xD83Du16, 0u16, 0u16, 0u16, 0xD83Du16, 0xDCA9u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0u16, 0xDCA9u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
];
let reference = vec![
0u16, 0xFFFDu16, 0u16, 0u16, 0u16, 0xD83Du16, 0xDCA9u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0u16, 0xFFFDu16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
0u16, 0u16, 0u16, 0u16, 0u16, 0u16,
];
ensure_utf16_validity(&mut src[..]);
assert_eq!(src, reference);
}
#[test]
fn test_is_char_bidi() {
assert!(!is_char_bidi('a'));
assert!(!is_char_bidi('\u{03B1}'));
assert!(!is_char_bidi('\u{3041}'));
assert!(!is_char_bidi('\u{1F4A9}'));
assert!(!is_char_bidi('\u{FE00}'));
assert!(!is_char_bidi('\u{202C}'));
assert!(!is_char_bidi('\u{FEFF}'));
assert!(is_char_bidi('\u{0590}'));
assert!(is_char_bidi('\u{08FF}'));
assert!(is_char_bidi('\u{061C}'));
assert!(is_char_bidi('\u{FB50}'));
assert!(is_char_bidi('\u{FDFF}'));
assert!(is_char_bidi('\u{FE70}'));
assert!(is_char_bidi('\u{FEFE}'));
assert!(is_char_bidi('\u{200F}'));
assert!(is_char_bidi('\u{202B}'));
assert!(is_char_bidi('\u{202E}'));
assert!(is_char_bidi('\u{2067}'));
assert!(is_char_bidi('\u{10800}'));
assert!(is_char_bidi('\u{10FFF}'));
assert!(is_char_bidi('\u{1E800}'));
assert!(is_char_bidi('\u{1EFFF}'));
}
#[test]
fn test_is_utf16_code_unit_bidi() {
assert!(!is_utf16_code_unit_bidi(0x0062));
assert!(!is_utf16_code_unit_bidi(0x03B1));
assert!(!is_utf16_code_unit_bidi(0x3041));
assert!(!is_utf16_code_unit_bidi(0xD801));
assert!(!is_utf16_code_unit_bidi(0xFE00));
assert!(!is_utf16_code_unit_bidi(0x202C));
assert!(!is_utf16_code_unit_bidi(0xFEFF));
assert!(is_utf16_code_unit_bidi(0x0590));
assert!(is_utf16_code_unit_bidi(0x08FF));
assert!(is_utf16_code_unit_bidi(0x061C));
assert!(is_utf16_code_unit_bidi(0xFB1D));
assert!(is_utf16_code_unit_bidi(0xFB50));
assert!(is_utf16_code_unit_bidi(0xFDFF));
assert!(is_utf16_code_unit_bidi(0xFE70));
assert!(is_utf16_code_unit_bidi(0xFEFE));
assert!(is_utf16_code_unit_bidi(0x200F));
assert!(is_utf16_code_unit_bidi(0x202B));
assert!(is_utf16_code_unit_bidi(0x202E));
assert!(is_utf16_code_unit_bidi(0x2067));
assert!(is_utf16_code_unit_bidi(0xD802));
assert!(is_utf16_code_unit_bidi(0xD803));
assert!(is_utf16_code_unit_bidi(0xD83A));
assert!(is_utf16_code_unit_bidi(0xD83B));
}
#[test]
fn test_is_str_bidi() {
assert!(!is_str_bidi("abcdefghijklmnopaabcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{03B1}abcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{3041}abcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{1F4A9}abcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{FE00}abcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{202C}abcdefghijklmnop"));
assert!(!is_str_bidi("abcdefghijklmnop\u{FEFF}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{0590}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{08FF}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{061C}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{FB50}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{FDFF}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{FE70}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{FEFE}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{200F}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{202B}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{202E}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{2067}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{10800}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{10FFF}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{1E800}abcdefghijklmnop"));
assert!(is_str_bidi("abcdefghijklmnop\u{1EFFF}abcdefghijklmnop"));
}
#[test]
fn test_is_utf8_bidi() {
assert!(!is_utf8_bidi(
"abcdefghijklmnopaabcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{03B1}abcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{3041}abcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{1F4A9}abcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{FE00}abcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{202C}abcdefghijklmnop".as_bytes()
));
assert!(!is_utf8_bidi(
"abcdefghijklmnop\u{FEFF}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{0590}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{08FF}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{061C}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{FB50}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{FDFF}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{FE70}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{FEFE}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{200F}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{202B}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{202E}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{2067}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{10800}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{10FFF}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{1E800}abcdefghijklmnop".as_bytes()
));
assert!(is_utf8_bidi(
"abcdefghijklmnop\u{1EFFF}abcdefghijklmnop".as_bytes()
));
}
#[test]
fn test_is_utf16_bidi() {
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0062, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x03B1, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x3041, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD801, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFE00, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202C, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(!is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFEFF, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0590, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x08FF, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x061C, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFB1D, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFB50, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFDFF, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFE70, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFEFE, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x200F, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202B, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202E, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x2067, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD802, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD803, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD83A, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD83B, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69,
]));
assert!(is_utf16_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0590, 0x3041, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]));
}
#[test]
fn test_check_str_for_latin1_and_bidi() {
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnopaabcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{03B1}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{3041}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{1F4A9}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FE00}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{202C}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_ne!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FEFF}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{0590}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{08FF}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{061C}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FB50}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FDFF}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FE70}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{FEFE}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{200F}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{202B}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{202E}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{2067}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{10800}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{10FFF}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{1E800}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
assert_eq!(
check_str_for_latin1_and_bidi("abcdefghijklmnop\u{1EFFF}abcdefghijklmnop"),
Latin1Bidi::Bidi
);
}
#[test]
fn test_check_utf8_for_latin1_and_bidi() {
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnopaabcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{03B1}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{3041}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{1F4A9}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FE00}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{202C}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FEFF}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{0590}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{08FF}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{061C}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FB50}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FDFF}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FE70}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{FEFE}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{200F}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{202B}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{202E}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{2067}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{10800}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{10FFF}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{1E800}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf8_for_latin1_and_bidi("abcdefghijklmnop\u{1EFFF}abcdefghijklmnop".as_bytes()),
Latin1Bidi::Bidi
);
}
#[test]
fn test_check_utf16_for_latin1_and_bidi() {
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0062, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x03B1, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x3041, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD801, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFE00, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202C, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_ne!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFEFF, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0590, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x08FF, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x061C, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFB1D, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFB50, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFDFF, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFE70, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xFEFE, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x200F, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202B, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x202E, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x2067, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD802, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD803, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD83A, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xD83B, 0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
assert_eq!(
check_utf16_for_latin1_and_bidi(&[
0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x0590, 0x3041, 0x62, 0x63, 0x64,
0x65, 0x66, 0x67, 0x68, 0x69,
]),
Latin1Bidi::Bidi
);
}
#[inline(always)]
pub fn reference_is_char_bidi(c: char) -> bool {
match c {
'\u{0590}'..='\u{08FF}'
| '\u{FB1D}'..='\u{FDFF}'
| '\u{FE70}'..='\u{FEFE}'
| '\u{10800}'..='\u{10FFF}'
| '\u{1E800}'..='\u{1EFFF}'
| '\u{200F}'
| '\u{202B}'
| '\u{202E}'
| '\u{2067}' => true,
_ => false,
}
}
#[inline(always)]
pub fn reference_is_utf16_code_unit_bidi(u: u16) -> bool {
match u {
0x0590..=0x08FF
| 0xFB1D..=0xFDFF
| 0xFE70..=0xFEFE
| 0xD802
| 0xD803
| 0xD83A
| 0xD83B
| 0x200F
| 0x202B
| 0x202E
| 0x2067 => true,
_ => false,
}
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn test_is_char_bidi_thoroughly() {
for i in 0..0xD800u32 {
let c: char = ::core::char::from_u32(i).unwrap();
assert_eq!(is_char_bidi(c), reference_is_char_bidi(c));
}
for i in 0xE000..0x110000u32 {
let c: char = ::core::char::from_u32(i).unwrap();
assert_eq!(is_char_bidi(c), reference_is_char_bidi(c));
}
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn test_is_utf16_code_unit_bidi_thoroughly() {
for i in 0..0x10000u32 {
let u = i as u16;
assert_eq!(
is_utf16_code_unit_bidi(u),
reference_is_utf16_code_unit_bidi(u)
);
}
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn test_is_str_bidi_thoroughly() {
let mut buf = [0; 4];
for i in 0..0xD800u32 {
let c: char = ::core::char::from_u32(i).unwrap();
assert_eq!(
is_str_bidi(c.encode_utf8(&mut buf[..])),
reference_is_char_bidi(c)
);
}
for i in 0xE000..0x110000u32 {
let c: char = ::core::char::from_u32(i).unwrap();
assert_eq!(
is_str_bidi(c.encode_utf8(&mut buf[..])),
reference_is_char_bidi(c)
);
}
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn test_is_utf8_bidi_thoroughly() {
let mut buf = [0; 8];
for i in 0..0xD800u32 {
let c: char = ::core::char::from_u32(i).unwrap();
let expect = reference_is_char_bidi(c);
{
let len = {
let bytes = c.encode_utf8(&mut buf[..]).as_bytes();
assert_eq!(is_utf8_bidi(bytes), expect);
bytes.len()
};
{
let tail = &mut buf[len..];
for b in tail.iter_mut() {
*b = 0;
}
}
}
assert_eq!(is_utf8_bidi(&buf[..]), expect);
}
for i in 0xE000..0x110000u32 {
let c: char = ::core::char::from_u32(i).unwrap();
let expect = reference_is_char_bidi(c);
{
let len = {
let bytes = c.encode_utf8(&mut buf[..]).as_bytes();
assert_eq!(is_utf8_bidi(bytes), expect);
bytes.len()
};
{
let tail = &mut buf[len..];
for b in tail.iter_mut() {
*b = 0;
}
}
}
assert_eq!(is_utf8_bidi(&buf[..]), expect);
}
}
#[test]
#[cfg_attr(miri, ignore)] // Miri is too slow
fn test_is_utf16_bidi_thoroughly() {
let mut buf = [0; 32];
for i in 0..0x10000u32 {
let u = i as u16;
buf[15] = u;
assert_eq!(
is_utf16_bidi(&buf[..]),
reference_is_utf16_code_unit_bidi(u)
);
}
}
#[test]
fn test_is_utf8_bidi_edge_cases() {
assert!(!is_utf8_bidi(b"\xD5\xBF\x61"));
assert!(!is_utf8_bidi(b"\xD6\x80\x61"));
assert!(!is_utf8_bidi(b"abc"));
assert!(is_utf8_bidi(b"\xD5\xBF\xC2"));
assert!(is_utf8_bidi(b"\xD6\x80\xC2"));
assert!(is_utf8_bidi(b"ab\xC2"));
}
#[test]
fn test_decode_latin1() {
match decode_latin1(b"ab") {
Cow::Borrowed(s) => {
assert_eq!(s, "ab");
}
Cow::Owned(_) => {
unreachable!("Should have borrowed");
}
}
assert_eq!(decode_latin1(b"a\xE4"), "a\u{E4}");
}
#[test]
fn test_encode_latin1_lossy() {
match encode_latin1_lossy("ab") {
Cow::Borrowed(s) => {
assert_eq!(s, b"ab");
}
Cow::Owned(_) => {
unreachable!("Should have borrowed");
}
}
assert_eq!(encode_latin1_lossy("a\u{E4}"), &(b"a\xE4")[..]);
}
#[test]
fn test_convert_utf8_to_utf16_without_replacement() {
let mut buf = [0u16; 5];
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"ab", &mut buf[..2]),
Some(2)
);
assert_eq!(buf[0], u16::from(b'a'));
assert_eq!(buf[1], u16::from(b'b'));
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xC3\xA4c", &mut buf[..3]),
Some(2)
);
assert_eq!(buf[0], 0xE4);
assert_eq!(buf[1], u16::from(b'c'));
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xE2\x98\x83", &mut buf[..3]),
Some(1)
);
assert_eq!(buf[0], 0x2603);
assert_eq!(buf[1], u16::from(b'c'));
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xE2\x98\x83d", &mut buf[..4]),
Some(2)
);
assert_eq!(buf[0], 0x2603);
assert_eq!(buf[1], u16::from(b'd'));
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xE2\x98\x83\xC3\xA4", &mut buf[..5]),
Some(2)
);
assert_eq!(buf[0], 0x2603);
assert_eq!(buf[1], 0xE4);
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xF0\x9F\x93\x8E", &mut buf[..4]),
Some(2)
);
assert_eq!(buf[0], 0xD83D);
assert_eq!(buf[1], 0xDCCE);
assert_eq!(buf[2], 0);
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xF0\x9F\x93\x8Ee", &mut buf[..5]),
Some(3)
);
assert_eq!(buf[0], 0xD83D);
assert_eq!(buf[1], 0xDCCE);
assert_eq!(buf[2], u16::from(b'e'));
assert_eq!(
convert_utf8_to_utf16_without_replacement(b"\xF0\x9F\x93", &mut buf[..5]),
None
);
}
}