/usr/include/d2/4.6/std/encoding.d is in libphobos2-4.6-dev 0.29.1-4.6.3-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | // Written in the D programming language.
/**
Classes and functions for handling and transcoding between various encodings.
For cases where the _encoding is known at compile-time, functions are provided
for arbitrary _encoding and decoding of characters, arbitrary transcoding
between strings of different type, as well as validation and sanitization.
Encodings currently supported are UTF-8, UTF-16, UTF-32, ASCII, ISO-8859-1
(also known as LATIN-1), and WINDOWS-1252.
$(UL
$(LI The type $(D AsciiChar) represents an ASCII character.)
$(LI The type $(D AsciiString) represents an ASCII string.)
$(LI The type $(D Latin1Char) represents an ISO-8859-1 character.)
$(LI The type $(D Latin1String) represents an ISO-8859-1 string.)
$(LI The type $(D Windows1252Char) represents a Windows-1252 character.)
$(LI The type $(D Windows1252String) represents a Windows-1252 string.))
For cases where the _encoding is not known at compile-time, but is
known at run-time, we provide the abstract class $(D EncodingScheme)
and its subclasses. To construct a run-time encoder/decoder, one does
e.g.
----------------------------------------------------
auto e = EncodingScheme.create("utf-8");
----------------------------------------------------
This library supplies $(D EncodingScheme) subclasses for ASCII,
ISO-8859-1 (also known as LATIN-1), WINDOWS-1252, UTF-8, and (on
little-endian architectures) UTF-16LE and UTF-32LE; or (on big-endian
architectures) UTF-16BE and UTF-32BE.
This library provides a mechanism whereby other modules may add $(D
EncodingScheme) subclasses for any other _encoding.
Macros:
WIKI=Phobos/StdEncoding
Copyright: Copyright Janice Caron 2008 - 2009.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: Janice Caron
Source: $(PHOBOSSRC std/_encoding.d)
*/
/*
Copyright Janice Caron 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.encoding;
import std.string;
import std.traits;
import std.range;
unittest
{
static ubyte[][] validStrings =
[
// Plain ASCII
cast(ubyte[])"hello",
// First possible sequence of a certain length
[ 0x00 ], // U+00000000 one byte
[ 0xC2, 0x80 ], // U+00000080 two bytes
[ 0xE0, 0xA0, 0x80 ], // U+00000800 three bytes
[ 0xF0, 0x90, 0x80, 0x80 ], // U+00010000 three bytes
// Last possible sequence of a certain length
[ 0x7F ], // U+0000007F one byte
[ 0xDF, 0xBF ], // U+000007FF two bytes
[ 0xEF, 0xBF, 0xBF ], // U+0000FFFF three bytes
// Other boundary conditions
[ 0xED, 0x9F, 0xBF ],
// U+0000D7FF Last character before surrogates
[ 0xEE, 0x80, 0x80 ],
// U+0000E000 First character after surrogates
[ 0xEF, 0xBF, 0xBD ],
// U+0000FFFD Unicode replacement character
[ 0xF4, 0x8F, 0xBF, 0xBF ],
// U+0010FFFF Very last character
// Non-character code points
/* NOTE: These are legal in UTF, and may be converted from
one UTF to another, however they do not represent Unicode
characters. These code points have been reserved by
Unicode as non-character code points. They are permissible
for data exchange within an application, but they are are
not permitted to be used as characters. Since this module
deals with UTF, and not with Unicode per se, we choose to
accept them here. */
[ 0xDF, 0xBE ], // U+0000FFFE
[ 0xDF, 0xBF ], // U+0000FFFF
];
static ubyte[][] invalidStrings =
[
// First possible sequence of a certain length, but greater
// than U+10FFFF
[ 0xF8, 0x88, 0x80, 0x80, 0x80 ], // U+00200000 five bytes
[ 0xFC, 0x84, 0x80, 0x80, 0x80, 0x80 ], // U+04000000 six bytes
// Last possible sequence of a certain length, but greater than U+10FFFF
[ 0xF7, 0xBF, 0xBF, 0xBF ], // U+001FFFFF four bytes
[ 0xFB, 0xBF, 0xBF, 0xBF, 0xBF ], // U+03FFFFFF five bytes
[ 0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF ], // U+7FFFFFFF six bytes
// Other boundary conditions
[ 0xF4, 0x90, 0x80, 0x80 ], // U+00110000
// First code
// point after
// last character
// Unexpected continuation bytes
[ 0x80 ],
[ 0xBF ],
[ 0x20, 0x80, 0x20 ],
[ 0x20, 0xBF, 0x20 ],
[ 0x80, 0x9F, 0xA0 ],
// Lonely start bytes
[ 0xC0 ],
[ 0xCF ],
[ 0x20, 0xC0, 0x20 ],
[ 0x20, 0xCF, 0x20 ],
[ 0xD0 ],
[ 0xDF ],
[ 0x20, 0xD0, 0x20 ],
[ 0x20, 0xDF, 0x20 ],
[ 0xE0 ],
[ 0xEF ],
[ 0x20, 0xE0, 0x20 ],
[ 0x20, 0xEF, 0x20 ],
[ 0xF0 ],
[ 0xF1 ],
[ 0xF2 ],
[ 0xF3 ],
[ 0xF4 ],
[ 0xF5 ], // If this were legal it would start a character > U+10FFFF
[ 0xF6 ], // If this were legal it would start a character > U+10FFFF
[ 0xF7 ], // If this were legal it would start a character > U+10FFFF
[ 0xEF, 0xBF ], // Three byte sequence with third byte missing
[ 0xF7, 0xBF, 0xBF ], // Four byte sequence with fourth byte missing
[ 0xEF, 0xBF, 0xF7, 0xBF, 0xBF ], // Concatenation of the above
// Impossible bytes
[ 0xF8 ],
[ 0xF9 ],
[ 0xFA ],
[ 0xFB ],
[ 0xFC ],
[ 0xFD ],
[ 0xFE ],
[ 0xFF ],
[ 0x20, 0xF8, 0x20 ],
[ 0x20, 0xF9, 0x20 ],
[ 0x20, 0xFA, 0x20 ],
[ 0x20, 0xFB, 0x20 ],
[ 0x20, 0xFC, 0x20 ],
[ 0x20, 0xFD, 0x20 ],
[ 0x20, 0xFE, 0x20 ],
[ 0x20, 0xFF, 0x20 ],
// Overlong sequences, all representing U+002F
/* With a safe UTF-8 decoder, all of the following five overlong
representations of the ASCII character slash ("/") should be
rejected like a malformed UTF-8 sequence */
[ 0xC0, 0xAF ],
[ 0xE0, 0x80, 0xAF ],
[ 0xF0, 0x80, 0x80, 0xAF ],
[ 0xF8, 0x80, 0x80, 0x80, 0xAF ],
[ 0xFC, 0x80, 0x80, 0x80, 0x80, 0xAF ],
// Maximum overlong sequences
/* Below you see the highest Unicode value that is still resulting in
an overlong sequence if represented with the given number of bytes.
This is a boundary test for safe UTF-8 decoders. All five
characters should be rejected like malformed UTF-8 sequences. */
[ 0xC1, 0xBF ], // U+0000007F
[ 0xE0, 0x9F, 0xBF ], // U+000007FF
[ 0xF0, 0x8F, 0xBF, 0xBF ], // U+0000FFFF
[ 0xF8, 0x87, 0xBF, 0xBF, 0xBF ], // U+001FFFFF
[ 0xFC, 0x83, 0xBF, 0xBF, 0xBF, 0xBF ], // U+03FFFFFF
// Overlong representation of the NUL character
/* The following five sequences should also be rejected like malformed
UTF-8 sequences and should not be treated like the ASCII NUL
character. */
[ 0xC0, 0x80 ],
[ 0xE0, 0x80, 0x80 ],
[ 0xF0, 0x80, 0x80, 0x80 ],
[ 0xF8, 0x80, 0x80, 0x80, 0x80 ],
[ 0xFC, 0x80, 0x80, 0x80, 0x80, 0x80 ],
// Illegal code positions
/* The following UTF-8 sequences should be rejected like malformed
sequences, because they never represent valid ISO 10646 characters
and a UTF-8 decoder that accepts them might introduce security
problems comparable to overlong UTF-8 sequences. */
[ 0xED, 0xA0, 0x80 ], // U+D800
[ 0xED, 0xAD, 0xBF ], // U+DB7F
[ 0xED, 0xAE, 0x80 ], // U+DB80
[ 0xED, 0xAF, 0xBF ], // U+DBFF
[ 0xED, 0xB0, 0x80 ], // U+DC00
[ 0xED, 0xBE, 0x80 ], // U+DF80
[ 0xED, 0xBF, 0xBF ], // U+DFFF
];
static string[] sanitizedStrings =
[
"\uFFFD","\uFFFD",
"\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD"," \uFFFD ",
" \uFFFD ","\uFFFD\uFFFD\uFFFD","\uFFFD","\uFFFD"," \uFFFD "," \uFFFD ",
"\uFFFD","\uFFFD"," \uFFFD "," \uFFFD ","\uFFFD","\uFFFD"," \uFFFD ",
" \uFFFD ","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD",
"\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD\uFFFD","\uFFFD","\uFFFD",
"\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD"," \uFFFD ",
" \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD "," \uFFFD ",
" \uFFFD ","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD",
"\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD",
"\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD","\uFFFD",
];
// Make sure everything that should be valid, is
foreach(a;validStrings)
{
string s = cast(string)a;
assert(isValid(s),"Failed to validate: "~makeReadable(s));
}
// Make sure everything that shouldn't be valid, isn't
foreach(a;invalidStrings)
{
string s = cast(string)a;
assert(!isValid(s),"Incorrectly validated: "~makeReadable(s));
}
// Make sure we can sanitize everything bad
assert(invalidStrings.length == sanitizedStrings.length);
for(int i=0; i<invalidStrings.length; ++i)
{
string s = cast(string)invalidStrings[i];
string t = sanitize(s);
assert(isValid(t));
assert(t == sanitizedStrings[i]);
ubyte[] u = cast(ubyte[])t;
validStrings ~= u;
}
// Make sure all transcodings work in both directions, using both forward
// and reverse iteration
foreach(a; validStrings)
{
string s = cast(string)a;
string s2;
wstring ws, ws2;
dstring ds, ds2;
transcode(s,ws);
assert(isValid(ws));
transcode(ws,s2);
assert(s == s2);
transcode(s,ds);
assert(isValid(ds));
transcode(ds,s2);
assert(s == s2);
transcode(ws,s);
assert(isValid(s));
transcode(s,ws2);
assert(ws == ws2);
transcode(ws,ds);
assert(isValid(ds));
transcode(ds,ws2);
assert(ws == ws2);
transcode(ds,s);
assert(isValid(s));
transcode(s,ds2);
assert(ds == ds2);
transcode(ds,ws);
assert(isValid(ws));
transcode(ws,ds2);
assert(ds == ds2);
transcodeReverse(s,ws);
assert(isValid(ws));
transcodeReverse(ws,s2);
assert(s == s2);
transcodeReverse(s,ds);
assert(isValid(ds));
transcodeReverse(ds,s2);
assert(s == s2);
transcodeReverse(ws,s);
assert(isValid(s));
transcodeReverse(s,ws2);
assert(ws == ws2);
transcodeReverse(ws,ds);
assert(isValid(ds));
transcodeReverse(ds,ws2);
assert(ws == ws2);
transcodeReverse(ds,s);
assert(isValid(s));
transcodeReverse(s,ds2);
assert(ds == ds2);
transcodeReverse(ds,ws);
assert(isValid(ws));
transcodeReverse(ws,ds2);
assert(ds == ds2);
}
// Make sure the non-UTF encodings work too
{
auto s = "\u20AC100";
Windows1252String t;
transcode(s,t);
assert(t == cast(Windows1252Char[])[0x80, '1', '0', '0']);
string u;
transcode(s,u);
assert(s == u);
Latin1String v;
transcode(s,v);
assert(cast(string)v == "?100");
AsciiString w;
transcode(v,w);
assert(cast(string)w == "?100");
}
// Make sure we can count properly
{
assert(encodedLength!(char)('A') == 1);
assert(encodedLength!(char)('\u00E3') == 2);
assert(encodedLength!(char)('\u2028') == 3);
assert(encodedLength!(char)('\U0010FFF0') == 4);
assert(encodedLength!(wchar)('A') == 1);
assert(encodedLength!(wchar)('\U0010FFF0') == 2);
}
// Make sure we can write into mutable arrays
{
char[4] buffer;
auto n = encode(cast(dchar)'\u00E3',buffer);
assert(n == 2);
assert(buffer[0] == 0xC3);
assert(buffer[1] == 0xA3);
}
}
//=============================================================================
/** Special value returned by $(D safeDecode) */
enum dchar INVALID_SEQUENCE = cast(dchar) 0xFFFFFFFF;
template EncoderFunctions()
{
// Various forms of read
template ReadFromString()
{
bool canRead() { return s.length != 0; }
E peek() { return s[0]; }
E read() { E t = s[0]; s = s[1..$]; return t; }
}
template ReverseReadFromString()
{
bool canRead() { return s.length != 0; }
E peek() { return s[$-1]; }
E read() { E t = s[$-1]; s = s[0..$-1]; return t; }
}
// Various forms of Write
template WriteToString()
{
E[] s;
void write(E c) { s ~= c; }
}
template WriteToArray()
{
void write(E c) { array[0] = c; array = array[1..$]; }
}
deprecated template WriteToBuffer()
{
void write(E c) { buffer ~= c; }
}
template WriteToDelegate()
{
void write(E c) { dg(c); }
}
// Functions we will export
template EncodeViaWrite()
{
mixin encodeViaWrite;
void encode(dchar c) { encodeViaWrite(c); }
}
template SkipViaRead()
{
mixin skipViaRead;
void skip() { skipViaRead(); }
}
template DecodeViaRead()
{
mixin decodeViaRead;
dchar decode() { return decodeViaRead(); }
}
template SafeDecodeViaRead()
{
mixin safeDecodeViaRead;
dchar safeDecode() { return safeDecodeViaRead(); }
}
template DecodeReverseViaRead()
{
mixin decodeReverseViaRead;
dchar decodeReverse() { return decodeReverseViaRead(); }
}
// Encoding to different destinations
template EncodeToString()
{
mixin WriteToString;
mixin EncodeViaWrite;
}
template EncodeToArray()
{
mixin WriteToArray;
mixin EncodeViaWrite;
}
deprecated template EncodeToBuffer()
{
mixin WriteToBuffer;
mixin EncodeViaWrite;
}
template EncodeToDelegate()
{
mixin WriteToDelegate;
mixin EncodeViaWrite;
}
// Decoding functions
template SkipFromString()
{
mixin ReadFromString;
mixin SkipViaRead;
}
template DecodeFromString()
{
mixin ReadFromString;
mixin DecodeViaRead;
}
template SafeDecodeFromString()
{
mixin ReadFromString;
mixin SafeDecodeViaRead;
}
template DecodeReverseFromString()
{
mixin ReverseReadFromString;
mixin DecodeReverseViaRead;
}
//=========================================================================
// Below are the functions we will ultimately expose to the user
E[] encode(dchar c)
{
mixin EncodeToString e;
e.encode(c);
return e.s;
}
void encode(dchar c, ref E[] array)
{
mixin EncodeToArray e;
e.encode(c);
}
void encode(dchar c, void delegate(E) dg)
{
mixin EncodeToDelegate e;
e.encode(c);
}
void skip(ref const(E)[] s)
{
mixin SkipFromString e;
e.skip();
}
dchar decode(S)(ref S s)
{
mixin DecodeFromString e;
return e.decode();
}
dchar safeDecode(S)(ref S s)
{
mixin SafeDecodeFromString e;
return e.safeDecode();
}
dchar decodeReverse(ref const(E)[] s)
{
mixin DecodeReverseFromString e;
return e.decodeReverse();
}
}
//=========================================================================
struct CodePoints(E)
{
const(E)[] s;
this(const(E)[] s)
in
{
assert(isValid(s));
}
body
{
this.s = s;
}
int opApply(scope int delegate(ref dchar) dg)
{
int result = 0;
while (s.length != 0)
{
dchar c = decode(s);
result = dg(c);
if (result != 0) break;
}
return result;
}
int opApply(scope int delegate(ref size_t, ref dchar) dg)
{
size_t i = 0;
int result = 0;
while (s.length != 0)
{
size_t len = s.length;
dchar c = decode(s);
size_t j = i; // We don't want the delegate corrupting i
result = dg(j,c);
if (result != 0) break;
i += len - s.length;
}
return result;
}
int opApplyReverse(scope int delegate(ref dchar) dg)
{
int result = 0;
while (s.length != 0)
{
dchar c = decodeReverse(s);
result = dg(c);
if (result != 0) break;
}
return result;
}
int opApplyReverse(scope int delegate(ref size_t, ref dchar) dg)
{
int result = 0;
while (s.length != 0)
{
dchar c = decodeReverse(s);
size_t i = s.length;
result = dg(i,c);
if (result != 0) break;
}
return result;
}
}
struct CodeUnits(E)
{
E[] s;
this(dchar d)
in
{
assert(isValidCodePoint(d));
}
body
{
s = encode!(E)(d);
}
int opApply(scope int delegate(ref E) dg)
{
int result = 0;
foreach(E c;s)
{
result = dg(c);
if (result != 0) break;
}
return result;
}
int opApplyReverse(scope int delegate(ref E) dg)
{
int result = 0;
foreach_reverse(E c;s)
{
result = dg(c);
if (result != 0) break;
}
return result;
}
}
//=============================================================================
template EncoderInstance(E)
{
static assert(false,"Cannot instantiate EncoderInstance for type "
~ E.stringof);
}
//=============================================================================
// ASCII
//=============================================================================
/** Defines various character sets. */
enum AsciiChar : ubyte { init };
/// Ditto
alias immutable(AsciiChar)[] AsciiString;
template EncoderInstance(CharType : AsciiChar)
{
alias AsciiChar E;
alias AsciiString EString;
string encodingName()
{
return "ASCII";
}
bool canEncode(dchar c)
{
return c < 0x80;
}
bool isValidCodeUnit(AsciiChar c)
{
return c < 0x80;
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
return 1;
}
void encodeX(Range)(dchar c, Range r)
{
if (!canEncode(c)) c = '?';
r.write(cast(AsciiChar) c);
}
void encodeViaWrite()(dchar c)
{
if (!canEncode(c)) c = '?';
write(cast(AsciiChar)c);
}
void skipViaRead()()
{
read();
}
dchar decodeViaRead()()
{
return read;
}
dchar safeDecodeViaRead()()
{
dchar c = read;
return canEncode(c) ? c : INVALID_SEQUENCE;
}
dchar decodeReverseViaRead()()
{
return read;
}
EString replacementSequence()
{
return cast(EString)("?");
}
mixin EncoderFunctions;
}
//=============================================================================
// ISO-8859-1
//=============================================================================
/** Defines an Latin1-encoded character. */
enum Latin1Char : ubyte { init };
/**
Defines an Latin1-encoded string (as an array of $(D
immutable(Latin1Char))).
*/
alias immutable(Latin1Char)[] Latin1String; ///
template EncoderInstance(CharType : Latin1Char)
{
alias Latin1Char E;
alias Latin1String EString;
string encodingName()
{
return "ISO-8859-1";
}
bool canEncode(dchar c)
{
return c < 0x100;
}
bool isValidCodeUnit(Latin1Char c)
{
return true;
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
return 1;
}
void encodeViaWrite()(dchar c)
{
if (!canEncode(c)) c = '?';
write(cast(Latin1Char)c);
}
void skipViaRead()()
{
read();
}
dchar decodeViaRead()()
{
return read;
}
dchar safeDecodeViaRead()()
{
return read;
}
dchar decodeReverseViaRead()()
{
return read;
}
EString replacementSequence()
{
return cast(EString)("?");
}
mixin EncoderFunctions;
}
//=============================================================================
// WINDOWS-1252
//=============================================================================
/** Defines a Windows1252-encoded character. */
enum Windows1252Char : ubyte { init };
/**
Defines an Windows1252-encoded string (as an array of $(D
immutable(Windows1252Char))).
*/
alias immutable(Windows1252Char)[] Windows1252String; ///
template EncoderInstance(CharType : Windows1252Char)
{
alias Windows1252Char E;
alias Windows1252String EString;
string encodingName()
{
return "windows-1252";
}
immutable wstring charMap =
"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021"
"\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD"
"\uFFFD\u2018\u2019\u201C\u201D\u2022\u2103\u2014"
"\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178"
;
bool canEncode(dchar c)
{
if (c < 0x80 || (c >= 0xA0 && c < 0x100)) return true;
if (c >= 0xFFFD) return false;
foreach(wchar d;charMap) { if (c == d) return true; }
return false;
}
bool isValidCodeUnit(Windows1252Char c)
{
if (c < 0x80 || c >= 0xA0) return true;
return (charMap[c-0x80] != 0xFFFD);
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
return 1;
}
void encodeViaWrite()(dchar c)
{
if (c < 0x80 || (c >= 0xA0 && c < 0x100)) {}
else if (c >= 0xFFFD) { c = '?'; }
else
{
sizediff_t n = -1;
foreach (i, wchar d; charMap)
{
if (c == d)
{
n = i;
break;
}
}
c = n == -1 ? '?' : 0x80 + cast(dchar) n;
}
write(cast(Windows1252Char)c);
}
void skipViaRead()()
{
read();
}
dchar decodeViaRead()()
{
Windows1252Char c = read;
return (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c;
}
dchar safeDecodeViaRead()()
{
Windows1252Char c = read;
dchar d = (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c;
return d == 0xFFFD ? INVALID_SEQUENCE : d;
}
dchar decodeReverseViaRead()()
{
Windows1252Char c = read;
return (c >= 0x80 && c < 0xA0) ? charMap[c-0x80] : c;
}
EString replacementSequence()
{
return cast(EString)("?");
}
mixin EncoderFunctions;
}
//=============================================================================
// UTF-8
//=============================================================================
template EncoderInstance(CharType : char)
{
alias char E;
alias immutable(char)[] EString;
string encodingName()
{
return "UTF-8";
}
bool canEncode(dchar c)
{
return isValidCodePoint(c);
}
bool isValidCodeUnit(char c)
{
return (c < 0xC0 || (c >= 0xC2 && c < 0xF5));
}
immutable ubyte[128] tailTable =
[
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,4,4,4,4,5,5,6,0,
];
private int tails(char c)
in
{
assert(c >= 0x80);
}
body
{
return tailTable[c-0x80];
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c < 0x10000) return 3;
return 4;
}
void encodeViaWrite()(dchar c)
{
if (c < 0x80)
{
write(cast(char)c);
}
else if (c < 0x800)
{
write(cast(char)((c >> 6) + 0xC0));
write(cast(char)((c & 0x3F) + 0x80));
}
else if (c < 0x10000)
{
write(cast(char)((c >> 12) + 0xE0));
write(cast(char)(((c >> 6) & 0x3F) + 0x80));
write(cast(char)((c & 0x3F) + 0x80));
}
else
{
write(cast(char)((c >> 18) + 0xF0));
write(cast(char)(((c >> 12) & 0x3F) + 0x80));
write(cast(char)(((c >> 6) & 0x3F) + 0x80));
write(cast(char)((c & 0x3F) + 0x80));
}
}
void skipViaRead()()
{
auto c = read;
if (c < 0xC0) return;
int n = tails(cast(char) c);
for (size_t i=0; i<n; ++i)
{
read();
}
}
dchar decodeViaRead()()
{
dchar c = read;
if (c < 0xC0) return c;
int n = tails(cast(char) c);
c &= (1 << (6 - n)) - 1;
for (size_t i=0; i<n; ++i)
{
c = (c << 6) + (read & 0x3F);
}
return c;
}
dchar safeDecodeViaRead()()
{
dchar c = read;
if (c < 0x80) return c;
int n = tails(cast(char) c);
if (n == 0) return INVALID_SEQUENCE;
if (!canRead) return INVALID_SEQUENCE;
size_t d = peek;
bool err =
(
(c < 0xC2) // fail overlong 2-byte sequences
|| (c > 0xF4) // fail overlong 4-6-byte sequences
|| (c == 0xE0 && ((d & 0xE0) == 0x80)) // fail overlong 3-byte sequences
|| (c == 0xED && ((d & 0xE0) == 0xA0)) // fail surrogates
|| (c == 0xF0 && ((d & 0xF0) == 0x80)) // fail overlong 4-byte sequences
|| (c == 0xF4 && ((d & 0xF0) >= 0x90)) // fail code points > 0x10FFFF
);
c &= (1 << (6 - n)) - 1;
for (size_t i=0; i<n; ++i)
{
if (!canRead) return INVALID_SEQUENCE;
d = peek;
if ((d & 0xC0) != 0x80) return INVALID_SEQUENCE;
c = (c << 6) + (read & 0x3F);
}
return err ? INVALID_SEQUENCE : c;
}
dchar decodeReverseViaRead()()
{
dchar c = read;
if (c < 0x80) return c;
size_t shift = 0;
c &= 0x3F;
for (size_t i=0; i<4; ++i)
{
shift += 6;
auto d = read;
size_t n = tails(cast(char) d);
size_t mask = n == 0 ? 0x3F : (1 << (6 - n)) - 1;
c += ((d & mask) << shift);
if (n != 0) break;
}
return c;
}
EString replacementSequence()
{
return "\uFFFD";
}
mixin EncoderFunctions;
}
//=============================================================================
// UTF-16
//=============================================================================
template EncoderInstance(CharType : wchar)
{
alias wchar E;
alias immutable(wchar)[] EString;
string encodingName()
{
return "UTF-16";
}
bool canEncode(dchar c)
{
return isValidCodePoint(c);
}
bool isValidCodeUnit(wchar c)
{
return true;
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
return (c < 0x10000) ? 1 : 2;
}
void encodeViaWrite()(dchar c)
{
if (c < 0x10000)
{
write(cast(wchar)c);
}
else
{
size_t n = c - 0x10000;
write(cast(wchar)(0xD800 + (n >> 10)));
write(cast(wchar)(0xDC00 + (n & 0x3FF)));
}
}
void skipViaRead()()
{
wchar c = read;
if (c < 0xD800 || c >= 0xE000) return;
read();
}
dchar decodeViaRead()()
{
wchar c = read;
if (c < 0xD800 || c >= 0xE000) return cast(dchar)c;
wchar d = read;
c &= 0x3FF;
d &= 0x3FF;
return 0x10000 + (c << 10) + d;
}
dchar safeDecodeViaRead()()
{
wchar c = read;
if (c < 0xD800 || c >= 0xE000) return cast(dchar)c;
if (c >= 0xDC00) return INVALID_SEQUENCE;
if (!canRead) return INVALID_SEQUENCE;
wchar d = peek;
if (d < 0xDC00 || d >= 0xE000) return INVALID_SEQUENCE;
d = read;
c &= 0x3FF;
d &= 0x3FF;
return 0x10000 + (c << 10) + d;
}
dchar decodeReverseViaRead()()
{
wchar c = read;
if (c < 0xD800 || c >= 0xE000) return cast(dchar)c;
wchar d = read;
c &= 0x3FF;
d &= 0x3FF;
return 0x10000 + (d << 10) + c;
}
EString replacementSequence()
{
return "\uFFFD"w;
}
mixin EncoderFunctions;
}
//=============================================================================
// UTF-32
//=============================================================================
template EncoderInstance(CharType : dchar)
{
alias dchar E;
alias immutable(dchar)[] EString;
string encodingName()
{
return "UTF-32";
}
bool canEncode(dchar c)
{
return isValidCodePoint(c);
}
bool isValidCodeUnit(dchar c)
{
return isValidCodePoint(c);
}
size_t encodedLength(dchar c)
in
{
assert(canEncode(c));
}
body
{
return 1;
}
void encodeViaWrite()(dchar c)
{
write(c);
}
void skipViaRead()()
{
read();
}
dchar decodeViaRead()()
{
return cast(dchar)read;
}
dchar safeDecodeViaRead()()
{
dchar c = read;
return isValidCodePoint(c) ? c : INVALID_SEQUENCE;
}
dchar decodeReverseViaRead()()
{
return cast(dchar)read;
}
EString replacementSequence()
{
return "\uFFFD"d;
}
mixin EncoderFunctions;
}
//=============================================================================
// Below are forwarding functions which expose the function to the user
/**
Returns true if c is a valid code point
Note that this includes the non-character code points U+FFFE and U+FFFF,
since these are valid code points (even though they are not valid
characters).
Supercedes:
This function supercedes $(D std.utf.startsValidDchar()).
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code point to be tested
*/
bool isValidCodePoint(dchar c)
{
return c < 0xD800 || (c >= 0xE000 && c < 0x110000);
}
/**
Returns the name of an encoding.
The type of encoding cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding type.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Examples:
-----------------------------------
assert(encodingName!(Latin1Char) == "ISO-8859-1");
-----------------------------------
*/
string encodingName(T)()
{
return EncoderInstance!(T).encodingName;
}
unittest
{
assert(encodingName!(char) == "UTF-8");
assert(encodingName!(wchar) == "UTF-16");
assert(encodingName!(dchar) == "UTF-32");
assert(encodingName!(AsciiChar) == "ASCII");
assert(encodingName!(Latin1Char) == "ISO-8859-1");
assert(encodingName!(Windows1252Char) == "windows-1252");
}
/**
Returns true iff it is possible to represent the specifed codepoint
in the encoding.
The type of encoding cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding type.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Examples:
-----------------------------------
assert(canEncode!(Latin1Char)('A'));
-----------------------------------
*/
bool canEncode(E)(dchar c)
{
return EncoderInstance!(E).canEncode(c);
}
unittest
{
assert(!canEncode!(AsciiChar)('\u00A0'));
assert(canEncode!(Latin1Char)('\u00A0'));
assert(canEncode!(Windows1252Char)('\u20AC'));
assert(!canEncode!(Windows1252Char)('\u20AD'));
assert(!canEncode!(Windows1252Char)('\uFFFD'));
assert(!canEncode!(char)(cast(dchar)0x110000));
}
/**
Returns true if the code unit is legal. For example, the byte 0x80 would
not be legal in ASCII, because ASCII code units must always be in the range
0x00 to 0x7F.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code unit to be tested
*/
bool isValidCodeUnit(E)(E c)
{
return EncoderInstance!(E).isValidCodeUnit(c);
}
unittest
{
assert(!isValidCodeUnit(cast(AsciiChar)0xA0));
assert( isValidCodeUnit(cast(Windows1252Char)0x80));
assert(!isValidCodeUnit(cast(Windows1252Char)0x81));
assert(!isValidCodeUnit(cast(char)0xC0));
assert(!isValidCodeUnit(cast(char)0xFF));
assert( isValidCodeUnit(cast(wchar)0xD800));
assert(!isValidCodeUnit(cast(dchar)0xD800));
}
/**
Returns true if the string is encoded correctly
Supercedes:
This function supercedes std.utf.validate(), however note that this
function returns a bool indicating whether the input was valid or not,
wheras the older funtion would throw an exception.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be tested
*/
bool isValid(E)(const(E)[] s)
{
return s.length == validLength(s);
}
unittest
{
assert(isValid("\u20AC100"));
}
/**
Returns the length of the longest possible substring, starting from
the first code unit, which is validly encoded.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be tested
*/
size_t validLength(E)(const(E)[] s)
{
size_t result, before = void;
while ((before = s.length) > 0)
{
if (EncoderInstance!(E).safeDecode(s) == INVALID_SEQUENCE)
break;
result += before - s.length;
}
return result;
}
/**
Sanitizes a string by replacing malformed code unit sequences with valid
code unit sequences. The result is guaranteed to be valid for this encoding.
If the input string is already valid, this function returns the original,
otherwise it constructs a new string by replacing all illegal code unit
sequences with the encoding's replacement character, Invalid sequences will
be replaced with the Unicode replacement character (U+FFFD) if the
character repertoire contains it, otherwise invalid sequences will be
replaced with '?'.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be sanitized
*/
immutable(E)[] sanitize(E)(immutable(E)[] s)
{
size_t n = validLength(s);
if (n == s.length) return s;
auto repSeq = EncoderInstance!(E).replacementSequence;
// Count how long the string needs to be.
// Overestimating is not a problem
size_t len = s.length;
const(E)[] t = s[n..$];
while (t.length != 0)
{
dchar c = EncoderInstance!(E).safeDecode(t);
assert(c == INVALID_SEQUENCE);
len += repSeq.length;
t = t[validLength(t)..$];
}
// Now do the write
E[] array = new E[len];
array[0..n] = s[0..n];
size_t offset = n;
t = s[n..$];
while (t.length != 0)
{
dchar c = EncoderInstance!(E).safeDecode(t);
assert(c == INVALID_SEQUENCE);
array[offset..offset+repSeq.length] = repSeq[];
offset += repSeq.length;
n = validLength(t);
array[offset..offset+n] = t[0..n];
offset += n;
t = t[n..$];
}
return cast(immutable(E)[])array[0..offset];
}
unittest
{
assert(sanitize("hello \xF0\x80world") == "hello \xEF\xBF\xBDworld");
}
/**
Returns the length of the first encoded sequence.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be sliced
*/
size_t firstSequence(E)(const(E)[] s)
in
{
assert(s.length != 0);
const(E)[] u = s;
assert(safeDecode(u) != INVALID_SEQUENCE);
}
body
{
auto before = s.length;
EncoderInstance!(E).skip(s);
return before - s.length;
}
unittest
{
assert(firstSequence("\u20AC1000") == "\u20AC".length);
}
/**
Returns the length the last encoded sequence.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be sliced
*/
size_t lastSequence(E)(const(E)[] s)
in
{
assert(s.length != 0);
assert(isValid(s));
}
body
{
const(E)[] t = s;
EncoderInstance!(E).decodeReverse(s);
return t.length - s.length;
}
unittest
{
assert(lastSequence("1000\u20AC") == "\u20AC".length);
}
/**
Returns the array index at which the (n+1)th code point begins.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Supercedes:
This function supercedes std.utf.toUTFindex().
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be counted
*/
sizediff_t index(E)(const(E)[] s,int n)
in
{
assert(isValid(s));
assert(n >= 0);
}
body
{
const(E)[] t = s;
for (size_t i=0; i<n; ++i) EncoderInstance!(E).skip(s);
return t.length - s.length;
}
unittest
{
assert(index("\u20AC100",1) == 3);
}
/**
Decodes a single code point.
This function removes one or more code units from the start of a string,
and returns the decoded code point which those code units represent.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Supercedes:
This function supercedes std.utf.decode(), however, note that the
function codePoints() supercedes it more conveniently.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string whose first code point is to be decoded
*/
dchar decode(S)(ref S s)
in
{
assert(s.length != 0);
auto u = s;
assert(safeDecode(u) != INVALID_SEQUENCE);
}
body
{
return EncoderInstance!(typeof(s[0])).decode(s);
}
/**
Decodes a single code point from the end of a string.
This function removes one or more code units from the end of a string,
and returns the decoded code point which those code units represent.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string whose first code point is to be decoded
*/
dchar decodeReverse(E)(ref const(E)[] s)
in
{
assert(s.length != 0);
assert(isValid(s));
}
body
{
return EncoderInstance!(E).decodeReverse(s);
}
/**
Decodes a single code point. The input does not have to be valid.
This function removes one or more code units from the start of a string,
and returns the decoded code point which those code units represent.
This function will accept an invalidly encoded string as input.
If an invalid sequence is found at the start of the string, this
function will remove it, and return the value INVALID_SEQUENCE.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string whose first code point is to be decoded
*/
dchar safeDecode(S)(ref S s)
in
{
assert(s.length != 0);
}
body
{
return EncoderInstance!(typeof(s[0])).safeDecode(s);
}
/**
Returns the number of code units required to encode a single code point.
The input to this function MUST be a valid code point.
This is enforced by the function's in-contract.
The type of the output cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding as a template parameter.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code point to be encoded
*/
size_t encodedLength(E)(dchar c)
in
{
assert(isValidCodePoint(c));
}
body
{
return EncoderInstance!(E).encodedLength(c);
}
/**
Encodes a single code point.
This function encodes a single code point into one or more code units.
It returns a string containing those code units.
The input to this function MUST be a valid code point.
This is enforced by the function's in-contract.
The type of the output cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding as a template parameter.
Supercedes:
This function supercedes std.utf.encode(), however, note that the
function codeUnits() supercedes it more conveniently.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code point to be encoded
*/
E[] encode(E)(dchar c)
in
{
assert(isValidCodePoint(c));
}
body
{
return EncoderInstance!(E).encode(c);
}
/**
Encodes a single code point into an array.
This function encodes a single code point into one or more code units
The code units are stored in a user-supplied fixed-size array,
which must be passed by reference.
The input to this function MUST be a valid code point.
This is enforced by the function's in-contract.
The type of the output cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding as a template parameter.
Supercedes:
This function supercedes std.utf.encode(), however, note that the
function codeUnits() supercedes it more conveniently.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code point to be encoded
Returns:
the number of code units written to the array
*/
size_t encode(E)(dchar c, E[] array)
in
{
assert(isValidCodePoint(c));
}
body
{
E[] t = array;
EncoderInstance!(E).encode(c,t);
return array.length - t.length;
}
// /**
// * Encodes a single code point into a Buffer.
// *
// * This function encodes a single code point into one or more code units
// * The code units are stored in a growable buffer.
// *
// * The input to this function MUST be a valid code point.
// * This is enforced by the function's in-contract.
// *
// * The type of the output cannot be deduced. Therefore, it is necessary to
// * explicitly specify the encoding as a template parameter.
// *
// * Supercedes:
// * This function supercedes std.utf.encode(), however, note that the
// * function codeUnits() supercedes it more conveniently.
// *
// * Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
// *
// * Params:
// * c = the code point to be encoded
// */
// deprecated void encode(E)(dchar c, ref Buffer!(E) buffer)
// in
// {
// assert(isValidCodePoint(c));
// }
// body
// {
// EncoderInstance!(E).encode(c,buffer);
// }
/*
Encodes $(D c) in units of type $(D E) and writes the result to the
output range $(D R). Returns the number of $(D E)s written.
*/
size_t encode(E, R)(dchar c, R range)
{
static if (is(Unqual!E == char))
{
if (c <= 0x7F)
{
range.put(cast(char) c);
return 1;
}
if (c <= 0x7FF)
{
range.put(cast(char)(0xC0 | (c >> 6)));
range.put(cast(char)(0x80 | (c & 0x3F)));
return 2;
}
if (c <= 0xFFFF)
{
range.put(cast(char)(0xE0 | (c >> 12)));
range.put(cast(char)(0x80 | ((c >> 6) & 0x3F)));
range.put(cast(char)(0x80 | (c & 0x3F)));
return 3;
}
if (c <= 0x10FFFF)
{
range.put(cast(char)(0xF0 | (c >> 18)));
range.put(cast(char)(0x80 | ((c >> 12) & 0x3F)));
range.put(cast(char)(0x80 | ((c >> 6) & 0x3F)));
range.put(cast(char)(0x80 | (c & 0x3F)));
return 4;
}
else
{
assert(0);
}
}
else static if (is(Unqual!E == wchar))
{
if (c <= 0xFFFF)
{
r.put(cast(wchar) c);
return 1;
}
r.put(cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800));
r.put(cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00));
return 2;
}
else static if (is(Unqual!E == dchar))
{
r.put(c);
return 1;
}
else
{
assert(0);
}
}
/**
Encodes a single code point to a delegate.
This function encodes a single code point into one or more code units.
The code units are passed one at a time to the supplied delegate.
The input to this function MUST be a valid code point.
This is enforced by the function's in-contract.
The type of the output cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding as a template parameter.
Supercedes:
This function supercedes std.utf.encode(), however, note that the
function codeUnits() supercedes it more conveniently.
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
c = the code point to be encoded
*/
void encode(E)(dchar c, void delegate(E) dg)
in
{
assert(isValidCodePoint(c));
}
body
{
EncoderInstance!(E).encode(c,dg);
}
/**
Returns a foreachable struct which can bidirectionally iterate over all
code points in a string.
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
You can foreach either
with or without an index. If an index is specified, it will be initialized
at each iteration with the offset into the string at which the code point
begins.
Supercedes:
This function supercedes std.utf.decode().
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the string to be decoded
Examples:
--------------------------------------------------------
string s = "hello world";
foreach(c;codePoints(s))
{
// do something with c (which will always be a dchar)
}
--------------------------------------------------------
Note that, currently, foreach(c:codePoints(s)) is superior to foreach(c;s)
in that the latter will fall over on encountering U+FFFF.
*/
CodePoints!(E) codePoints(E)(immutable(E)[] s)
in
{
assert(isValid(s));
}
body
{
return CodePoints!(E)(s);
}
unittest
{
string s = "hello";
string t;
foreach(c;codePoints(s))
{
t ~= cast(char)c;
}
assert(s == t);
}
/**
Returns a foreachable struct which can bidirectionally iterate over all
code units in a code point.
The input to this function MUST be a valid code point.
This is enforced by the function's in-contract.
The type of the output cannot be deduced. Therefore, it is necessary to
explicitly specify the encoding type in the template parameter.
Supercedes:
This function supercedes std.utf.encode().
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
d = the code point to be encoded
Examples:
--------------------------------------------------------
dchar d = '\u20AC';
foreach(c;codeUnits!(char)(d))
{
writefln("%X",c)
}
// will print
// E2
// 82
// AC
--------------------------------------------------------
*/
CodeUnits!(E) codeUnits(E)(dchar c)
in
{
assert(isValidCodePoint(c));
}
body
{
return CodeUnits!(E)(c);
}
unittest
{
char[] a;
foreach(c;codeUnits!(char)(cast(dchar)'\u20AC'))
{
a ~= c;
}
assert(a.length == 3);
assert(a[0] == 0xE2);
assert(a[1] == 0x82);
assert(a[2] == 0xAC);
}
/**
Encodes $(D c) in units of type $(D E) and writes the result to the
output range $(D R). Returns the number of $(D E)s written.
*/
size_t encode(Tgt, Src, R)(in Src[] s, R range)
{
size_t result;
foreach (c; s)
{
result += encode!(Tgt)(c, range);
}
return result;
}
/**
Convert a string from one encoding to another. (See also to!() below).
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Supercedes:
This function supercedes std.utf.toUTF8(), std.utf.toUTF16() and
std.utf.toUTF32()
(but note that to!() supercedes it more conveniently).
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
s = the source string
r = the destination string
Examples:
--------------------------------------------------------
wstring ws;
transcode("hello world",ws);
// transcode from UTF-8 to UTF-16
Latin1String ls;
transcode(ws, ls);
// transcode from UTF-16 to ISO-8859-1
--------------------------------------------------------
*/
void transcode(Src,Dst)(immutable(Src)[] s,out immutable(Dst)[] r)
in
{
assert(isValid(s));
}
body
{
static if(is(Src==Dst))
{
r = s;
}
else static if(is(Src==AsciiChar))
{
transcode!(char,Dst)(cast(string)s,r);
}
else
{
const(Src)[] t = s;
while (t.length != 0)
{
r ~= encode!(Dst)(decode(t));
}
}
}
/*
Convert a string from one encoding to another. (See also transcode() above).
The input to this function MUST be validly encoded.
This is enforced by the function's in-contract.
Supercedes:
This function supercedes std.utf.toUTF8(), std.utf.toUTF16() and
std.utf.toUTF32().
Standards: Unicode 5.0, ASCII, ISO-8859-1, WINDOWS-1252
Params:
Dst = the destination encoding type
s = the source string
Examples:
-----------------------------------------------------------------------------
auto ws = to!(wchar)("hello world"); // transcode from UTF-8 to UTF-16
auto ls = to!(Latin1Char)(ws); // transcode from UTF-16 to ISO-8859-1
-----------------------------------------------------------------------------
*/
// TODO: Commented out for no - to be moved to std.conv
// Dst to(Dst,Src)(immutable(Src)[] s)
// in
// {
// assert(isValid(s));
// }
// body
// {
// Dst r;
// transcode(s,r);
// return r;
// }
//=============================================================================
/** The base class for exceptions thrown by this module */
class EncodingException : Exception { this(string msg) { super(msg); } }
class UnrecognizedEncodingException : EncodingException
{
private this(string msg) { super(msg); }
}
/** Abstract base class of all encoding schemes */
abstract class EncodingScheme
{
/**
* Registers a subclass of EncodingScheme.
*
* This function allows user-defined subclasses of EncodingScheme to
* be declared in other modules.
*
* Examples:
* ----------------------------------------------
* class Amiga1251 : EncodingScheme
* {
* shared static this()
* {
* EncodingScheme.register("path.to.Amiga1251");
* }
* }
* ----------------------------------------------
*/
static void register(string className)
{
auto scheme = cast(EncodingScheme)ClassInfo.find(className).create();
if (scheme is null)
throw new EncodingException("Unable to create class "~className);
foreach(encodingName;scheme.names())
{
supported[toLower(encodingName)] = className;
}
}
/**
* Obtains a subclass of EncodingScheme which is capable of encoding
* and decoding the named encoding scheme.
*
* This function is only aware of EncodingSchemes which have been
* registered with the register() function.
*
* Examples:
* ---------------------------------------------------
* auto scheme = EncodingScheme.create("Amiga-1251");
* ---------------------------------------------------
*/
static EncodingScheme create(string encodingName)
{
auto p = std.string.toLower(encodingName) in supported;
if (p is null)
throw new EncodingException("Unrecognized Encoding: "~encodingName);
string className = *p;
auto scheme = cast(EncodingScheme)ClassInfo.find(className).create();
if (scheme is null) throw new EncodingException("Unable to create class "~className);
return scheme;
}
const
{
/**
* Returns the standard name of the encoding scheme
*/
abstract override string toString();
/**
* Returns an array of all known names for this encoding scheme
*/
abstract string[] names();
/**
* Returns true if the character c can be represented
* in this encoding scheme.
*/
abstract bool canEncode(dchar c);
/**
* Returns the number of ubytes required to encode this code point.
*
* The input to this function MUST be a valid code point.
*
* Params:
* c = the code point to be encoded
*
* Returns:
* the number of ubytes required.
*/
abstract size_t encodedLength(dchar c);
/**
* Encodes a single code point into a user-supplied, fixed-size buffer.
*
* This function encodes a single code point into one or more ubytes.
* The supplied buffer must be code unit aligned.
* (For example, UTF-16LE or UTF-16BE must be wchar-aligned,
* UTF-32LE or UTF-32BE must be dchar-aligned, etc.)
*
* The input to this function MUST be a valid code point.
*
* Params:
* c = the code point to be encoded
*
* Returns:
* the number of ubytes written.
*/
abstract size_t encode(dchar c, ubyte[] buffer);
/**
* Decodes a single code point.
*
* This function removes one or more ubytes from the start of an array,
* and returns the decoded code point which those ubytes represent.
*
* The input to this function MUST be validly encoded.
*
* Params:
* s = the array whose first code point is to be decoded
*/
abstract dchar decode(ref const(ubyte)[] s);
/**
* Decodes a single code point. The input does not have to be valid.
*
* This function removes one or more ubytes from the start of an array,
* and returns the decoded code point which those ubytes represent.
*
* This function will accept an invalidly encoded array as input.
* If an invalid sequence is found at the start of the string, this
* function will remove it, and return the value INVALID_SEQUENCE.
*
* Params:
* s = the array whose first code point is to be decoded
*/
abstract dchar safeDecode(ref const(ubyte)[] s);
/**
* Returns the sequence of ubytes to be used to represent
* any character which cannot be represented in the encoding scheme.
*
* Normally this will be a representation of some substitution
* character, such as U+FFFD or '?'.
*/
abstract immutable(ubyte)[] replacementSequence();
}
/**
* Returns true if the array is encoded correctly
*
* Params:
* s = the array to be tested
*/
bool isValid(const(ubyte)[] s)
{
while (s.length != 0)
{
dchar d = safeDecode(s);
if (d == INVALID_SEQUENCE)
return false;
}
return true;
}
/**
* Returns the length of the longest possible substring, starting from
* the first element, which is validly encoded.
*
* Params:
* s = the array to be tested
*/
size_t validLength(const(ubyte)[] s)
{
const(ubyte)[] r = s;
const(ubyte)[] t = s;
while (s.length != 0)
{
if (safeDecode(s) == INVALID_SEQUENCE) break;
t = s;
}
return r.length - t.length;
}
/**
* Sanitizes an array by replacing malformed ubyte sequences with valid
* ubyte sequences. The result is guaranteed to be valid for this
* encoding scheme.
*
* If the input array is already valid, this function returns the
* original, otherwise it constructs a new array by replacing all illegal
* sequences with the encoding scheme's replacement sequence.
*
* Params:
* s = the string to be sanitized
*/
immutable(ubyte)[] sanitize(immutable(ubyte)[] s)
{
auto n = validLength(s);
if (n == s.length) return s;
auto repSeq = replacementSequence;
// Count how long the string needs to be.
// Overestimating is not a problem
auto len = s.length;
const(ubyte)[] t = s[n..$];
while (t.length != 0)
{
dchar c = safeDecode(t);
assert(c == INVALID_SEQUENCE);
len += repSeq.length;
t = t[validLength(t)..$];
}
// Now do the write
ubyte[] array = new ubyte[len];
array[0..n] = s[0..n];
auto offset = n;
t = s[n..$];
while (t.length != 0)
{
dchar c = safeDecode(t);
assert(c == INVALID_SEQUENCE);
array[offset..offset+repSeq.length] = repSeq[];
offset += repSeq.length;
n = validLength(t);
array[offset..offset+n] = t[0..n];
offset += n;
t = t[n..$];
}
return cast(immutable(ubyte)[])array[0..offset];
}
/**
* Returns the length of the first encoded sequence.
*
* The input to this function MUST be validly encoded.
* This is enforced by the function's in-contract.
*
* Params:
* s = the array to be sliced
*/
size_t firstSequence(const(ubyte)[] s)
in
{
assert(s.length != 0);
const(ubyte)[] u = s;
assert(safeDecode(u) != INVALID_SEQUENCE);
}
body
{
const(ubyte)[] t = s;
decode(s);
return t.length - s.length;
}
/**
* Returns the total number of code points encoded in a ubyte array.
*
* The input to this function MUST be validly encoded.
* This is enforced by the function's in-contract.
*
* Params:
* s = the string to be counted
*/
size_t count(const(ubyte)[] s)
in
{
assert(isValid(s));
}
body
{
size_t n = 0;
while (s.length != 0)
{
decode(s);
++n;
}
return n;
}
/**
* Returns the array index at which the (n+1)th code point begins.
*
* The input to this function MUST be validly encoded.
* This is enforced by the function's in-contract.
*
* Params:
* s = the string to be counted
*/
sizediff_t index(const(ubyte)[] s, size_t n)
in
{
assert(isValid(s));
assert(n >= 0);
}
body
{
const(ubyte)[] t = s;
for (size_t i=0; i<n; ++i) decode(s);
return t.length - s.length;
}
__gshared string[string] supported;
}
/**
EncodingScheme to handle ASCII
This scheme recognises the following names:
"ANSI_X3.4-1968",
"ANSI_X3.4-1986",
"ASCII",
"IBM367",
"ISO646-US",
"ISO_646.irv:1991",
"US-ASCII",
"cp367",
"csASCII"
"iso-ir-6",
"us"
*/
class EncodingSchemeASCII : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeASCII");
}
const
{
override string[] names()
{
return
[
cast(string)
"ANSI_X3.4-1968",
"ANSI_X3.4-1986",
"ASCII",
"IBM367",
"ISO646-US",
"ISO_646.irv:1991",
"US-ASCII",
"cp367",
"csASCII"
"iso-ir-6",
"us"
];
}
override string toString()
{
return "ASCII";
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(AsciiChar)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(AsciiChar)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(AsciiChar[])buffer;
return std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
{
auto t = cast(const(AsciiChar)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
{
auto t = cast(const(AsciiChar)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"?";
}
}
}
/**
EncodingScheme to handle Latin-1
This scheme recognises the following names:
"CP819",
"IBM819",
"ISO-8859-1",
"ISO_8859-1",
"ISO_8859-1:1987",
"csISOLatin1",
"iso-ir-100",
"l1",
"latin1"
*/
class EncodingSchemeLatin1 : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeLatin1");
}
const
{
override string[] names()
{
return
[
cast(string)
"CP819",
"IBM819",
"ISO-8859-1",
"ISO_8859-1",
"ISO_8859-1:1987",
"csISOLatin1",
"iso-ir-100",
"l1",
"latin1"
];
}
override string toString()
{
return "ISO-8859-1";
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(Latin1Char)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(Latin1Char)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(Latin1Char[])buffer;
return std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
{
auto t = cast(const(Latin1Char)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
{
auto t = cast(const(Latin1Char)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"?";
}
}
}
/**
EncodingScheme to handle Windows-1252
This scheme recognises the following names:
"windows-1252"
*/
class EncodingSchemeWindows1252 : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeWindows1252");
}
const
{
override string[] names()
{
return
[
cast(string)
"windows-1252"
];
}
override string toString()
{
return "windows-1252";
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(Windows1252Char)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(Windows1252Char)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(Windows1252Char[])buffer;
return std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
{
auto t = cast(const(Windows1252Char)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
{
auto t = cast(const(Windows1252Char)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"?";
}
}
}
/**
EncodingScheme to handle UTF-8
This scheme recognises the following names:
"UTF-8"
*/
class EncodingSchemeUtf8 : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeUtf8");
}
const
{
override string[] names()
{
return
[
cast(string)
"UTF-8"
];
}
override string toString()
{
return "UTF-8";
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(char)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(char)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(char[])buffer;
return std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
{
auto t = cast(const(char)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
{
auto t = cast(const(char)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"\uFFFD";
}
}
}
/**
EncodingScheme to handle UTF-16 in native byte order
This scheme recognises the following names:
"UTF-16LE" (little-endian architecture only)
"UTF-16BE" (big-endian architecture only)
*/
class EncodingSchemeUtf16Native : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeUtf16Native");
}
const
{
version(LittleEndian) { enum string NAME = "UTF-16LE"; }
version(BigEndian) { enum string NAME = "UTF-16BE"; }
override string[] names()
{
return [ NAME ];
}
override string toString()
{
return NAME;
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(wchar)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(wchar)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(wchar[])buffer;
return wchar.sizeof * std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
in
{
assert((s.length & 1) == 0);
}
body
{
auto t = cast(const(wchar)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
in
{
assert((s.length & 1) == 0);
}
body
{
auto t = cast(const(wchar)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"\uFFFD"w;
}
}
}
/**
EncodingScheme to handle UTF-32 in native byte order
This scheme recognises the following names:
"UTF-32LE" (little-endian architecture only)
"UTF-32BE" (big-endian architecture only)
*/
class EncodingSchemeUtf32Native : EncodingScheme
{
shared static this()
{
EncodingScheme.register("std.encoding.EncodingSchemeUtf32Native");
}
const
{
version(LittleEndian) { enum string NAME = "UTF-32LE"; }
version(BigEndian) { enum string NAME = "UTF-32BE"; }
override string[] names()
{
return [ NAME ];
}
override string toString()
{
return NAME;
}
override bool canEncode(dchar c)
{
return std.encoding.canEncode!(dchar)(c);
}
override size_t encodedLength(dchar c)
{
return std.encoding.encodedLength!(dchar)(c);
}
override size_t encode(dchar c, ubyte[] buffer)
{
auto r = cast(dchar[])buffer;
return dchar.sizeof * std.encoding.encode(c,r);
}
override dchar decode(ref const(ubyte)[] s)
in
{
assert((s.length & 3) == 0);
}
body
{
auto t = cast(const(dchar)[]) s;
dchar c = std.encoding.decode(t);
s = s[$-t.length..$];
return c;
}
override dchar safeDecode(ref const(ubyte)[] s)
in
{
assert((s.length & 3) == 0);
}
body
{
auto t = cast(const(dchar)[]) s;
dchar c = std.encoding.safeDecode(t);
s = s[$-t.length..$];
return c;
}
override immutable(ubyte)[] replacementSequence()
{
return cast(immutable(ubyte)[])"\uFFFD"d;
}
}
}
//=============================================================================
// Helper functions
version(unittest)
{
void transcodeReverse(Src,Dst)(immutable(Src)[] s, out immutable(Dst)[] r)
{
static if(is(Src==Dst))
{
return s;
}
else static if(is(Src==AsciiChar))
{
transcodeReverse!(char,Dst)(cast(string)s,r);
}
else
{
foreach_reverse(d;codePoints(s))
{
foreach_reverse(c;codeUnits!(Dst)(d))
{
r = c ~ r;
}
}
}
}
string makeReadable(string s)
{
string r = "\"";
foreach(char c;s)
{
if (c >= 0x20 && c < 0x80)
{
r ~= c;
}
else
{
r ~= "\\x";
r ~= toHexDigit(c >> 4);
r ~= toHexDigit(c);
}
}
r ~= "\"";
return r;
}
string makeReadable(wstring s)
{
string r = "\"";
foreach(wchar c;s)
{
if (c >= 0x20 && c < 0x80)
{
r ~= cast(char) c;
}
else
{
r ~= "\\u";
r ~= toHexDigit(c >> 12);
r ~= toHexDigit(c >> 8);
r ~= toHexDigit(c >> 4);
r ~= toHexDigit(c);
}
}
r ~= "\"w";
return r;
}
string makeReadable(dstring s)
{
string r = "\"";
foreach(dchar c; s)
{
if (c >= 0x20 && c < 0x80)
{
r ~= cast(char) c;
}
else if (c < 0x10000)
{
r ~= "\\u";
r ~= toHexDigit(c >> 12);
r ~= toHexDigit(c >> 8);
r ~= toHexDigit(c >> 4);
r ~= toHexDigit(c);
}
else
{
r ~= "\\U00";
r ~= toHexDigit(c >> 20);
r ~= toHexDigit(c >> 16);
r ~= toHexDigit(c >> 12);
r ~= toHexDigit(c >> 8);
r ~= toHexDigit(c >> 4);
r ~= toHexDigit(c);
}
}
r ~= "\"d";
return r;
}
char toHexDigit(int n)
{
return "0123456789ABCDEF"[n & 0xF];
}
}
|