1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101
|
unit Unicode;
// Version 3.1.2
//
//------------------------------------------------------------------------------------------------------------------------------------------
// This unit contains routines and classes to manage and work with Unicode/WideString strings.
//
// Unicode.pas is released under the MIT license:
// Copyright (c) 1999-2005 Mike Lischke (support@soft-gems.net, www.soft-gems.net).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// You are asked to give the author(s) the due credit. This means that you acknowledge the work of the author(s)
// in the product documentation, about box, help or wherever a prominent place is.
//
//----------------------------------------------------------------------------------------------------------------------
//
// You need Delphi 4 or higher to compile this code.
//
// Publicly available low level functions are all preceded by "Unicode..." (e.g.
// in UnicodeToUpper) while the high level functions use the Str... or Wide...
// naming scheme (e.g. StrLICompW and WideUpperCase).
//
// The normalization implementation in this unit has successfully and completely passed the
// official normative conformance testing as of Annex 9 in Technical Report #15
// (Unicode Standard Annex #15, http://www.unicode.org/unicode/reports/tr15, from 2000-08-31).
//
//------------------------------------------------------------------------------------------------------------------------------------------
//
// January 2007
// - Not really a final bug fix but temporary: case data for large and small latin letter i is wrong. The data in memory
// is once corrected to compensate for that.
// September 2006
// - Added ccSeparatorParagraph to white space check function.
// June 2006:
// - Added decimal digits to the check for hex digits.
// October 2004:
// - Code review
// 29-NOV-2001:
// - bug fix
// 06-JUN-2001:
// - small changes
// 28-APR-2001:
// - bug fixes
// 05-APR-2001:
// - bug fixes
// 23-MAR-2001:
// - WideSameText
// - small changes
// 10-FEB-2001:
// - bug fix in StringToWideStringEx and WideStringToStringEx
// 05-FEB-2001:
// - TWideStrings.GetSeparatedText changed (no separator anymore after the last line)
// 29-JAN-2001:
// - PrepareUnicodeData
// - LoadInProgress critical section is now created at init time to avoid critical thread races
// - bug fixes
// 26-JAN-2001:
// - ExpandANSIString
// - TWideStrings.SaveUnicode is by default True now
// 20..21-JAN-2001:
// - StrUpperW, StrLowerW and StrTitleW removed because they potentially would need
// a reallocation to work correctly (use the WideString versions instead)
// - further improvements related to internal data
// - introduced TUnicodeBlock
// - CodeBlockFromChar improved
// 07-JAN-2001:
// optimized access to character properties, combining class etc.
// 06-JAN-2001:
// TWideStrings and TWideStringList improved
// APR-DEC 2000: versions 2.1 - 2.6
// - preparation for public rlease
// - additional conversion routines
// - JCL compliance
// - character properties unified
// - character properties data and lookup improvements
// - reworked Unicode data resource file
// - improved simple string comparation routines (StrCompW, StrLCompW etc., include surrogate fix)
// - special case folding data for language neutral case insensitive comparations included
// - optimized decomposition
// - composition and normalization support
// - normalization conformance tests applied
// - bug fixes
// FEB-MAR 2000: version 2.0
// - Unicode regular expressions (URE) search class (TURESearch)
// - generic search engine base class for both the Boyer-Moore and the RE search class
// - whole word only search in UTBM, bug fixes in UTBM
// - string decompositon (including hangul)
// OCT/99 - JAN/2000: version 1.0
// - basic Unicode implementation, more than 100 WideString/UCS2Char and UCS4Char core functions
// - TWideStrings and TWideStringList classes
// - Unicode Tuned Boyer-Moore search class (TUTBMSearch)
// - low and high level Unicode/Wide* functions
// - low level Unicode UCS4Char data import and functions
// - helper functions
//
//------------------------------------------------------------------------------------------------------------------------------------------
// Open issues:
// - Yet to do things in the URE class are:
// - check all character classes if they match correctly
// - optimize rebuild of DFA (build only when pattern changes)
// - set flag parameter of ExecuteURE
// - add \d any decimal digit
// \D any character that is not a decimal digit
// \s any whitespace character
// \S any character that is not a whitespace character
// \w any "word" character
// \W any "non-word" character
// - The wide string classes still compare text with functions provided by the
// particular system. This works usually fine under WinNT/W2K (although also
// there are limitations like maximum text lengths). Under Win9x conversions
// from and to MBCS are necessary which are bound to a particular locale and
// so very limited in general use. These comparisons should be changed so that
// the code in this unit is used.
//------------------------------------------------------------------------------------------------------------------------------------------
interface
{$booleval off} // Use fastest possible boolean evaluation.
{$i Compilers.inc}
{$ifdef COMPILER_7_UP}
// For some things to work we need code, which is classified as being unsafe for .NET.
{$warn UNSAFE_TYPE off}
{$warn UNSAFE_CAST off}
{$warn UNSAFE_CODE off}
{$endif COMPILER_7_UP}
uses
Windows, Classes;
const
// Definitions of often used characters:
// Note: Use them only for tests of a certain character not to determine character
// classes (like white spaces) as in Unicode are often many code points defined
// being in a certain class. Hence your best option is to use the various
// UnicodeIs* functions.
WideNull = WideChar(#0);
WideTabulator = WideChar(#9);
WideSpace = WideChar(#32);
// logical line breaks
WideLF = WideChar(#10);
WideLineFeed = WideChar(#10);
WideVerticalTab = WideChar(#11);
WideFormFeed = WideChar(#12);
WideCR = WideChar(#13);
WideCarriageReturn = WideChar(#13);
WideCRLF: WideString = #13#10;
WideLineSeparator = WideChar($2028);
WideParagraphSeparator = WideChar($2029);
// byte order marks for Unicode files
// Unicode text files (in UTF-16 format) should contain $FFFE as first character to
// identify such a file clearly. Depending on the system where the file was created
// on this appears either in big endian or little endian style.
BOM_LSB_FIRST = WideChar($FEFF);
BOM_MSB_FIRST = WideChar($FFFE);
BOM_UTF8: array[0..2] of Byte = ($EF, $BB, $BF);
type
// Unicode transformation formats (UTF) data types.
PUTF8 = ^UTF8;
UTF8 = Char;
PUTF16 = ^UTF16;
UTF16 = WideChar;
PUTF32 = ^UTF32;
UTF32 = Cardinal;
// UTF conversion schemes (UCS) data types. They are defined in Delphi 7, but not in ealier versions.
{$ifndef COMPILER_7_UP}
PUCS2Char = PWideChar;
UCS2Char = WideChar;
PUCS4 = ^UCS4Char;
UCS4Char = LongWord;
{$endif COMPILER_7_UP}
UCS2String = array of UCS2Char;
{$ifndef COMPILER_7_UP}
UCS4String = array of UCS4Char;
{$endif COMPILER_7_UP}
// various predefined or otherwise useful character property categories
TCharacterCategory = (
// normative categories
ccLetterUppercase,
ccLetterLowercase,
ccLetterTitlecase,
ccMarkNonSpacing,
ccMarkSpacingCombining,
ccMarkEnclosing,
ccNumberDecimalDigit,
ccNumberLetter,
ccNumberOther,
ccSeparatorSpace,
ccSeparatorLine,
ccSeparatorParagraph,
ccOtherControl,
ccOtherFormat,
ccOtherSurrogate,
ccOtherPrivate,
ccOtherUnassigned,
// informative categories
ccLetterModifier,
ccLetterOther,
ccPunctuationConnector,
ccPunctuationDash,
ccPunctuationOpen,
ccPunctuationClose,
ccPunctuationInitialQuote,
ccPunctuationFinalQuote,
ccPunctuationOther,
ccSymbolMath,
ccSymbolCurrency,
ccSymbolModifier,
ccSymbolOther,
// bidirectional categories
ccLeftToRight,
ccLeftToRightEmbedding,
ccLeftToRightOverride,
ccRightToLeft,
ccRightToLeftArabic,
ccRightToLeftEmbedding,
ccRightToLeftoverride,
ccPopDirectionalFormat,
ccEuropeanNumber,
ccEuropeanNumberSeparator,
ccEuropeanNumberTerminator,
ccArabicNumber,
ccCommonNumberSeparator,
ccBoundaryNeutral,
ccSegmentSeparator, // this includes tab and vertical tab
ccWhiteSpace,
ccOtherNeutrals,
// self defined categories, they do not appear in the Unicode data file
ccComposed, // can be decomposed
ccNonBreaking,
ccSymmetric, // has left and right forms
ccHexDigit,
ccQuotationMark,
ccMirroring,
ccSpaceOther,
ccAssigned // means there is a definition in the Unicode standard
);
TCharacterCategories = set of TCharacterCategory;
// four forms of normalization are defined:
TNormalizationForm = (
nfNone, // do not normalize
nfC, // canonical decomposition followed by canonical composition (this is most often used)
nfD, // canonical decomposition
nfKC, // compatibility decomposition followed by a canonical composition
nfKD // compatibility decomposition
);
// An Unicode block usually corresponds to a particular language script but
// can also represent special characters, musical symbols and the like.
TUnicodeBlock = (
ubUndefined,
ubBasicLatin,
ubLatin1Supplement,
ubLatinExtendedA,
ubLatinExtendedB,
ubIPAExtensions,
ubSpacingModifierLetters,
ubCombiningDiacriticalMarks,
ubGreek,
ubCyrillic,
ubArmenian,
ubHebrew,
ubArabic,
ubSyriac,
ubThaana,
ubDevanagari,
ubBengali,
ubGurmukhi,
ubGujarati,
ubOriya,
ubTamil,
ubTelugu,
ubKannada,
ubMalayalam,
ubSinhala,
ubThai,
ubLao,
ubTibetan,
ubMyanmar,
ubGeorgian,
ubHangulJamo,
ubEthiopic,
ubCherokee,
ubUnifiedCanadianAboriginalSyllabics,
ubOgham,
ubRunic,
ubKhmer,
ubMongolian,
ubLatinExtendedAdditional,
ubGreekExtended,
ubGeneralPunctuation,
ubSuperscriptsAndSubscripts,
ubCurrencySymbols,
ubCombiningMarksForSymbols,
ubLetterlikeSymbols,
ubNumberForms,
ubArrows,
ubMathematicalOperators,
ubMiscellaneousTechnical,
ubControlPictures,
ubOpticalCharacterRecognition,
ubEnclosedAlphanumerics,
ubBoxDrawing,
ubBlockElements,
ubGeometricShapes,
ubMiscellaneousSymbols,
ubDingbats,
ubBraillePatterns,
ubCJKRadicalsSupplement,
ubKangxiRadicals,
ubIdeographicDescriptionCharacters,
ubCJKSymbolsAndPunctuation,
ubHiragana,
ubKatakana,
ubBopomofo,
ubHangulCompatibilityJamo,
ubKanbun,
ubBopomofoExtended,
ubEnclosedCJKLettersAndMonths,
ubCJKCompatibility,
ubCJKUnifiedIdeographsExtensionA,
ubCJKUnifiedIdeographs,
ubYiSyllables,
ubYiRadicals,
ubHangulSyllables,
ubHighSurrogates,
ubHighPrivateUseSurrogates,
ubLowSurrogates,
ubPrivateUse,
ubCJKCompatibilityIdeographs,
ubAlphabeticPresentationForms,
ubArabicPresentationFormsA,
ubCombiningHalfMarks,
ubCJKCompatibilityForms,
ubSmallFormVariants,
ubArabicPresentationFormsB,
ubSpecials,
ubHalfwidthAndFullwidthForms,
ubOldItalic,
ubGothic,
ubDeseret,
ubByzantineMusicalSymbols,
ubMusicalSymbols,
ubMathematicalAlphanumericSymbols,
ubCJKUnifiedIdeographsExtensionB,
ubCJKCompatibilityIdeographsSupplement,
ubTags
);
TWideStrings = class;
TSearchFlag = (
sfCaseSensitive, // match letter case
sfIgnoreNonSpacing, // ignore non-spacing characters in search
sfSpaceCompress, // handle several consecutive white spaces as one white space
// (this applies to the pattern as well as the search text)
sfWholeWordOnly // match only text at end/start and/or surrounded by white spaces
);
TSearchFlags = set of TSearchFlag;
// a generic search class defininition used for tuned Boyer-Moore and Unicode
// regular expression searches
TSearchEngine = class(TObject)
private
FResults: TList; // 2 entries for each result (start and stop position)
FOwner: TWideStrings; // at the moment unused, perhaps later to access strings faster
protected
function GetCount: Integer; virtual;
public
constructor Create(AOwner: TWideStrings); virtual;
destructor Destroy; override;
procedure AddResult(Start, Stop: Cardinal); virtual;
procedure Clear; virtual;
procedure ClearResults; virtual;
procedure DeleteResult(Index: Cardinal); virtual;
procedure FindPrepare(const Pattern: WideString; Options: TSearchFlags); overload; virtual; abstract;
procedure FindPrepare(const Pattern: PWideChar; PatternLength: Cardinal; Options: TSearchFlags); overload; virtual;
abstract;
function FindFirst(const Text: WideString; var Start, Stop: Cardinal): Boolean; overload; virtual; abstract;
function FindFirst(const Text: PWideChar; TextLen: Cardinal; var Start, Stop: Cardinal): Boolean; overload; virtual;
abstract;
function FindAll(const Text: WideString): Boolean; overload; virtual; abstract;
function FindAll(const Text: PWideChar; TextLen: Cardinal): Boolean; overload; virtual; abstract;
procedure GetResult(Index: Cardinal; var Start, Stop: Integer); virtual;
property Count: Integer read GetCount;
end;
// The Unicode Tuned Boyer-Moore (UTBM) search implementation is an extended
// translation created from a free package written by Mark Leisher (mleisher@crl.nmsu.edu).
//
// The code handles high and low surrogates as well as case (in)dependency,
// can ignore non-spacing characters and allows optionally to return whole
// words only.
// single pattern character
PUTBMChar = ^TUTBMChar;
TUTBMChar = record
LoCase,
UpCase,
TitleCase: UCS4Char;
end;
PUTBMSkip = ^TUTBMSkip;
TUTBMSkip = record
BMChar: PUTBMChar;
SkipValues: Integer;
end;
TUTBMSearch = class(TSearchEngine)
private
FFlags: TSearchFlags;
FPattern: PUTBMChar;
FPatternUsed,
FPatternSize,
FPatternLength: Cardinal;
FSkipValues: PUTBMSkip;
FSkipsUsed: Integer;
FMD4: Cardinal;
protected
procedure ClearPattern;
procedure Compile(Pattern: PUCS2Char; PatternLength: Integer; Flags: TSearchFlags);
function Find(Text: PUCS2Char; TextLen: Cardinal; var MatchStart, MatchEnd: Cardinal): Boolean;
function GetSkipValue(TextStart, TextEnd: PUCS2Char): Cardinal;
function Match(Text, Start, Stop: PUCS2Char; var MatchStart, MatchEnd: Cardinal): Boolean;
public
procedure Clear; override;
procedure FindPrepare(const Pattern: WideString; Options: TSearchFlags); overload; override;
procedure FindPrepare(const Pattern: PWideChar; PatternLength: Cardinal; Options: TSearchFlags); overload;
override;
function FindFirst(const Text: WideString; var Start, Stop: Cardinal): Boolean; overload; override;
function FindFirst(const Text: PWideChar; TextLen: Cardinal; var Start, Stop: Cardinal): Boolean; overload;
override;
function FindAll(const Text: WideString): Boolean; overload; override;
function FindAll(const Text: PWideChar; TextLen: Cardinal): Boolean; overload; override;
end;
// Regular expression search engine for text in UCS2Char form taking surrogates
// into account. This implementation is an improved translation from the URE
// package written by Mark Leisher (mleisher@crl.nmsu.edu) who used a variation
// of the RE->DFA algorithm done by Mark Hopkins (markh@csd4.csd.uwm.edu).
// Assumptions:
// o Regular expression and text already normalized.
// o Conversion to lower case assumes a 1-1 mapping.
//
// Definitions:
// Separator - any one of U+2028, U+2029, NL, CR.
//
// Operators:
// . - match any character
// * - match zero or more of the last subexpression
// + - match one or more of the last subexpression
// ? - match zero or one of the last subexpression
// () - subexpression grouping
// {m, n} - match at least m occurences and up to n occurences
// Note: both values can be 0 or ommitted which denotes then a unlimiting bound
// {,} and {0,} and {0, 0} correspond to *
// {, 1} and {0, 1} correspond to ?
// {1,} and {1, 0} correspond to +
// {m} - match exactly m occurences
//
// Notes:
// o The "." operator normally does not match separators, but a flag is
// available that will allow this operator to match a separator.
//
// Literals and Constants:
// c - literal UCS2Char character
// \x.... - hexadecimal number of up to 4 digits
// \X.... - hexadecimal number of up to 4 digits
// \u.... - hexadecimal number of up to 4 digits
// \U.... - hexadecimal number of up to 4 digits
//
// Character classes:
// [...] - Character class
// [^...] - Negated character class
// \pN1,N2,...,Nn - Character properties class
// \PN1,N2,...,Nn - Negated character properties class
//
// POSIX character classes recognized:
// :alnum:
// :alpha:
// :cntrl:
// :digit:
// :graph:
// :lower:
// :print:
// :punct:
// :space:
// :upper:
// :xdigit:
//
// Notes:
// o Character property classes are \p or \P followed by a comma separated
// list of integers between 0 and the maximum entry index in TCharacterCategory.
// These integers directly correspond to the TCharacterCategory enumeration entries.
// Note: upper, lower and title case classes need to have case sensitive search
// be enabled to match correctly!
//
// o Character classes can contain literals, constants and character
// property classes. Example:
//
// [abc\U10A\p0,13,4]
// structure used to handle a compacted range of characters
PUcRange = ^TUcRange;
TUcRange = record
MinCode,
MaxCode: UCS4Char;
end;
TUcCClass = record
Ranges: array of TUcRange;
RangesUsed: Integer;
end;
// either a single character or a list of character classes
TUcSymbol = record
Chr: UCS4Char;
CCL: TUcCClass;
end;
// this is a general element structure used for expressions and stack elements
TUcElement = record
OnStack: Boolean;
AType,
LHS,
RHS: Cardinal;
end;
// this is a structure used to track a list or a stack of states
PUcStateList = ^TUcStateList;
TUcStateList = record
List: array of Cardinal;
ListUsed: Integer;
end;
// structure to track the list of unique states for a symbol during reduction
PUcSymbolTableEntry = ^TUcSymbolTableEntry;
TUcSymbolTableEntry = record
ID,
AType: Cardinal;
Mods,
Categories: TCharacterCategories;
Symbol: TUcSymbol;
States: TUcStateList;
end;
// structure to hold a single State
PUcState = ^TUcState;
TUcState = record
ID: Cardinal;
Accepting: Boolean;
StateList: TUcStateList;
Transitions: array of TUcElement;
TransitionsUsed: Integer;
end;
// structure used for keeping lists of states
TUcStateTable = record
States: array of TUcState;
StatesUsed: Integer;
end;
// structure to track pairs of DFA states when equivalent states are merged
TUcEquivalent = record
Left,
Right: Cardinal;
end;
TUcExpressionList = record
Expressions: array of TUcElement;
ExpressionsUsed: Integer;
end;
TUcSymbolTable = record
Symbols: array of TUcSymbolTableEntry;
SymbolsUsed: Integer;
end;
TUcEquivalentList = record
Equivalents: array of TUcEquivalent;
EquivalentsUsed: Integer;
end;
// structure used for constructing the NFA and reducing to a minimal DFA
PUREBuffer = ^TUREBuffer;
TUREBuffer = record
Reducing: Boolean;
Error: Integer;
Flags: Cardinal;
Stack: TUcStateList;
SymbolTable: TUcSymbolTable; // table of unique symbols encountered
ExpressionList: TUcExpressionList; // tracks the unique expressions generated
// for the NFA and when the NFA is reduced
States: TUcStateTable; // the reduced table of unique groups of NFA states
EquivalentList: TUcEquivalentList; // tracks states when equivalent states are merged
end;
TUcTransition = record
Symbol,
NextState: Cardinal;
end;
PDFAState = ^TDFAState;
TDFAState = record
Accepting: Boolean;
NumberTransitions: Integer;
StartTransition: Integer;
end;
TDFAStates = record
States: array of TDFAState;
StatesUsed: Integer;
end;
TUcTransitions = record
Transitions: array of TUcTransition;
TransitionsUsed: Integer;
end;
TDFA = record
Flags: Cardinal;
SymbolTable: TUcSymbolTable;
StateList: TDFAStates;
TransitionList: TUcTransitions;
end;
TURESearch = class(TSearchEngine)
private
FUREBuffer: TUREBuffer;
FDFA: TDFA;
protected
procedure AddEquivalentPair(L, R: Cardinal);
procedure AddRange(var CCL: TUcCClass; Range: TUcRange);
function AddState(NewStates: array of Cardinal): Cardinal;
procedure AddSymbolState(Symbol, State: Cardinal);
function BuildCharacterClass(CP: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
procedure ClearUREBuffer;
function CompileSymbol(S: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
procedure CompileURE(RE: PWideChar; RELength: Cardinal; Casefold: Boolean);
procedure CollectPendingOperations(var State: Cardinal);
function ConvertRegExpToNFA(RE: PWideChar; RELength: Cardinal): Cardinal;
function ExecuteURE(Flags: Cardinal; Text: PUCS2Char; TextLen: Cardinal; var MatchStart, MatchEnd: Cardinal): Boolean;
procedure ClearDFA;
procedure HexDigitSetup(Symbol: PUcSymbolTableEntry);
function MakeExpression(AType, LHS, RHS: Cardinal): Cardinal;
function MakeHexNumber(NP: PUCS2Char; Limit: Cardinal; var Number: UCS4Char): Cardinal;
function MakeSymbol(S: PUCS2Char; Limit: Cardinal; var Consumed: Cardinal): Cardinal;
procedure MergeEquivalents;
function ParsePropertyList(Properties: PUCS2Char; Limit: Cardinal; var Categories: TCharacterCategories): Cardinal;
function Peek: Cardinal;
function Pop: Cardinal;
function PosixCCL(CP: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
function ProbeLowSurrogate(LeftState: PUCS2Char; Limit: Cardinal; var Code: UCS4Char): Cardinal;
procedure Push(V: Cardinal);
procedure Reduce(Start: Cardinal);
procedure SpaceSetup(Symbol: PUcSymbolTableEntry; Categories: TCharacterCategories);
function SymbolsAreDifferent(A, B: PUcSymbolTableEntry): Boolean;
public
procedure Clear; override;
procedure FindPrepare(const Pattern: WideString; Options: TSearchFlags); overload; override;
procedure FindPrepare(const Pattern: PWideChar; PatternLength: Cardinal; Options: TSearchFlags); overload;
override;
function FindFirst(const Text: WideString; var Start, Stop: Cardinal): Boolean; overload; override;
function FindFirst(const Text: PWideChar; TextLen: Cardinal; var Start, Stop: Cardinal): Boolean; overload;
override;
function FindAll(const Text: WideString): Boolean; overload; override;
function FindAll(const Text: PWideChar; TextLen: Cardinal): Boolean; overload; override;
end;
// Event used to give the application a chance to switch the way of how to save
// the text in TWideStrings if the text contains characters not only from the
// ANSI block but the save type is ANSI. On triggering the event the application
// can change the property SaveUnicode as needed. This property is again checked
// after the callback returns.
TConfirmConversionEvent = procedure(Sender: TWideStrings; var Allowed: Boolean) of object;
TWideStrings = class(TPersistent)
private
FUpdateCount: Integer;
FLanguage: LCID; // Language can usually left alone, the system's default is used.
FSaved, // Set in SaveToStream, True if saving was successfull otherwise False.
FSaveUnicode: Boolean; // Flag set on loading to keep track in which format to save
// (can be set explicitely, but expect losses if there's true Unicode content
// and this flag is set to False)
FNormalizationForm: TNormalizationForm; // Determines whether input should be normalized and which format to use.
FOnConfirmConversion: TConfirmConversionEvent;
function GetCommaText: WideString;
function GetName(Index: Integer): WideString;
function GetValue(const Name: WideString): WideString;
procedure ReadData(Reader: TReader);
procedure SetCommaText(const Value: WideString);
procedure SetNormalizationForm(const Value: TNormalizationForm);
procedure SetValue(const Name, Value: WideString);
procedure WriteData(Writer: TWriter);
protected
procedure DefineProperties(Filer: TFiler); override;
procedure DoConfirmConversion(var Allowed: Boolean); virtual;
procedure Error(const Msg: string; Data: Integer);
function Get(Index: Integer): WideString; virtual; abstract;
function GetCapacity: Integer; virtual;
function GetCount: Integer; virtual; abstract;
function GetObject(Index: Integer): TObject; virtual;
function GetText: WideString; virtual;
procedure Put(Index: Integer; const S: WideString); virtual; abstract;
procedure PutObject(Index: Integer; AObject: TObject); virtual; abstract;
procedure SetCapacity(NewCapacity: Integer); virtual;
procedure SetUpdateState(Updating: Boolean); virtual;
procedure SetLanguage(Value: LCID); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function Add(const S: WideString): Integer; virtual;
function AddObject(const S: WideString; AObject: TObject): Integer; virtual;
procedure Append(const S: WideString);
procedure AddStrings(Strings: TStrings); overload; virtual;
procedure AddStrings(Strings: TWideStrings); overload; virtual;
procedure Assign(Source: TPersistent); override;
procedure AssignTo(Dest: TPersistent); override;
procedure BeginUpdate;
procedure Clear; virtual; abstract;
procedure Delete(Index: Integer); virtual; abstract;
procedure EndUpdate;
function Equals(Strings: TWideStrings): Boolean;
procedure Exchange(Index1, Index2: Integer); virtual;
function GetSeparatedText(Separators: WideString): WideString; virtual;
function IndexOf(const S: WideString): Integer; virtual;
function IndexOfName(const Name: WideString): Integer;
function IndexOfObject(AObject: TObject): Integer;
procedure Insert(Index: Integer; const S: WideString); virtual; abstract;
procedure InsertObject(Index: Integer; const S: WideString; AObject: TObject);
procedure LoadFromFile(const FileName: string); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure Move(CurIndex, NewIndex: Integer); virtual;
procedure SaveToFile(const FileName: string); virtual;
procedure SaveToStream(Stream: TStream; WithBOM: Boolean = True); virtual;
procedure SetText(const Value: WideString); virtual;
property Capacity: Integer read GetCapacity write SetCapacity;
property CommaText: WideString read GetCommaText write SetCommaText;
property Count: Integer read GetCount;
property Language: LCID read FLanguage write SetLanguage;
property Names[Index: Integer]: WideString read GetName;
property NormalizationForm: TNormalizationForm read FNormalizationForm write SetNormalizationForm default nfNone;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property Values[const Name: WideString]: WideString read GetValue write SetValue;
property Saved: Boolean read FSaved;
property SaveUnicode: Boolean read FSaveUnicode write FSaveUnicode default True;
property Strings[Index: Integer]: WideString read Get write Put; default;
property Text: WideString read GetText write SetText;
property OnConfirmConversion: TConfirmConversionEvent read FOnConfirmConversion write FOnConfirmConversion;
end;
//----- TWideStringList class
TWideStringItem = record
FString: WideString;
FObject: TObject;
end;
TWideStringItemList = array of TWideStringItem;
TWideStringList = class(TWideStrings)
private
FList: TWideStringItemList;
FCount: Integer;
FSorted: Boolean;
FDuplicates: TDuplicates;
FOnChange: TNotifyEvent;
FOnChanging: TNotifyEvent;
procedure ExchangeItems(Index1, Index2: Integer);
procedure Grow;
procedure QuickSort(L, R: Integer);
procedure SetSorted(Value: Boolean);
protected
procedure Changed; virtual;
procedure Changing; virtual;
function Get(Index: Integer): WideString; override;
function GetCapacity: Integer; override;
function GetCount: Integer; override;
function GetObject(Index: Integer): TObject; override;
procedure InsertItem(Index: Integer; const S: WideString); virtual;
procedure Put(Index: Integer; const S: WideString); override;
procedure PutObject(Index: Integer; AObject: TObject); override;
procedure SetCapacity(NewCapacity: Integer); override;
procedure SetUpdateState(Updating: Boolean); override;
procedure SetLanguage(Value: LCID); override;
public
destructor Destroy; override;
function Add(const S: WideString): Integer; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Exchange(Index1, Index2: Integer); override;
function Find(const S: WideString; var Index: Integer): Boolean; virtual;
function IndexOf(const S: WideString): Integer; override;
procedure Insert(Index: Integer; const S: WideString); override;
procedure Sort; virtual;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read FSorted write SetSorted;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChanging: TNotifyEvent read FOnChanging write FOnChanging;
end;
// result type for number retrieval functions
TUcNumber = record
Numerator,
Denominator: Integer;
end;
TFontCharSet = 0..255;
const
ReplacementCharacter: UCS4Char = $0000FFFD;
MaximumUCS2: UCS4Char = $0000FFFF;
MaximumUTF16: UCS4Char = $0010FFFF;
MaximumUCS4: UCS4Char = $7FFFFFFF;
SurrogateHighStart: UCS4Char = $D800;
SurrogateHighEnd: UCS4Char = $DBFF;
SurrogateLowStart: UCS4Char = $DC00;
SurrogateLowEnd: UCS4Char = $DFFF;
// functions involving null-terminated strings
function StrLenW(Str: PWideChar): Cardinal;
function StrEndW(Str: PWideChar): PWideChar;
function StrMoveW(Dest, Source: PWideChar; Count: Cardinal): PWideChar;
function StrCopyW(Dest, Source: PWideChar): PWideChar;
function StrECopyW(Dest, Source: PWideChar): PWideChar;
function StrLCopyW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
function StrPCopyW(Dest: PWideChar; const Source: string): PWideChar;
function StrPLCopyW(Dest: PWideChar; const Source: string; MaxLen: Cardinal): PWideChar;
function StrCatW(Dest, Source: PWideChar): PWideChar;
function StrLCatW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
function StrCompW(Str1, Str2: PWideChar): Integer;
function StrICompW(Str1, Str2: PWideChar): Integer;
function StrLCompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
function StrLICompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
function StrNScanW(S1, S2: PWideChar): Integer;
function StrRNScanW(S1, S2: PWideChar): Integer;
function StrScanW(Str: PWideChar; Chr: WideChar): PWideChar; overload;
function StrScanW(Str: PWideChar; Chr: WideChar; StrLen: Cardinal): PWideChar; overload;
function StrRScanW(Str: PWideChar; Chr: WideChar): PWideChar;
function StrPosW(Str, SubStr: PWideChar): PWideChar;
function StrAllocW(Size: Cardinal): PWideChar;
function StrBufSizeW(Str: PWideChar): Cardinal;
function StrNewW(Str: PWideChar): PWideChar;
procedure StrDisposeW(Str: PWideChar);
procedure StrSwapByteOrder(Str: PWideChar);
// functions involving Delphi wide strings
function WideAdjustLineBreaks(const S: WideString): WideString;
function WideCharPos(const S: WideString; const Ch: WideChar; const Index: Integer): Integer; //az
function WideCompose(const S: WideString): WideString;
function WideDecompose(const S: WideString; Compatible: Boolean): WideString;
function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): WideString;
function WideQuotedStr(const S: WideString; Quote: WideChar): WideString;
function WideStringOfChar(C: WideChar; Count: Cardinal): WideString;
function WideCaseFolding(C: WideChar): WideString; overload;
function WideCaseFolding(const S: WideString): WideString; overload;
function WideLowerCase(C: WideChar): WideString; overload;
function WideLowerCase(const S: WideString): WideString; overload;
function WideNormalize(const S: WideString; Form: TNormalizationForm): WideString;
function WideSameText(const Str1, Str2: WideString): Boolean;
function WideTitleCase(C: WideChar): WideString; overload;
function WideTitleCase(const S: WideString): WideString; overload;
function WideTrim(const S: WideString): WideString;
function WideTrimLeft(const S: WideString): WideString;
function WideTrimRight(const S: WideString): WideString;
function WideUpperCase(C: WideChar): WideString; overload;
function WideUpperCase(const S: WideString): WideString; overload;
// Low level character routines
function UnicodeNumberLookup(Code: UCS4Char; var Number: TUcNumber): Boolean;
function UnicodeComposePair(First, Second: UCS4Char; var Composite: UCS4Char): Boolean;
function UnicodeCaseFold(Code: UCS4Char): UCS4String;
function UnicodeToUpper(Code: UCS4Char): UCS4String;
function UnicodeToLower(Code: UCS4Char): UCS4String;
function UnicodeToTitle(Code: UCS4Char): UCS4String;
// Character test routines
function UnicodeIsAlpha(C: UCS4Char): Boolean;
function UnicodeIsDigit(C: UCS4Char): Boolean;
function UnicodeIsAlphaNum(C: UCS4Char): Boolean;
function UnicodeIsCased(C: UCS4Char): Boolean;
function UnicodeIsControl(C: UCS4Char): Boolean;
function UnicodeIsSpace(C: UCS4Char): Boolean;
function UnicodeIsWhiteSpace(C: UCS4Char): Boolean;
function UnicodeIsBlank(C: UCS4Char): Boolean;
function UnicodeIsPunctuation(C: UCS4Char): Boolean;
function UnicodeIsGraph(C: UCS4Char): Boolean;
function UnicodeIsPrintable(C: UCS4Char): Boolean;
function UnicodeIsUpper(C: UCS4Char): Boolean;
function UnicodeIsLower(C: UCS4Char): Boolean;
function UnicodeIsTitle(C: UCS4Char): Boolean;
function UnicodeIsHexDigit(C: UCS4Char): Boolean;
function UnicodeIsIsoControl(C: UCS4Char): Boolean;
function UnicodeIsFormatControl(C: UCS4Char): Boolean;
function UnicodeIsSymbol(C: UCS4Char): Boolean;
function UnicodeIsNumber(C: UCS4Char): Boolean;
function UnicodeIsNonSpacing(C: UCS4Char): Boolean;
function UnicodeIsOpenPunctuation(C: UCS4Char): Boolean;
function UnicodeIsClosePunctuation(C: UCS4Char): Boolean;
function UnicodeIsInitialPunctuation(C: UCS4Char): Boolean;
function UnicodeIsFinalPunctuation(C: UCS4Char): Boolean;
function UnicodeIsComposed(C: UCS4Char): Boolean;
function UnicodeIsQuotationMark(C: UCS4Char): Boolean;
function UnicodeIsSymmetric(C: UCS4Char): Boolean;
function UnicodeIsMirroring(C: UCS4Char): Boolean;
function UnicodeIsNonBreaking(C: UCS4Char): Boolean;
// Directionality functions
function UnicodeIsRightToLeft(C: UCS4Char): Boolean;
function UnicodeIsLeftToRight(C: UCS4Char): Boolean;
function UnicodeIsStrong(C: UCS4Char): Boolean;
function UnicodeIsWeak(C: UCS4Char): Boolean;
function UnicodeIsNeutral(C: UCS4Char): Boolean;
function UnicodeIsSeparator(C: UCS4Char): Boolean;
// Other character test functions
function UnicodeIsMark(C: UCS4Char): Boolean;
function UnicodeIsModifier(C: UCS4Char): Boolean;
function UnicodeIsLetterNumber(C: UCS4Char): Boolean;
function UnicodeIsConnectionPunctuation(C: UCS4Char): Boolean;
function UnicodeIsDash(C: UCS4Char): Boolean;
function UnicodeIsMath(C: UCS4Char): Boolean;
function UnicodeIsCurrency(C: UCS4Char): Boolean;
function UnicodeIsModifierSymbol(C: UCS4Char): Boolean;
function UnicodeIsNonSpacingMark(C: UCS4Char): Boolean;
function UnicodeIsSpacingMark(C: UCS4Char): Boolean;
function UnicodeIsEnclosing(C: UCS4Char): Boolean;
function UnicodeIsPrivate(C: UCS4Char): Boolean;
function UnicodeIsSurrogate(C: UCS4Char): Boolean;
function UnicodeIsLineSeparator(C: UCS4Char): Boolean;
function UnicodeIsParagraphSeparator(C: UCS4Char): Boolean;
function UnicodeIsIdentifierStart(C: UCS4Char): Boolean;
function UnicodeIsIdentifierPart(C: UCS4Char): Boolean;
function UnicodeIsDefined(C: UCS4Char): Boolean;
function UnicodeIsUndefined(C: UCS4Char): Boolean;
function UnicodeIsHan(C: UCS4Char): Boolean;
function UnicodeIsHangul(C: UCS4Char): Boolean;
// Utility functions
function CharSetFromLocale(Language: LCID): TFontCharSet;
function CodePageFromLocale(Language: LCID): Integer;
function CodeBlockFromChar(const C: UCS4Char): TUnicodeBlock;
function KeyboardCodePage: Word;
function KeyUnicode(C: Char): WideChar;
function StringToWideStringEx(const S: string; CodePage: Word): WideString;
function TranslateString(const S: string; CP1, CP2: Word): string;
function WideStringToStringEx(const WS: WideString; CodePage: Word): string;
// WideString conversion routines
procedure ExpandANSIString(const Source: PChar; Target: PWideChar; Count: Cardinal);
function WideStringToUTF8(S: WideString): AnsiString;
function UTF8ToWideString(S: AnsiString): WideString;
type
TCompareFunc = function(W1, W2: WideString; Locale: LCID): Integer;
var
WideCompareText: TCompareFunc;
//------------------------------------------------------------------------------------------------------------------------------------------
implementation
// Unicode data for case mapping, decomposition, numbers etc. This data is
// loaded on demand which means only those parts will be put in memory which are
// needed by one of the lookup functions.
// Note: There is a little tool called UDExtract which creates a resouce script from
// the Unicode database file which can be compiled to the needed res file.
// This tool, including its source code, can be downloaded from www.lischke-online.de/Unicode.html.
{$R Unicode.res}
uses
{$ifdef COMPILER_6_UP}
RtlConsts,
{$else}
Consts,
{$endif COMPILER_6_UP}
SysUtils,
SyncObjs;
resourcestring
SUREBaseString = 'Error in regular expression: %s' + #13;
SUREUnexpectedEOS = 'Unexpected end of pattern.';
SURECharacterClassOpen = 'Character class not closed, '']'' is missing.';
SUREUnbalancedGroup = 'Unbalanced group expression, '')'' is missing.';
SUREInvalidCharProperty = 'A character property is invalid';
SUREInvalidRepeatRange = 'Invalid repeation range.';
SURERepeatRangeOpen = 'Repeation range not closed, ''}'' is missing.';
SUREExpressionEmpty = 'Expression is empty.';
const
// some predefined sets to shorten parameter lists below and ease repeative usage
ClassLetter = [ccLetterUppercase, ccLetterLowercase, ccLetterTitlecase, ccLetterModifier, ccLetterOther];
ClassSpace = [ccSeparatorSpace, ccSpaceOther];
ClassPunctuation = [ccPunctuationConnector, ccPunctuationDash, ccPunctuationOpen, ccPunctuationClose,
ccPunctuationOther, ccPunctuationInitialQuote, ccPunctuationFinalQuote, ccPunctuationOther];
ClassMark = [ccMarkNonSpacing, ccMarkSpacingCombining, ccMarkEnclosing];
ClassNumber = [ccNumberDecimalDigit, ccNumberLetter, ccNumberOther];
ClassSymbol = [ccSymbolMath, ccSymbolCurrency, ccSymbolModifier, ccSymbolOther];
ClassEuropeanNumber = [ccEuropeanNumber, ccEuropeanNumberSeparator, ccEuropeanNumberTerminator];
// used to negate a set of categories
ClassAll = [Low(TCharacterCategory)..High(TCharacterCategory)];
var
// As the global data can be accessed by several threads it should be guarded
// while the data is loaded.
LoadInProgress: TCriticalSection;
//----------------- support for character categories -------------------------------------------------------------------
// Character category data is quite a large block since every defined character in Unicode is assigned at least
// one category. Because of this we cannot use a sparse matrix to provide quick access as implemented for
// e.g. composition data.
// The approach used here is based on the fact that an application seldomly uses all characters defined in Unicode
// simultanously. In fact the opposite is true. Most application will use either Western Europe or Arabic or
// Far East character data, but very rarely all together. Based on this fact is the implementation of virtual
// memory using the systems paging file (aka file mapping) to load only into virtual memory what is used currently.
// The implementation is not yet finished and needs a lot of improvements yet.
type
// start and stop of a range of code points
TRange = record
Start,
Stop: Cardinal;
end;
TRangeArray = array of TRange;
TCategoriesArray = array of TCharacterCategories;
var
// character categories, stored in the system's swap file and mapped on demand
CategoriesLoaded: Boolean;
Categories: array[Byte] of TCategoriesArray;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadCharacterCategories;
// Loads the character categories data (as saved by the Unicode database extractor, see also
// the comments about JclUnicode.res above).
var
Size: Integer;
Stream: TResourceStream;
Category: TCharacterCategory;
Buffer: TRangeArray;
First,
Second: Byte;
J, K: Integer;
begin
// Data already loaded?
if not CategoriesLoaded then
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
CategoriesLoaded := True;
Stream := TResourceStream.Create(HInstance, 'CATEGORIES', 'UNICODEDATA');
try
while Stream.Position < Stream.Size do
begin
// a) read which category is current in the stream
Stream.ReadBuffer(Category, 1);
// b) read the size of the ranges and the ranges themself
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(Buffer, Size);
Stream.ReadBuffer(Buffer[0], Size * SizeOf(TRange));
// c) go through every range and add the current category to each code point
for J := 0 to Size - 1 do
for K := Buffer[J].Start to Buffer[J].Stop do
begin
if K > $FFFF then
Break;
First := (K shr 8) and $FF;
Second := K and $FF;
// add second step array if not yet done
if Categories[First] = nil then
SetLength(Categories[First], 256);
Include(Categories[First, Second], Category);
end;
end;
end;
finally
Stream.Free;
end;
finally
LoadInProgress.Leave;
end;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function CategoryLookup(Code: Cardinal; Cats: TCharacterCategories): Boolean; overload;
// determines whether the Code is in the given category
var
First,
Second: Byte;
begin
// load property data if not already done
if not CategoriesLoaded then
LoadCharacterCategories;
First := (Code shr 8) and $FF;
Second := Code and $FF;
if Assigned(Categories[First]) then
Result := Categories[First, Second] * Cats <> []
else
Result := False;
end;
//----------------- support for case mapping ---------------------------------------------------------------------------
type
TCase = array[0..3] of UCS4String; // mapping for case fold, lower, title and upper in this order
TCaseArray = array of TCase;
var
// An array for all case mappings (including 1 to many casing if saved by the extraction program).
// The organization is a sparse, two stage matrix.
CaseDataLoaded: Boolean;
CaseMapping: array[Byte] of TCaseArray;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadCaseMappingData;
var
Stream: TResourceStream;
I, Code,
Size: Cardinal;
First,
Second: Byte;
begin
if not CaseDataLoaded then
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
CaseDataLoaded := True;
Stream := TResourceStream.Create(HInstance, 'CASE', 'UNICODEDATA');
try
// the first entry in the stream is the number of entries in the case mapping table
Stream.ReadBuffer(Size, 4);
for I := 0 to Size - 1 do
begin
// a) read actual code point
Stream.ReadBuffer(Code, 4);
Assert(Code < $10000, 'cased Unicode character > $FFFF found');
// if there is no high byte entry in the first stage table then create one
First := (Code shr 8) and $FF;
Second := Code and $FF;
if CaseMapping[First] = nil then
SetLength(CaseMapping[First], 256);
// b) read fold case array
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CaseMapping[First, Second, 0], Size);
Stream.ReadBuffer(CaseMapping[First, Second, 0, 0], Size * SizeOf(UCS4Char));
end;
// c) read lower case array
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CaseMapping[First, Second, 1], Size);
Stream.ReadBuffer(CaseMapping[First, Second, 1, 0], Size * SizeOf(UCS4Char));
end;
// d) read title case array
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CaseMapping[First, Second, 2], Size);
Stream.ReadBuffer(CaseMapping[First, Second, 2, 0], Size * SizeOf(UCS4Char));
end;
// e) read upper case array
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CaseMapping[First, Second, 3], Size);
Stream.ReadBuffer(CaseMapping[First, Second, 3, 0], Size * SizeOf(UCS4Char));
end;
end;
// TODO: there is serious problem in the compiled data. Upper and title case for small latin letter "i"
// is wrong ("large latin latter I with dot above" was used instead the one without the dot.
// This must yet be fixed but cannot currently as it requires to rework the UD extract utility.
// For now we fix this one value manually here.
CaseMapping[0, Ord('i'), 2, 0] := Ord('I');
CaseMapping[0, Ord('i'), 3, 0] := Ord('I');
CaseMapping[0, Ord('I'), 1, 0] := Ord('i');
finally
Stream.Free;
end;
finally
LoadInProgress.Leave;
end;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function CaseLookup(Code: Cardinal; CaseType: Cardinal): UCS4String;
// Performs a lookup of the given code and returns its case mapping if found.
// CaseType must be 0 for case folding, 1 for lower case, 2 for title case and 3 for upper case, respectively.
// If Code could not be found (or there is no case mapping) then the result is a mapping of length 1 with the
// code itself. Otherwise an array of code points is returned which represent the mapping.
var
First,
Second: Byte;
begin
// Load case mapping data if not already done.
if not CaseDataLoaded then
LoadCaseMappingData;
First := (Code shr 8) and $FF;
Second := Code and $FF;
// Check first stage table whether there is a mapping for a particular block and
// (if so) then whether there is a mapping or not.
if (CaseMapping[First] = nil) or (CaseMapping[First, Second, CaseType] = nil) then
begin
SetLength(Result, 1);
Result[0] := Code;
end
else
Result := CaseMapping[First, Second, CaseType];
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeCaseFold(Code: UCS4Char): UCS4String;
// This function returnes an array of special case fold mappings if there is one defined for the given
// code, otherwise the lower case will be returned. This all applies only to cased code points.
// Uncased code points are returned unchanged.
begin
Result := CaseLookup(Code, 0);
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeToUpper(Code: UCS4Char): UCS4String;
begin
Result := CaseLookup(Code, 3);
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeToLower(Code: UCS4Char): UCS4String;
begin
Result := CaseLookup(Code, 1);
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeToTitle(Code: UCS4Char): UCS4String;
begin
Result := CaseLookup(Code, 2);
end;
//----------------- support for decomposition --------------------------------------------------------------------------
const
// constants for hangul composition and hangul-to-jamo decomposition
SBase = $AC00; // hangul syllables start code point
LBase = $1100; // leading syllable
VBase = $1161;
TBase = $11A7; // trailing syllable
LCount = 19;
VCount = 21;
TCount = 28;
NCount = VCount * TCount; // 588
SCount = LCount * NCount; // 11172
type
TDecompositions = array of UCS4String;
TDecompositionsArray = array[Byte] of TDecompositions;
var
// list of decompositions, organized (again) as two stage matrix
// Note: there are two tables, one for canonical decompositions and the other one
// for compatibility decompositions.
DecompositionsLoaded: Boolean;
CanonicalDecompositions,
CompatibleDecompositions: TDecompositionsArray;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadDecompositionData;
var
Stream: TResourceStream;
I, Code,
Size: Cardinal;
First,
Second: Byte;
begin
if not DecompositionsLoaded then
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
DecompositionsLoaded := True;
Stream := TResourceStream.Create(HInstance, 'DECOMPOSITION', 'UNICODEDATA');
try
// determine how many decomposition entries we have
Stream.ReadBuffer(Size, 4);
for I := 0 to Size - 1 do
begin
Stream.ReadBuffer(Code, 4);
Assert((Code and not $40000000) < $10000, 'decomposed Unicode character > $FFFF found');
// if there is no high byte entry in the first stage table then create one
First := (Code shr 8) and $FF;
Second := Code and $FF;
// insert into the correct table depending on bit 30
// (if set then it is a compatibility decomposition)
if Code and $40000000 <> 0 then
begin
if CompatibleDecompositions[First] = nil then
SetLength(CompatibleDecompositions[First], 256);
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CompatibleDecompositions[First, Second], Size);
Stream.ReadBuffer(CompatibleDecompositions[First, Second, 0], Size * SizeOf(UCS4Char));
end;
end
else
begin
if CanonicalDecompositions[First] = nil then
SetLength(CanonicalDecompositions[First], 256);
Stream.ReadBuffer(Size, 4);
if Size > 0 then
begin
SetLength(CanonicalDecompositions[First, Second], Size);
Stream.ReadBuffer(CanonicalDecompositions[First, Second, 0], Size * SizeOf(UCS4Char));
end;
end;
end;
finally
Stream.Free;
end;
finally
LoadInProgress.Leave;
end;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeDecomposeHangul(Code: UCS4Char): UCS4String;
// algorithmically decomposes hangul character
var
Rest: Integer;
begin
Dec(Code, SBase);
Rest := Code mod TCount;
if Rest = 0 then
SetLength(Result, 2)
else
SetLength(Result, 3);
Result[0] := LBase + (Code div NCount);
Result[1] := VBase + ((Code mod NCount) div TCount);
if Rest <> 0 then
Result[2] := TBase + Rest;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeDecompose(Code: UCS4Char; Compatible: Boolean): UCS4String;
var
First,
Second: Byte;
begin
// load decomposition data if not already done
if not DecompositionsLoaded then
LoadDecompositionData;
Result := nil;
// if the code is hangul then decomposition is algorithmically
if UnicodeIsHangul(Code) then
Result := UnicodeDecomposeHangul(Code)
else
begin
First := (Code shr 8) and $FF;
Second := Code and $FF;
if Compatible then
begin
// Check first stage table whether there is a particular block and
// (if so) then whether there is a decomposition or not.
if (CompatibleDecompositions[First] = nil) or (CompatibleDecompositions[First, Second] = nil) then
begin
// if there is no compatibility decompositions try canonical
if (CanonicalDecompositions[First] = nil) or (CanonicalDecompositions[First, Second] = nil) then
Result := nil
else
Result := CanonicalDecompositions[First, Second];
end
else
Result := CompatibleDecompositions[First, Second];
end
else
begin
if (CanonicalDecompositions[First] = nil) or (CanonicalDecompositions[First, Second] = nil) then
Result := nil
else
Result := CanonicalDecompositions[First, Second];
end;
end;
end;
//----------------- support for combining classes ----------------------------------------------------------------------
type
TClassArray = array of Byte;
var
// canonical combining classes, again as two stage matrix
CCCsLoaded: Boolean;
CCCs: array[Byte] of TClassArray;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadCombiningClassData;
var
Stream: TResourceStream;
I, J, K,
Size: Cardinal;
Buffer: TRangeArray;
First,
Second: Byte;
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
if not CCCsLoaded then
begin
CCCsLoaded := True;
Stream := TResourceStream.Create(HInstance, 'COMBINING', 'UNICODEDATA');
try
while Stream.Position < Stream.Size do
begin
// a) determine which class is stored here
Stream.ReadBuffer(I, 4);
// b) determine how many ranges are assigned to this class
Stream.ReadBuffer(Size, 4);
// c) read start and stop code of each range
if Size > 0 then
begin
SetLength(Buffer, Size);
Stream.ReadBuffer(Buffer[0], Size * SizeOf(TRange));
// d) put this class in every of the code points just loaded
for J := 0 to Size - 1 do
for K := Buffer[J].Start to Buffer[J].Stop do
begin
Assert(K < $10000, 'combining class for Unicode character > $FFFF found');
First := (K shr 8) and $FF;
Second := K and $FF;
// add second step array if not yet done
if CCCs[First] = nil then
SetLength(CCCs[First], 256);
CCCs[First, Second] := I;
end;
end;
end;
finally
Stream.Free;
end;
end;
finally
LoadInProgress.Leave;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function CanonicalCombiningClass(Code: Cardinal): Cardinal;
var
First,
Second: Byte;
begin
// load combining class data if not already done
if not CCCsLoaded then
LoadCombiningClassData;
First := (Code shr 8) and $FF;
Second := Code and $FF;
if Assigned(CCCs[First]) then
Result := CCCs[First, Second]
else
Result := 0;
end;
//----------------- support for numeric values -------------------------------------------------------------------------
type
// structures for handling numbers
TCodeIndex = record
Code,
Index: Cardinal;
end;
var
// array to hold the number equivalents for specific codes
NumberCodes: array of TCodeIndex;
// array of numbers used in NumberCodes
Numbers: array of TUcNumber;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadNumberData;
var
Stream: TResourceStream;
Size: Cardinal;
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
if NumberCodes = nil then
begin
Stream := TResourceStream.Create(HInstance, 'NUMBERS', 'UNICODEDATA');
// Numbers are special (compared to other Unicode data) as they utilize two
// arrays, one containing all used numbers (in nominator-denominator format) and
// another one which maps a code point to one of the numbers in the first array.
// a) determine size of numbers array
Stream.ReadBuffer(Size, 4);
SetLength(Numbers, Size);
// b) read numbers data
Stream.ReadBuffer(Numbers[0], Size * SizeOf(TUcNumber));
// c) determine size of index array
Stream.ReadBuffer(Size, 4);
SetLength(NumberCodes, Size);
// d) read index data
Stream.ReadBuffer(NumberCodes[0], Size * SizeOf(TCodeIndex));
Stream.Free;
end;
finally
LoadInProgress.Leave;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeNumberLookup(Code: UCS4Char; var Number: TUcNumber): Boolean;
// Searches for the given code and returns its number equivalent (if there is one).
// Typical cases are: '1/6' (U+2159), '3/8' (U+215C), 'XII' (U+216B) etc.
// Result is set to True if the code could be found.
var
L, R, M: Integer;
begin
// load number data if not already done
if NumberCodes = nil then
LoadNumberData;
Result := False;
L := 0;
R := High(NumberCodes);
while L <= R do
begin
M := (L + R) shr 1;
if Code > NumberCodes[M].Code then
L := M + 1
else
begin
if Code < NumberCodes[M].Code then
R := M - 1
else
begin
Number := Numbers[NumberCodes[M].Index];
Result := True;
Break;
end;
end;
end;
end;
//----------------- support for composition ----------------------------------------------------------------------------
type
// maps between a pair of code points to a composite code point
// Note: the source pair is packed into one 4 byte value to speed up search.
TCompositionPair = record
Code: Cardinal;
Composition: UCS4Char;
end;
var
// list of composition mappings
Compositions: array of TCompositionPair;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure LoadCompositionData;
var
Stream: TResourceStream;
Size: Cardinal;
begin
// make sure no other code is currently modifying the global data area
LoadInProgress.Enter;
try
if Compositions = nil then
begin
Stream := TResourceStream.Create(HInstance, 'COMPOSITION', 'UNICODEDATA');
// a) determine size of compositions array
Stream.ReadBuffer(Size, 4);
SetLength(Compositions, Size);
// b) read data
Stream.ReadBuffer(Compositions[0], Size * SizeOf(TCompositionPair));
Stream.Free;
end;
finally
LoadInProgress.Leave;
end;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
function UnicodeComposePair(First, Second: UCS4Char; var Composite: UCS4Char): Boolean;
// Maps the sequence of First and Second to a composite.
// Result is True if there was a mapping otherwise it is False.
var
L, R, M, C: Integer;
Pair: Integer;
begin
if Compositions = nil then
LoadCompositionData;
Result := False;
L := 0;
R := High(Compositions);
Pair := Integer((First shl 16) or Word(Second));
while L <= R do
begin
M := (L + R) shr 1;
C := Integer(Compositions[M].Code) - Pair;
if C < 0 then
L := M + 1
else
begin
R := M - 1;
if C = 0 then
begin
Result := True;
L := M;
end;
end;
end;
if Result then
Composite := Compositions[L].Composition;
end;
//----------------- TSearchEngine --------------------------------------------------------------------------------------
constructor TSearchEngine.Create(AOwner: TWideStrings);
begin
FOwner := AOwner;
FResults := TList.Create;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
destructor TSearchEngine.Destroy;
begin
Clear;
FResults.Free;
inherited;
end;
//------------------------------------------------------------------------------------------------------------------------------------------
procedure TSearchEngine.AddResult(Start, Stop: Cardinal);
begin
FResults.Add(Pointer(Start));
FResults.Add(Pointer(Stop));
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSearchEngine.Clear;
begin
ClearResults;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSearchEngine.ClearResults;
begin
FResults.Clear;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSearchEngine.DeleteResult(Index: Cardinal);
// explicitly deletes a search result
begin
with FResults do
begin
// start index
Delete(2 * Index);
// stop index
Delete(2 * Index);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TSearchEngine.GetCount: Integer;
// returns the number of matches found
begin
Result := FResults.Count div 2;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TSearchEngine.GetResult(Index: Cardinal; var Start, Stop: Integer);
// returns the start position of a match (end position can be determined by
// adding the length of the pattern to the start position)
begin
Start := Cardinal(FResults[2 * Index]);
Stop := Cardinal(FResults[2 * Index + 1]);
end;
//----------------- TUTBSearch ---------------------------------------------------------------------
procedure TUTBMSearch.ClearPattern;
begin
FreeMem(FPattern);
FPattern := nil;
FFlags := [];
FPatternUsed := 0;
FPatternSize := 0;
FPatternLength := 0;
FreeMem(FSkipValues);
FSkipValues := nil;
FSkipsUsed := 0;
FMD4 := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.GetSkipValue(TextStart, TextEnd: PUCS2Char): Cardinal;
// looks up the SkipValues value for a character
var
I: Integer;
C1,
C2: UCS4Char;
Sp: PUTBMSkip;
begin
Result := 0;
if Cardinal(TextStart) < Cardinal(TextEnd) then
begin
C1 := UCS4Char(TextStart^);
if (TextStart + 1) < TextEnd then
C2 := UCS4Char((TextStart + 1)^)
else
C2 := $FFFFFFFF;
if (SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) and
(SurrogateLowStart <= C2) and (C2 <= $DDDD) then
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
Sp := FSkipValues;
for I := 0 to FSkipsUsed - 1 do
begin
if not (Boolean(C1 xor Sp.BMChar.UpCase) and
Boolean(C1 xor Sp.BMChar.LoCase) and
Boolean(C1 xor Sp.BMChar.TitleCase)) then
begin
if (TextEnd - TextStart) < Sp.SkipValues then
Result := TextEnd - TextStart
else
Result := Sp.SkipValues;
Exit;
end;
Inc(Sp);
end;
Result := FPatternLength;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.Match(Text, Start, Stop: PUCS2Char; var MatchStart, MatchEnd: Cardinal): Boolean;
// Checks once whether the text at position Start (which points to the end of the
// current text part to be matched) matches.
// Note: If whole words only are allowed then the left and right border tests are
// done here too. The keypoint for the right border is that the next character
// after the search string is either the text end or a space character.
// For the left side this is similar, but there is nothing like a string
// start marker (like the string end marker #0).
//
// It seems not obvious, but we still can use the passed Text pointer to do
// the left check. Although this pointer might not point to the real string
// start (e.g. in TUTBMSearch.FindAll Text is incremented as needed) it is
// still a valid check mark. The reason is that Text either points to the
// real string start or a previous match (happend already, keep in mind the
// search options do not change in the FindAll loop) and the character just
// before Text is a space character.
// This fact implies, though, that strings passed to Find (or FindFirst,
// FindAll in TUTBMSearch) always really start at the given address. Although
// this might not be the case in some circumstances (e.g. if you pass only
// the selection from an editor) it is still assumed that a pattern matching
// from the first position on (from the search string start) also matches
// when whole words only are allowed.
var
CheckSpace: Boolean;
C1, C2: UCS4Char;
Count: Integer;
Cp: PUTBMChar;
begin
// be pessimistic
Result := False;
// set the potential match endpoint first
MatchEnd := (Start - Text) + 1;
C1 := UCS4Char(Start^);
if (Start + 1) < Stop then
C2 := UCS4Char((Start + 1)^)
else
C2 := $FFFFFFFF;
if (SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) and
(SurrogateLowStart <= C2) and (C2 <= SurrogateLowEnd) then
begin
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
// Adjust the match end point to occur after the UTF-16 character.
Inc(MatchEnd);
end;
// check special cases
if FPatternUsed = 1 then
begin
MatchStart := Start - Text;
Result := True;
Exit;
end;
// Early out if entire words need to be matched and the next character
// in the search string is neither the string end nor a space character.
if (sfWholeWordOnly in FFlags) and
not ((Start + 1)^ = WideNull) and
not UnicodeIsWhiteSpace(UCS4Char((Start + 1)^)) then
Exit;
// compare backward
Cp := FPattern;
Inc(Cp, FPatternUsed - 1);
Count := FPatternLength;
while (Start >= Text) and (Count > 0) do
begin
// ignore non-spacing characters if indicated
if sfIgnoreNonSpacing in FFlags then
begin
while (Start > Text) and UnicodeIsNonSpacing(C1) do
begin
Dec(Start);
C2 := UCS4Char(Start^);
if (Start - 1) > Text then
C1 := UCS4Char((Start - 1)^)
else
C1 := $FFFFFFFF;
if (SurrogateLowStart <= C2) and (C2 <= SurrogateLowEnd) and
(SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) then
begin
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
Dec(Start);
end
else
C1 := C2;
end;
end;
// handle space compression if indicated
if sfSpaceCompress in FFlags then
begin
CheckSpace := False;
while (Start > Text) and (UnicodeIsWhiteSpace(C1) or UnicodeIsControl(C1)) do
begin
CheckSpace := UnicodeIsWhiteSpace(C1);
Dec(Start);
C2 := UCS4Char(Start^);
if (Start - 1) > Text then
C1 := UCS4Char((Start - 1)^)
else
C1 := $FFFFFFFF;
if (SurrogateLowStart <= C2) and (C2 <= SurrogateLowEnd) and
(SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) then
begin
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
Dec(Start);
end
else
C1 := C2;
end;
// Handle things if space compression was indicated and one or
// more member characters were found.
if CheckSpace then
begin
if Cp.UpCase <> $20 then
Exit;
Dec(Cp);
Dec(Count);
// If Count is 0 at this place then the space character(s) was the first
// in the pattern and we need to correct the start position.
if Count = 0 then
Inc(Start);
end;
end;
// handle the normal comparison cases
if (Count > 0) and
(Boolean(C1 xor Cp.UpCase) and
Boolean(C1 xor Cp.LoCase) and
Boolean(C1 xor Cp.TitleCase)) then
Exit;
if C1 >= $10000 then
Dec(Count, 2)
else
Dec(Count, 1);
if Count > 0 then
begin
Dec(Cp);
// get the next preceding character
if Start > Text then
begin
Dec(Start);
C2 := UCS4Char(Start^);
if (Start - 1) > Text then
C1 := UCS4Char((Start - 1)^)
else
C1 := $FFFFFFFF;
if (SurrogateLowStart <= C2) and (C2 <= SurrogateLowEnd) and
(SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) then
begin
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
Dec(Start);
end
else
C1 := C2;
end;
end;
end;
// So far the string matched. Now check its left border for a space character
// if whole word only are allowed.
if not (sfWholeWordOnly in FFlags) or
(Start <= Text) or
UnicodeIsWhiteSpace(UCS4Char((Start - 1)^)) then
begin
// set the match start position
MatchStart := Start - Text;
Result := True;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TUTBMSearch.Compile(Pattern: PUCS2Char; PatternLength: Integer; Flags: TSearchFlags);
var
HaveSpace: Boolean;
I, J, K,
SLen: Integer;
Cp: PUTBMChar;
Sp: PUTBMSkip;
C1, C2,
Sentinel: UCS4Char;
begin
if (Pattern <> nil) and (Pattern^ <> #0) and (PatternLength > 0) then
begin
// do some initialization
FFlags := Flags;
// extra skip flag
FMD4 := 1;
Sentinel := 0;
// allocate more storage if necessary
FPattern := AllocMem(SizeOf(TUTBMChar) * PatternLength);
FSkipValues := AllocMem(SizeOf(TUTBMSkip) * PatternLength);
FPatternSize := PatternLength;
// Preprocess the pattern to remove controls (if specified) and determine case.
Cp := FPattern;
I := 0;
HaveSpace := False;
while I < PatternLength do
begin
C1 := UCS4Char(Pattern[I]);
if (I + 1) < PatternLength then
C2 := UCS4Char(Pattern[I + 1])
else
C2 := $FFFFFFFF;
if (SurrogateHighStart <= C1) and (C1 <= SurrogateHighEnd) and
(SurrogateLowStart <= C2) and (C2 <= SurrogateLowEnd) then
C1 := $10000 + (((C1 and $03FF) shl 10) or (C2 and $03FF));
// Make sure the HaveSpace flag is turned off if the character is not an
// appropriate one.
if not UnicodeIsWhiteSpace(C1) then
HaveSpace := False;
// If non-spacing characters should be ignored, do it here.
if (sfIgnoreNonSpacing in Flags) and UnicodeIsNonSpacing(C1) then
begin
Inc(I);
Continue;
end;
// check if spaces and controls need to be compressed
if sfSpaceCompress in Flags then
begin
if UnicodeIsWhiteSpace(C1) then
begin
if not HaveSpace then
begin
// Add a space and set the flag.
Cp.UpCase := $20;
Cp.LoCase := $20;
Cp.TitleCase := $20;
Inc(Cp);
// increase the real pattern length
Inc(FPatternLength);
Sentinel := $20;
HaveSpace := True;
end;
Inc(I);
Continue;
end;
// ignore all control characters
if UnicodeIsControl(C1) then
begin
Inc(I);
Continue;
end;
end;
// add the character
if not (sfCaseSensitive in Flags) then
begin
// TODO: use the entire mapping, not only the first character
Cp.UpCase := UnicodeToUpper(C1)[0];
Cp.LoCase := UnicodeToLower(C1)[0];
Cp.TitleCase := UnicodeToTitle(C1)[0];
end
else
begin
Cp.UpCase := C1;
Cp.LoCase := C1;
Cp.TitleCase := C1;
end;
Sentinel := Cp.UpCase;
// move to the next character
Inc(Cp);
// increase the real pattern length appropriately
if C1 >= $10000 then
Inc(FPatternLength, 2)
else
Inc(FPatternLength);
// increment the loop index for UTF-16 characters
if C1 > $10000 then
Inc(I, 2)
else
Inc(I);
end;
// set the number of characters actually used
FPatternUsed := (PChar(Cp) - PChar(FPattern)) div SizeOf(TUTBMChar);
// Go through and construct the skip array and determine the actual length
// of the pattern in UCS2Char terms.
SLen := FPatternLength - 1;
Cp := FPattern;
K := 0;
for I := 0 to FPatternUsed - 1 do
begin
// locate the character in the FSkipValues array
Sp := FSkipValues;
J := 0;
while (J < FSkipsUsed) and (Sp.BMChar.UpCase <> Cp.UpCase) do
begin
Inc(J);
Inc(Sp);
end;
// If the character is not found, set the new FSkipValues element and
// increase the number of FSkipValues elements.
if J = FSkipsUsed then
begin
Sp.BMChar := Cp;
Inc(FSkipsUsed);
end;
// Set the updated FSkipValues value. If the character is UTF-16 and is
// not the last one in the pattern, add one to its FSkipValues value.
Sp.SkipValues := SLen - K;
if (Cp.UpCase >= $10000) and ((K + 2) < SLen) then
Inc(Sp.SkipValues);
// set the new extra FSkipValues for the sentinel character
if ((Cp.UpCase >= $10000) and
((K + 2) <= SLen) or ((K + 1) <= SLen) and
(Cp.UpCase = Sentinel)) then
FMD4 := SLen - K;
// increase the actual index
if Cp.UpCase >= $10000 then
Inc(K, 2)
else
Inc(K);
Inc(Cp);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.Find(Text: PUCS2Char; TextLen: Cardinal; var MatchStart, MatchEnd: Cardinal): Boolean;
// this is the main matching routine using a tuned Boyer-Moore algorithm
var
K: Cardinal;
Start,
Stop: PUCS2Char;
begin
Result := False;
if (FPattern <> nil) and (FPatternUsed > 0) and (Text <> nil) and
(TextLen > 0) and (TextLen >= FPatternLength) then
begin
Start := Text + FPatternLength - 1;
Stop := Text + TextLen;
// adjust the start point if it points to a low surrogate
if (SurrogateLowStart <= UCS4Char(Start^)) and
(UCS4Char(Start^) <= SurrogateLowEnd) and
(SurrogateHighStart <= UCS4Char((Start - 1)^)) and
(UCS4Char((Start - 1)^) <= SurrogateHighEnd) then
Dec(Start);
while Start < Stop do
begin
repeat
K := GetSkipValue(Start, Stop);
if K = 0 then
Break;
Inc(Start, K);
if (Start < Stop) and
(SurrogateLowStart <= UCS4Char(Start^)) and
(UCS4Char(Start^) <= SurrogateLowEnd) and
(SurrogateHighStart <= UCS4Char((Start - 1)^)) and
(UCS4Char((Start - 1)^) <= SurrogateHighEnd) then
Dec(Start);
until False;
if (Start < Stop) and Match(Text, Start, Stop, MatchStart, MatchEnd) then
begin
Result := True;
Break;
end;
Inc(Start, FMD4);
if (Start < Stop) and
(SurrogateLowStart <= UCS4Char(Start^)) and
(UCS4Char(Start^) <= SurrogateLowEnd) and
(SurrogateHighStart <= UCS4Char((Start - 1)^)) and
(UCS4Char((Start - 1)^) <= SurrogateHighEnd) then
Dec(Start);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TUTBMSearch.Clear;
begin
ClearPattern;
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.FindAll(const Text: WideString): Boolean;
begin
Result := FindAll(PWideChar(Text), Length(Text));
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.FindAll(const Text: PWideChar; TextLen: Cardinal): Boolean;
// Looks for all occurences of the pattern passed to FindPrepare and creates an
// internal list of their positions.
var
Start, Stop: Cardinal;
Run: PWideChar;
RunLen: Cardinal;
begin
ClearResults;
Run := Text;
RunLen := TextLen;
// repeat to find all occurences of the pattern
while Find(Run, RunLen, Start, Stop) do
begin
// store this result (consider text pointer movement)...
AddResult(Start + Run - Text, Stop + Run - Text);
// ... and advance text position and length
Inc(Run, Stop);
Dec(RunLen, Stop);
end;
Result := Count > 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.FindFirst(const Text: WideString; var Start, Stop: Cardinal): Boolean;
// Looks for the first occurence of the pattern passed to FindPrepare in Text and
// returns True if one could be found (in which case Start and Stop are set to
// the according indices) otherwise False. This function is in particular of
// interest if only one occurence needs to be found.
begin
ClearResults;
Result := Find(PWideChar(Text), Length(Text), Start, Stop);
if Result then
AddResult(Start, Stop);
end;
//----------------------------------------------------------------------------------------------------------------------
function TUTBMSearch.FindFirst(const Text: PWideChar; TextLen: Cardinal; var Start, Stop: Cardinal): Boolean;
// Same as the WideString version of this method.
begin
ClearResults;
Result := Find(Text, TextLen, Start, Stop);
if Result then
AddResult(Start, Stop);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TUTBMSearch.FindPrepare(const Pattern: WideString; Options: TSearchFlags);
begin
FindPrepare(PWideChar(Pattern), Length(Pattern), Options);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TUTBMSearch.FindPrepare(const Pattern: PWideChar; PatternLength: Cardinal; Options: TSearchFlags);
// prepares following search by compiling the given pattern into an internal structure
begin
Compile(Pattern, PatternLength, Options);
end;
//----------------- Unicode RE search core ---------------------------------------------------------
const
// error codes
_URE_OK = 0;
_URE_UNEXPECTED_EOS = -1;
_URE_CCLASS_OPEN = -2;
_URE_UNBALANCED_GROUP = -3;
_URE_INVALID_PROPERTY = -4;
_URE_INVALID_RANGE = -5;
_URE_RANGE_OPEN = -6;
// options that can be combined for searching
URE_IGNORE_NONSPACING = $01;
URE_DONT_MATCHES_SEPARATORS = $02;
const
// Flags used internally in the DFA
_URE_DFA_CASEFOLD = $01;
_URE_DFA_BLANKLINE = $02;
// symbol types for the DFA
_URE_ANY_CHAR = 1;
_URE_CHAR = 2;
_URE_CCLASS = 3;
_URE_NCCLASS = 4;
_URE_BOL_ANCHOR = 5;
_URE_EOL_ANCHOR = 6;
// op codes for converting the NFA to a DFA
_URE_SYMBOL = 10;
_URE_PAREN = 11;
_URE_QUEST = 12;
_URE_STAR = 13;
_URE_PLUS = 14;
_URE_ONE = 15;
_URE_AND = 16;
_URE_OR = 17;
_URE_NOOP = $FFFF;
//----------------- TURESearch ---------------------------------------------------------------------
procedure TURESearch.Clear;
begin
inherited;
ClearUREBuffer;
ClearDFA;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.Push(V: Cardinal);
begin
with FUREBuffer do
begin
// If the 'Reducing' parameter is True, check to see if the value passed is
// already on the stack.
if Reducing and ExpressionList.Expressions[Word(V)].OnStack then
Exit;
if Stack.ListUsed = Length(Stack.List) then
SetLength(Stack.List, Length(Stack.List) + 8);
Stack.List[Stack.ListUsed] := V;
Inc(Stack.ListUsed);
// If the 'reducing' parameter is True, flag the element as being on the Stack.
if Reducing then
ExpressionList.Expressions[Word(V)].OnStack := True;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.Peek: Cardinal;
begin
if FUREBuffer.Stack.ListUsed = 0 then
Result := _URE_NOOP
else
Result := FUREBuffer.Stack.List[FUREBuffer.Stack.ListUsed - 1];
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.Pop: Cardinal;
begin
if FUREBuffer.Stack.ListUsed = 0 then
Result := _URE_NOOP
else
begin
Dec(FUREBuffer.Stack.ListUsed);
Result := FUREBuffer.Stack.List[FUREBuffer.Stack.ListUsed];
if FUREBuffer.Reducing then
FUREBuffer.ExpressionList.Expressions[Word(Result)].OnStack := False;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.ParsePropertyList(Properties: PUCS2Char; Limit: Cardinal;
var Categories: TCharacterCategories): Cardinal;
// Parse a comma-separated list of integers that represent character properties.
// Combine them into a set of categories and return the number of characters consumed.
var
N: Cardinal;
Run,
ListEnd: PUCS2Char;
begin
Run := Properties;
ListEnd := Run + Limit;
N := 0;
Categories := [];
while (FUREBuffer.Error = _URE_OK) and (Run < ListEnd) do
begin
if Run^ = ',' then
begin
// Encountered a comma, so take the number parsed so far as category and
// reset the number.
Include(Categories, TCharacterCategory(N));
N := 0;
end
else
begin
if (Run^ >= '0') and (Run^ <= '9') then
begin
// Encountered a digit, so start or continue building the cardinal that
// represents the character category.
N := (N * 10) + Cardinal(Word(Run^) - Ord('0'));
end
else
begin
// Encountered something that is not part of the property list.
// Indicate that we are done.
Break;
end;
end;
// If the number is to large then there is a problem.
// Most likely a missing comma separator.
if Integer(N) > Ord(High(TCharacterCategory)) then
FUREBuffer.Error := _URE_INVALID_PROPERTY;
Inc(Run);
end;
// Return the number of characters consumed.
Result := Run - Properties;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.MakeHexNumber(NP: PUCS2Char; Limit: Cardinal; var Number: UCS4Char): Cardinal;
// Collect a hex number with 1 to 4 digits and return the number of characters used.
var
I: Integer;
Run,
ListEnd: PUCS2Char;
begin
Run := np;
ListEnd := Run + Limit;
Number := 0;
I := 0;
while (I < 4) and (Run < ListEnd) do
begin
if (Run^ >= '0') and (Run^ <= '9') then
Number := (Number shl 4) + Cardinal(Word(Run^) - Ord('0'))
else
begin
if (Run^ >= 'A') and (Run^ <= 'F') then
Number := (Number shl 4) + Cardinal(Word(Run^) - Ord('A')) + 10
else
begin
if (Run^ >= 'a') and (Run^ <= 'f') then
Number := (Number shl 4) + Cardinal(Word(Run^) - Ord('a')) + 10
else
Break;
end;
end;
Inc(I);
Inc(Run);
end;
Result := Run - NP;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.AddRange(var CCL: TUcCClass; Range: TUcRange);
// Insert a Range into a character class, removing duplicates and ordering them
// in increasing Range-start order.
var
I: Integer;
Temp: UCS4Char;
begin
// If the `Casefold' flag is set, then make sure both endpoints of the Range
// are converted to lower.
if (FUREBuffer.Flags and _URE_DFA_CASEFOLD) <> 0 then
begin
// TODO: use the entire mapping, not only the first character
Range.MinCode := UnicodeToLower(Range.MinCode)[0];
Range.MaxCode := UnicodeToLower(Range.MaxCode)[0];
end;
// Swap the Range endpoints if they are not in increasing order.
if Range.MinCode > Range.MaxCode then
begin
Temp := Range.MinCode;
Range.MinCode := Range.MaxCode;
Range.MaxCode := Temp;
end;
I := 0;
while (I < CCL.RangesUsed) and (Range.MinCode < CCL.Ranges[I].MinCode) do
Inc(I);
// check for a duplicate
if (I < CCL.RangesUsed) and (Range.MinCode = CCL.Ranges[I].MinCode) and
(Range.MaxCode = CCL.Ranges[I].MaxCode) then
Exit;
if CCL.RangesUsed = Length(CCL.Ranges) then
SetLength(CCL.Ranges, Length(CCL.Ranges) + 8);
if I < CCL.RangesUsed then
Move(CCL.Ranges[I], CCL.Ranges[I + 1], SizeOf(TUcRange) * (CCL.RangesUsed - I));
CCL.Ranges[I].MinCode := Range.MinCode;
CCL.Ranges[I].MaxCode := Range.MaxCode;
Inc(CCL.RangesUsed);
end;
//----------------------------------------------------------------------------------------------------------------------
type
PTrie = ^TTrie;
TTrie = record
Key: UCS2Char;
Len,
Next: Cardinal;
Setup: Integer;
Categories: TCharacterCategories;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.SpaceSetup(Symbol: PUcSymbolTableEntry; Categories: TCharacterCategories);
var
Range: TUcRange;
begin
Symbol.Categories := Symbol.Categories + Categories;
Range.MinCode := UCS4Char(WideTabulator);
Range.MaxCode := UCS4Char(WideTabulator);
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := UCS4Char(WideCarriageReturn);
Range.MaxCode := UCS4Char(WideCarriageReturn);
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := UCS4Char(WideLineFeed);
Range.MaxCode := UCS4Char(WideLineFeed);
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := UCS4Char(WideFormFeed);
Range.MaxCode := UCS4Char(WideFormFeed);
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := $FEFF;
Range.MaxCode := $FEFF;
AddRange(Symbol.Symbol.CCL, Range);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.HexDigitSetup(Symbol: PUcSymbolTableEntry);
var
Range: TUcRange;
begin
Range.MinCode := UCS4Char('0');
Range.MaxCode := UCS4Char('9');
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := UCS4Char('A');
Range.MaxCode := UCS4Char('F');
AddRange(Symbol.Symbol.CCL, Range);
Range.MinCode := UCS4Char('a');
Range.MaxCode := UCS4Char('f');
AddRange(Symbol.Symbol.CCL, Range);
end;
//----------------------------------------------------------------------------------------------------------------------
const
CClassTrie: array[0..64] of TTrie = (
(Key: #$003A; Len: 1; Next: 1; Setup: 0; Categories: []),
(Key: #$0061; Len: 9; Next: 10; Setup: 0; Categories: []),
(Key: #$0063; Len: 8; Next: 19; Setup: 0; Categories: []),
(Key: #$0064; Len: 7; Next: 24; Setup: 0; Categories: []),
(Key: #$0067; Len: 6; Next: 29; Setup: 0; Categories: []),
(Key: #$006C; Len: 5; Next: 34; Setup: 0; Categories: []),
(Key: #$0070; Len: 4; Next: 39; Setup: 0; Categories: []),
(Key: #$0073; Len: 3; Next: 49; Setup: 0; Categories: []),
(Key: #$0075; Len: 2; Next: 54; Setup: 0; Categories: []),
(Key: #$0078; Len: 1; Next: 59; Setup: 0; Categories: []),
(Key: #$006C; Len: 1; Next: 11; Setup: 0; Categories: []),
(Key: #$006E; Len: 2; Next: 13; Setup: 0; Categories: []),
(Key: #$0070; Len: 1; Next: 16; Setup: 0; Categories: []),
(Key: #$0075; Len: 1; Next: 14; Setup: 0; Categories: []),
(Key: #$006D; Len: 1; Next: 15; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 16; Setup: 1; Categories: ClassLetter + ClassNumber),
(Key: #$0068; Len: 1; Next: 17; Setup: 0; Categories: []),
(Key: #$0061; Len: 1; Next: 18; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 19; Setup: 1; Categories: ClassLetter),
(Key: #$006E; Len: 1; Next: 20; Setup: 0; Categories: []),
(Key: #$0074; Len: 1; Next: 21; Setup: 0; Categories: []),
(Key: #$0072; Len: 1; Next: 22; Setup: 0; Categories: []),
(Key: #$006C; Len: 1; Next: 23; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 24; Setup: 1; Categories: [ccOtherControl, ccOtherFormat]),
(Key: #$0069; Len: 1; Next: 25; Setup: 0; Categories: []),
(Key: #$0067; Len: 1; Next: 26; Setup: 0; Categories: []),
(Key: #$0069; Len: 1; Next: 27; Setup: 0; Categories: []),
(Key: #$0074; Len: 1; Next: 28; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 29; Setup: 1; Categories: ClassNumber),
(Key: #$0072; Len: 1; Next: 30; Setup: 0; Categories: []),
(Key: #$0061; Len: 1; Next: 31; Setup: 0; Categories: []),
(Key: #$0070; Len: 1; Next: 32; Setup: 0; Categories: []),
(Key: #$0068; Len: 1; Next: 33; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 34; Setup: 1; Categories: ClassMark + ClassNumber + ClassLetter + ClassPunctuation +
ClassSymbol),
(Key: #$006F; Len: 1; Next: 35; Setup: 0; Categories: []),
(Key: #$0077; Len: 1; Next: 36; Setup: 0; Categories: []),
(Key: #$0065; Len: 1; Next: 37; Setup: 0; Categories: []),
(Key: #$0072; Len: 1; Next: 38; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 39; Setup: 1; Categories: [ccLetterLowercase]),
(Key: #$0072; Len: 2; Next: 41; Setup: 0; Categories: []),
(Key: #$0075; Len: 1; Next: 45; Setup: 0; Categories: []),
(Key: #$0069; Len: 1; Next: 42; Setup: 0; Categories: []),
(Key: #$006E; Len: 1; Next: 43; Setup: 0; Categories: []),
(Key: #$0074; Len: 1; Next: 44; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 45; Setup: 1; Categories: ClassMark + ClassNumber + ClassLetter + ClassPunctuation +
ClassSymbol + [ccSeparatorSpace]),
(Key: #$006E; Len: 1; Next: 46; Setup: 0; Categories: []),
(Key: #$0063; Len: 1; Next: 47; Setup: 0; Categories: []),
(Key: #$0074; Len: 1; Next: 48; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 49; Setup: 1; Categories: ClassPunctuation),
(Key: #$0070; Len: 1; Next: 50; Setup: 0; Categories: []),
(Key: #$0061; Len: 1; Next: 51; Setup: 0; Categories: []),
(Key: #$0063; Len: 1; Next: 52; Setup: 0; Categories: []),
(Key: #$0065; Len: 1; Next: 53; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 54; Setup: 2; Categories: ClassSpace),
(Key: #$0070; Len: 1; Next: 55; Setup: 0; Categories: []),
(Key: #$0070; Len: 1; Next: 56; Setup: 0; Categories: []),
(Key: #$0065; Len: 1; Next: 57; Setup: 0; Categories: []),
(Key: #$0072; Len: 1; Next: 58; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 59; Setup: 1; Categories: [ccLetterUppercase]),
(Key: #$0064; Len: 1; Next: 60; Setup: 0; Categories: []),
(Key: #$0069; Len: 1; Next: 61; Setup: 0; Categories: []),
(Key: #$0067; Len: 1; Next: 62; Setup: 0; Categories: []),
(Key: #$0069; Len: 1; Next: 63; Setup: 0; Categories: []),
(Key: #$0074; Len: 1; Next: 64; Setup: 0; Categories: []),
(Key: #$003A; Len: 1; Next: 65; Setup: 3; Categories: [])
);
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.PosixCCL(CP: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
// Probe for one of the POSIX colon delimited character classes in the static trie.
var
I: Integer;
N: Cardinal;
TP: PTrie;
Run,
ListEnd: PUCS2Char;
begin
Result := 0;
// If the number of characters left is less than 7,
// then this cannot be interpreted as one of the colon delimited classes.
if Limit >= 7 then
begin
Run := cp;
ListEnd := Run + Limit;
TP := @CClassTrie[0];
I := 0;
while (Run < ListEnd) and (I < 8) do
begin
N := TP.Len;
while (N > 0) and (TP.Key <> Run^) do
begin
Inc(TP);
Dec(N);
end;
if N = 0 then
begin
Result := 0;
Exit;
end;
if (Run^ = ':') and ((I = 6) or (I = 7)) then
begin
Inc(Run);
Break;
end;
if (Run + 1) < ListEnd then
TP := @CClassTrie[TP.Next];
Inc(I);
Inc(Run);
end;
Result := Run - CP;
case TP.Setup of
1:
Symbol.Categories := Symbol.Categories + TP.Categories;
2:
SpaceSetup(Symbol, TP.Categories);
3:
HexDigitSetup(Symbol);
else
Result := 0;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.BuildCharacterClass(CP: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
// Construct a list of ranges and return the number of characters consumed.
var
RangeEnd: Integer;
N: Cardinal;
Run,
ListEnd: PUCS2Char;
C, Last: UCS4Char;
Range: TUcRange;
begin
Run := cp;
ListEnd := Run + Limit;
if Run^ = '^' then
begin
Symbol.AType := _URE_NCCLASS;
Inc(Run);
end
else
Symbol.AType := _URE_CCLASS;
Last := 0;
RangeEnd := 0;
while (FUREBuffer.Error = _URE_OK) and (Run < ListEnd) do
begin
// Allow for the special case []abc], where the first closing bracket would end an empty
// character class, which makes no sense. Hence this bracket is treaded literally.
if (Run^ = ']') and (Symbol.Symbol.CCL.RangesUsed > 0) then
Break;
C := UCS4Char(Run^);
Inc(Run);
// escape character
if C = Ord('\') then
begin
if Run = ListEnd then
begin
// The EOS was encountered when expecting the reverse solidus to be followed by the character it is escaping.
// Set an Error code and return the number of characters consumed up to this point.
FUREBuffer.Error := _URE_UNEXPECTED_EOS;
Result := Run - CP;
Exit;
end;
C := UCS4Char(Run^);
Inc(Run);
case UCS2Char(C) of
'a':
C := $07;
'b':
C := $08;
'f':
C := $0C;
'n':
C := $0A;
'R':
C := $0D;
't':
C := $09;
'v':
C := $0B;
'p', 'P':
begin
Inc(Run, ParsePropertyList(Run, ListEnd - Run, Symbol.Categories));
// Invert the bit mask of the properties if this is a negated character class or if 'P' is used to specify
// a list of character properties that should *not* match in a character class.
if C = Ord('P') then
Symbol.Categories := ClassAll - Symbol.Categories;
Continue;
end;
'x', 'X', 'u', 'U':
begin
if (Run < ListEnd) and
((Run^ >= '0') and (Run^ <= '9') or
(Run^ >= 'A') and (Run^ <= 'F') or
(Run^ >= 'a') and (Run^ <= 'f')) then
Inc(Run, MakeHexNumber(Run, ListEnd - Run, C));
end;
end;
end
else
begin
if C = Ord(':') then
begin
// Probe for a POSIX colon delimited character class.
Dec(Run);
N := PosixCCL(Run, ListEnd - Run, Symbol);
if N = 0 then
Inc(Run)
else
begin
Inc(Run, N);
Continue;
end;
end;
end;
// Check to see if the current character is a low surrogate that needs
// to be combined with a preceding high surrogate.
if Last <> 0 then
begin
if (C >= SurrogateLowStart) and (C <= SurrogateLowEnd) then
begin
// Construct the UTF16 character code.
C := $10000 + (((Last and $03FF) shl 10) or (C and $03FF))
end
else
begin
// Add the isolated high surrogate to the range.
if RangeEnd = 1 then
Range.MaxCode := Last and $FFFF
else
begin
Range.MinCode := Last and $FFFF;
Range.MaxCode := Last and $FFFF;
end;
AddRange(Symbol.Symbol.CCL, Range);
RangeEnd := 0;
end;
end;
// Clear the Last character code.
Last := 0;
// This slightly awkward code handles the different cases needed to construct a range.
if (C >= SurrogateHighStart) and (C <= SurrogateHighEnd) then
begin
// If the high surrogate is followed by a Range indicator, simply add it as the Range start. Otherwise,
// save it in the next character is a low surrogate.
if Run^ = '-' then
begin
Inc(Run);
Range.MinCode := C;
RangeEnd := 1;
end
else
Last := C;
end
else
begin
if RangeEnd = 1 then
begin
Range.MaxCode := C;
AddRange(Symbol.Symbol.CCL, Range);
RangeEnd := 0;
end
else
begin
Range.MinCode := C;
Range.MaxCode := C;
if Run^ = '-' then
begin
Inc(Run);
RangeEnd := 1;
end
else
AddRange(Symbol.Symbol.CCL, Range);
end;
end;
end;
if (Run < ListEnd) and (Run^ = ']') then
Inc(Run)
else
begin
// The parse was not terminated by the character class close symbol (']'), so set an error code.
FUREBuffer.Error := _URE_CCLASS_OPEN;
end;
Result := Run - CP;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.ProbeLowSurrogate(LeftState: PUCS2Char; Limit: Cardinal; var Code: UCS4Char): Cardinal;
// probes for a low surrogate hex code
var
I: Integer;
Run,
ListEnd: PUCS2Char;
begin
I := 0;
Code := 0;
Run := LeftState;
ListEnd := Run + Limit;
while (I < 4) and (Run < ListEnd) do
begin
if (Run^ >= '0') and (Run^ <= '9') then
Code := (Code shl 4) + Cardinal(Word(Run^) - Ord('0'))
else
begin
if (Run^ >= 'A') and (Run^ <= 'F') then
Code := (Code shl 4) + Cardinal(Word(Run^) - Ord('A')) + 10
else
begin
if (Run^ >= 'a') and (Run^ <= 'f') then
Code := (Code shl 4) + Cardinal(Word(Run^) - Ord('a')) + 10
else
Break;
end;
end;
Inc(Run);
end;
if (SurrogateLowStart <= Code) and (Code <= SurrogateLowEnd) then
Result := Run - LeftState
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.CompileSymbol(S: PUCS2Char; Limit: Cardinal; Symbol: PUcSymbolTableEntry): Cardinal;
var
C: UCS4Char;
Run,
ListEnd: PUCS2Char;
begin
Run := S;
ListEnd := S + Limit;
C := UCS4Char(Run^);
Inc(Run);
if C = Ord('\') then
begin
if Run = ListEnd then
begin
// The EOS was encountered when expecting the reverse solidus to be followed
// by the character it is escaping. Set an Error code and return the number
// of characters consumed up to this point.
FUREBuffer.Error := _URE_UNEXPECTED_EOS;
Result := Run - S;
Exit;
end;
C := UCS4Char(Run^);
Inc(Run);
case UCS2Char(C) of
'p', 'P':
begin
if UCS2Char(C) = 'p' then
Symbol.AType := _URE_CCLASS
else
Symbol.AType := _URE_NCCLASS;
Inc(Run, ParsePropertyList(Run, ListEnd - Run, Symbol.Categories));
end;
'a':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $07;
end;
'b':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $08;
end;
'f':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $0C;
end;
'n':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $0A;
end;
'r':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $0D;
end;
't':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $09;
end;
'v':
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := $0B;
end;
else
case UCS2Char(C) of
'x', 'X', 'u', 'U':
begin
// Collect between 1 and 4 digits representing an UCS2Char code.
if (Run < ListEnd) and
((Run^ >= '0') and (Run^ <= '9') or
(Run^ >= 'A') and (Run^ <= 'F') or
(Run^ >= 'a') and (Run^ <= 'f')) then
Inc(Run, MakeHexNumber(Run, ListEnd - Run, C));
end;
end;
// Simply add an escaped character here.
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := C;
end;
end
else
begin
if (UCS2Char(C) = '^') or (UCS2Char(C) = '$') then
begin
// Handle the BOL and EOL anchors. This actually consists simply of setting
// a flag that indicates that the user supplied anchor match function should
// be called. This needs to be done instead of simply matching line/paragraph
// separators because beginning-of-text and end-of-text tests are needed as well.
if UCS2Char(C) = '^' then
Symbol.AType := _URE_BOL_ANCHOR
else
Symbol.AType := _URE_EOL_ANCHOR;
end
else
begin
if UCS2Char(C) = '[' then
begin
// construct a character class
Inc(Run, BuildCharacterClass(Run, ListEnd - Run, Symbol));
end
else
begin
if UCS2Char(C) = '.' then
Symbol.AType := _URE_ANY_CHAR
else
begin
Symbol.AType := _URE_CHAR;
Symbol.Symbol.Chr := C;
end;
end;
end;
end;
// If the symbol type happens to be a character and is a high surrogate, then
// probe forward to see if it is followed by a low surrogate that needs to be added.
if (Run < ListEnd) and
(Symbol.AType = _URE_CHAR) and
(SurrogateHighStart <= Symbol.Symbol.Chr) and
(Symbol.Symbol.Chr <= SurrogateHighEnd) then
begin
if (SurrogateLowStart <= UCS4Char(Run^)) and
(UCS4Char(Run^) <= SurrogateLowEnd) then
begin
Symbol.Symbol.Chr := $10000 + (((Symbol.Symbol.Chr and $03FF) shl 10) or (UCS4Char(Run^) and $03FF));
Inc(Run);
end
else
begin
if (Run^ = '\') and (((Run + 1)^ = 'x') or ((Run + 1)^ = 'X') or
((Run + 1)^ = 'u') or ((Run + 1)^ = 'U')) then
begin
Inc(Run, ProbeLowSurrogate(Run + 2, ListEnd - (Run + 2), C));
if (SurrogateLowStart <= C) and (C <= SurrogateLowEnd) then
begin
// Take into account the \[xu] in front of the hex code.
Inc(Run, 2);
Symbol.Symbol.Chr := $10000 + (((Symbol.Symbol.Chr and $03FF) shl 10) or (C and $03FF));
end;
end;
end;
end;
// Last, make sure any _URE_CHAR type symbols are changed to lower if the
// 'Casefold' flag is set.
// TODO: use the entire mapping, not only the first character and use the
// case fold abilities of the unit.
if ((FUREBuffer.Flags and _URE_DFA_CASEFOLD) <> 0) and (Symbol.AType = _URE_CHAR) then
Symbol.Symbol.Chr := UnicodeToLower(Symbol.Symbol.Chr)[0];
// If the symbol constructed is anything other than one of the anchors,
// make sure the _URE_DFA_BLANKLINE flag is removed.
if (Symbol.AType <> _URE_BOL_ANCHOR) and (Symbol.AType <> _URE_EOL_ANCHOR) then
FUREBuffer.Flags := FUREBuffer.Flags and not _URE_DFA_BLANKLINE;
// Return the number of characters consumed.
Result := Run - S;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.SymbolsAreDifferent(A, B: PUcSymbolTableEntry): Boolean;
begin
Result := False;
if (A.AType <> B.AType) or (A.Mods <> B.Mods) or (A.Categories <> B.Categories) then
Result := True
else
begin
if (A.AType = _URE_CCLASS) or (A.AType = _URE_NCCLASS) then
begin
if A.Symbol.CCL.RangesUsed <> B.Symbol.CCL.RangesUsed then
Result := True
else
begin
if (A.Symbol.CCL.RangesUsed > 0) and
not CompareMem(@A.Symbol.CCL.Ranges[0], @B.Symbol.CCL.Ranges[0],
SizeOf(TUcRange) * A.Symbol.CCL.RangesUsed) then
Result := True;
;
end;
end
else
begin
if (A.AType = _URE_CHAR) and (A.Symbol.Chr <> B.Symbol.Chr) then
Result := True;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.MakeSymbol(S: PUCS2Char; Limit: Cardinal; var Consumed: Cardinal): Cardinal;
// constructs a symbol, but only keep unique symbols
var
I: Integer;
Start: PUcSymbolTableEntry;
Symbol: TUcSymbolTableEntry;
begin
// Build the next symbol so we can test to see if it is already in the symbol table.
FillChar(Symbol, SizeOf(TUcSymbolTableEntry), 0);
Consumed := CompileSymbol(S, Limit, @Symbol);
// Check to see if the symbol exists.
I := 0;
Start := @FUREBuffer.SymbolTable.Symbols[0];
while (I < FUREBuffer.SymbolTable.SymbolsUsed) and SymbolsAreDifferent(@Symbol, Start) do
begin
Inc(I);
Inc(Start);
end;
if I < FUREBuffer.SymbolTable.SymbolsUsed then
begin
// Free up any ranges used for the symbol.
if (Symbol.AType = _URE_CCLASS) or (Symbol.AType = _URE_NCCLASS) then
Symbol.Symbol.CCL.Ranges := nil;
Result := FUREBuffer.SymbolTable.Symbols[I].ID;
Exit;
end;
// Need to add the new symbol.
if FUREBuffer.SymbolTable.SymbolsUsed = Length(FUREBuffer.SymbolTable.Symbols) then
begin
SetLength(FUREBuffer.SymbolTable.Symbols, Length(FUREBuffer.SymbolTable.Symbols) + 8);
end;
Symbol.ID := FUREBuffer.SymbolTable.SymbolsUsed;
Inc(FUREBuffer.SymbolTable.SymbolsUsed);
FUREBuffer.SymbolTable.Symbols[Symbol.ID] := Symbol;
Result := Symbol.ID;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.MakeExpression(AType, LHS, RHS: Cardinal): Cardinal;
var
I: Integer;
begin
// Determine if the expression already exists or not.
with FUREBuffer.ExpressionList do
begin
for I := 0 to ExpressionsUsed - 1 do
begin
if (Expressions[I].AType = AType) and
(Expressions[I].LHS = LHS) and
(Expressions[I].RHS = RHS) then
begin
Result := I;
Exit;
end;
end;
// Need to add a new expression.
if ExpressionsUsed = Length(Expressions) then
SetLength(Expressions, Length(Expressions) + 8);
Expressions[ExpressionsUsed].OnStack := False;
Expressions[ExpressionsUsed].AType := AType;
Expressions[ExpressionsUsed].LHS := LHS;
Expressions[ExpressionsUsed].RHS := RHS;
Result := ExpressionsUsed;
Inc(ExpressionsUsed);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function IsSpecial(C: Word): Boolean;
begin
Result := C in [Word('+'), Word('*'), Word('?'), Word('{'), Word('|'), Word(')')];
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.CollectPendingOperations(var State: Cardinal);
// collects all pending AND and OR operations and make corresponding expressions
var
Operation: Cardinal;
begin
repeat
Operation := Peek;
if (Operation <> _URE_AND) and (Operation <> _URE_OR) then
Break;
// make an expression with the AND or OR operator and its right hand side
Operation := Pop;
State := MakeExpression(Operation, Pop, State);
until False;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.ConvertRegExpToNFA(RE: PWideChar; RELength: Cardinal): Cardinal;
// Converts the regular expression into an NFA in a form that will be easy to
// reduce to a DFA. The starting state for the reduction will be returned.
var
C: UCS2Char;
Head, Tail: PUCS2Char;
S: WideString;
Symbol,
State,
LastState,
Used,
M, N: Cardinal;
I: Integer;
begin
State := _URE_NOOP;
Head := RE;
Tail := Head + RELength;
while (FUREBuffer.Error = _URE_OK) and (Head < Tail) do
begin
C := Head^;
Inc(Head);
case C of
'(':
Push(_URE_PAREN);
')': // check for the case of too many close parentheses
begin
if Peek = _URE_NOOP then
begin
FUREBuffer.Error := _URE_UNBALANCED_GROUP;
Break;
end;
CollectPendingOperations(State);
// remove the _URE_PAREN off the stack
Pop;
end;
'*':
State := MakeExpression(_URE_STAR, State, _URE_NOOP);
'+':
State := MakeExpression(_URE_PLUS, State, _URE_NOOP);
'?':
State := MakeExpression(_URE_QUEST, State, _URE_NOOP);
'|':
begin
CollectPendingOperations(State);
Push(State);
Push(_URE_OR);
end;
'{': // expressions of the form {m, n}
begin
C := #0;
M := 0;
N := 0;
// get first number
while UnicodeIsWhiteSpace(UCS4Char(Head^)) do
Inc(Head);
S := '';
while Head^ in [WideChar('0')..WideChar('9')] do
begin
S := S + Head^;
Inc(Head);
end;
if S <> '' then
M := StrToInt(S);
while UnicodeIsWhiteSpace(UCS4Char(Head^)) do
Inc(Head);
if (Head^ <> ',') and (Head^ <> '}') then
begin
FUREBuffer.Error := _URE_INVALID_RANGE;
Break;
end;
// check for an upper limit
if Head^ <> '}' then
begin
Inc(Head);
// get second number
while UnicodeIsWhiteSpace(UCS4Char(Head^)) do
Inc(Head);
S := '';
while Head^ in [WideChar('0')..WideChar('9')] do
begin
S := S + Head^;
Inc(Head);
end;
if S <> '' then
N := StrToInt(S);
end
else
N := M;
if Head^ <> '}' then
begin
FUREBuffer.Error := _URE_RANGE_OPEN;
Break;
end
else
Inc(Head);
// N = 0 means unlimited number of occurences
if N = 0 then
begin
case M of
0: // {,} {0,} {0, 0} mean the same as the star operator
State := MakeExpression(_URE_STAR, State, _URE_NOOP);
1: // {1,} {1, 0} mean the same as the plus operator
State := MakeExpression(_URE_PLUS, State, _URE_NOOP);
else
begin
// encapsulate the expanded branches as would they be in parenthesis
// in order to avoid unwanted concatenation with pending operations/symbols
Push(_URE_PAREN);
// {m,} {m, 0} mean M fixed occurences plus star operator
// make E^m...
for I := 1 to M - 1 do
begin
Push(State);
Push(_URE_AND);
end;
// ...and repeat the last symbol one or more times
State := MakeExpression(_URE_PLUS, State, _URE_NOOP);
CollectPendingOperations(State);
Pop;
end;
end;
end
else
begin
// check proper range limits
if M > N then
begin
FUREBuffer.Error := _URE_INVALID_RANGE;
Break;
end;
// check special case {0, 1} (which corresponds to the ? operator)
if (M = 0) and (N = 1) then
State := MakeExpression(_URE_QUEST, State, _URE_NOOP)
else
begin
// handle the general case by expanding {m, n} into the equivalent
// expression E^m | E^(m + 1) | ... | E^n
// encapsulate the expanded branches as would they be in parenthesis
// in order to avoid unwanted concatenation with pending operations/symbols
Push(_URE_PAREN);
// keep initial state as this is the one all alternatives start from
LastState := State;
// Consider the special case M = 0 first. Because there's no construct
// to enter a pure epsilon-transition into the expression array I
// work around with the question mark operator to describe the first
// and second branch alternative.
if M = 0 then
begin
State := MakeExpression(_URE_QUEST, State, _URE_NOOP);
Inc(M, 2);
// Mark the pending OR operation (there must always follow at
// least on more alternative because the special case {0, 1} has
// already been handled).
Push(State);
Push(_URE_OR);
end;
while M <= N do
begin
State := LastState;
// create E^M
for I := 1 to Integer(M) - 1 do
begin
Push(State);
Push(_URE_AND);
end;
// finish the branch and mark it as pending OR operation if it
// isn't the last one
CollectPendingOperations(State);
if M < N then
begin
Push(State);
Push(_URE_OR);
end;
Inc(M);
end;
// remove the _URE_PAREN off the stack
Pop;
end;
end;
end;
else
Dec(Head);
Symbol := MakeSymbol(Head, Tail - Head, Used);
Inc(Head, Used);
State := MakeExpression(_URE_SYMBOL, Symbol, _URE_NOOP);
end;
if (C <> '(') and (C <> '|') and (C <> '{') and (Head < Tail) and
(not IsSpecial(Word(Head^)) or (Head^ = '(')) then
begin
Push(State);
Push(_URE_AND);
end;
end;
CollectPendingOperations(State);
if FUREBuffer.Stack.ListUsed > 0 then
FUREBuffer.Error := _URE_UNBALANCED_GROUP;
if FUREBuffer.Error = _URE_OK then
Result := State
else
Result := _URE_NOOP;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.AddSymbolState(Symbol, State: Cardinal);
var
I, J: Integer;
Found: Boolean;
begin
// Locate the symbol in the symbol table so the state can be added.
// If the symbol doesn't exist, then we are in serious trouble.
with FUREBuffer.SymbolTable do
begin
I := 0;
while (I < SymbolsUsed) and (Symbol <> Symbols[I].ID) do
Inc(I);
Assert(I < SymbolsUsed);
end;
// Now find out if the state exists in the symbol's state list.
with FUREBuffer.SymbolTable.Symbols[I].States do
begin
Found := False;
for J := 0 to ListUsed - 1 do
begin
if State <= List[J] then
begin
Found := True;
Break;
end;
end;
if not Found then
J := ListUsed;
if not Found or (State < List[J]) then
begin
// Need to add the state in order.
if ListUsed = Length(List) then
SetLength(List, Length(List) + 8);
if J < ListUsed then
Move(List[J], List[J + 1], SizeOf(Cardinal) * (ListUsed - J));
List[J] := State;
Inc(ListUsed);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.AddState(NewStates: array of Cardinal): Cardinal;
var
I: Integer;
Found: Boolean;
begin
Found := False;
for I := 0 to FUREBuffer.States.StatesUsed - 1 do
begin
if (FUREBuffer.States.States[I].StateList.ListUsed = Length(NewStates)) and
CompareMem(@NewStates[0], @FUREBuffer.States.States[I].StateList.List[0],
SizeOf(Cardinal) * Length(NewStates)) then
begin
Found := True;
Break;
end;
end;
if not Found then
begin
// Need to add a new DFA State (set of NFA states).
if FUREBuffer.States.StatesUsed = Length(FUREBuffer.States.States) then
SetLength(FUREBuffer.States.States, Length(FUREBuffer.States.States) + 8);
with FUREBuffer.States.States[FUREBuffer.States.StatesUsed] do
begin
ID := FUREBuffer.States.StatesUsed;
if (StateList.ListUsed + Length(NewStates)) >= Length(StateList.List) then
SetLength(StateList.List, Length(StateList.List) + Length(NewStates) + 8);
Move(NewStates[0], StateList.List[StateList.ListUsed], SizeOf(Cardinal) * Length(NewStates));
Inc(StateList.ListUsed, Length(NewStates));
end;
Inc(FUREBuffer.States.StatesUsed);
end;
// Return the ID of the DFA state representing a group of NFA States.
if Found then
Result := I
else
Result := FUREBuffer.States.StatesUsed - 1;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.Reduce(Start: Cardinal);
var
I, J,
Symbols: Integer;
State,
RHS,
s1, s2,
ns1, ns2: Cardinal;
Evaluating: Boolean;
begin
FUREBuffer.Reducing := True;
// Add the starting state for the reduction.
AddState([Start]);
// Process each set of NFA states that get created.
I := 0;
// further states are added in the loop
while I < FUREBuffer.States.StatesUsed do
begin
with FUREBuffer, States.States[I], ExpressionList do
begin
// Push the current states on the stack.
for J := 0 to StateList.ListUsed - 1 do
Push(StateList.List[J]);
// Reduce the NFA states.
Accepting := False;
Symbols := 0;
J := 0;
// need a while loop here as the stack will be modified within the loop and
// so also its usage count used to terminate the loop
while J < FUREBuffer.Stack.ListUsed do
begin
State := FUREBuffer.Stack.List[J];
Evaluating := True;
// This inner loop is the iterative equivalent of recursively
// reducing subexpressions generated as a result of a reduction.
while Evaluating do
begin
case Expressions[State].AType of
_URE_SYMBOL:
begin
ns1 := MakeExpression(_URE_ONE, _URE_NOOP, _URE_NOOP);
AddSymbolState(Expressions[State].LHS, ns1);
Inc(Symbols);
Evaluating := False;
end;
_URE_ONE:
begin
Accepting := True;
Evaluating := False;
end;
_URE_QUEST:
begin
s1 := Expressions[State].LHS;
ns1 := MakeExpression(_URE_ONE, _URE_NOOP, _URE_NOOP);
State := MakeExpression(_URE_OR, ns1, s1);
end;
_URE_PLUS:
begin
s1 := Expressions[State].LHS;
ns1 := MakeExpression(_URE_STAR, s1, _URE_NOOP);
State := MakeExpression(_URE_AND, s1, ns1);
end;
_URE_STAR:
begin
s1 := Expressions[State].LHS;
ns1 := MakeExpression(_URE_ONE, _URE_NOOP, _URE_NOOP);
ns2 := MakeExpression(_URE_PLUS, s1, _URE_NOOP);
State := MakeExpression(_URE_OR, ns1, ns2);
end;
_URE_OR:
begin
s1 := Expressions[State].LHS;
s2 := Expressions[State].RHS;
Push(s1);
Push(s2);
Evaluating := False;
end;
_URE_AND:
begin
s1 := Expressions[State].LHS;
s2 := Expressions[State].RHS;
case Expressions[s1].AType of
_URE_SYMBOL:
begin
AddSymbolState(Expressions[s1].LHS, s2);
Inc(Symbols);
Evaluating := False;
end;
_URE_ONE:
State := s2;
_URE_QUEST:
begin
ns1 := Expressions[s1].LHS;
ns2 := MakeExpression(_URE_AND, ns1, s2);
State := MakeExpression(_URE_OR, s2, ns2);
end;
_URE_PLUS:
begin
ns1 := Expressions[s1].LHS;
ns2 := MakeExpression(_URE_OR, s2, State);
State := MakeExpression(_URE_AND, ns1, ns2);
end;
_URE_STAR:
begin
ns1 := Expressions[s1].LHS;
ns2 := MakeExpression(_URE_AND, ns1, State);
State := MakeExpression(_URE_OR, s2, ns2);
end;
_URE_OR:
begin
ns1 := Expressions[s1].LHS;
ns2 := Expressions[s1].RHS;
ns1 := MakeExpression(_URE_AND, ns1, s2);
ns2 := MakeExpression(_URE_AND, ns2, s2);
State := MakeExpression(_URE_OR, ns1, ns2);
end;
_URE_AND:
begin
ns1 := Expressions[s1].LHS;
ns2 := Expressions[s1].RHS;
ns2 := MakeExpression(_URE_AND, ns2, s2);
State := MakeExpression(_URE_AND, ns1, ns2);
end;
end;
end;
end;
end;
Inc(J);
end;
// clear the state stack
while Pop <> _URE_NOOP do
{ nothing };
// generate the DFA states for the symbols collected during the current reduction
if (TransitionsUsed + Symbols) > Length(Transitions) then
SetLength(Transitions, Length(Transitions) + Symbols);
// go through the symbol table and generate the DFA state transitions for
// each symbol that has collected NFA states
Symbols := 0;
J := 0;
while J < FUREBuffer.SymbolTable.SymbolsUsed do
begin
begin
if FUREBuffer.SymbolTable.Symbols[J].States.ListUsed > 0 then
begin
Transitions[Symbols].LHS := FUREBuffer.SymbolTable.Symbols[J].ID;
with FUREBuffer.SymbolTable.Symbols[J] do
begin
RHS := AddState(Copy(States.List, 0, States.ListUsed));
States.ListUsed := 0;
end;
Transitions[Symbols].RHS := RHS;
Inc(Symbols);
end;
end;
Inc(J);
end;
// set the number of transitions actually used
// Note: we need again to qualify a part of the TransistionsUsed path since the
// state array could be reallocated in the AddState call above and the
// with ... do will then be invalid.
States.States[I].TransitionsUsed := Symbols;
end;
Inc(I);
end;
FUREBuffer.Reducing := False;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.AddEquivalentPair(L, R: Cardinal);
var
I: Integer;
begin
L := FUREBuffer.States.States[L].ID;
R := FUREBuffer.States.States[R].ID;
if L <> R then
begin
if L > R then
begin
I := L;
L := R;
R := I;
end;
// Check to see if the equivalence pair already exists.
I := 0;
with FUREBuffer.EquivalentList do
begin
while (I < EquivalentsUsed) and
((Equivalents[I].Left <> L) or (Equivalents[I].Right <> R)) do
Inc(I);
if I >= EquivalentsUsed then
begin
if EquivalentsUsed = Length(Equivalents) then
SetLength(Equivalents, Length(Equivalents) + 8);
Equivalents[EquivalentsUsed].Left := L;
Equivalents[EquivalentsUsed].Right := R;
Inc(EquivalentsUsed);
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.MergeEquivalents;
// merges the DFA states that are equivalent
var
I, J, K,
Equal: Integer;
Done: Boolean;
State1, State2,
LeftState,
RightState: PUcState;
begin
for I := 0 to FUREBuffer.States.StatesUsed - 1 do
begin
State1 := @FUREBuffer.States.States[I];
if State1.ID = Cardinal(I) then
begin
J := 0;
while J < I do
begin
State2 := @FUREBuffer.States.States[J];
if State2.ID = Cardinal(J) then
begin
FUREBuffer.EquivalentList.EquivalentsUsed := 0;
AddEquivalentPair(I, J);
Done := False;
Equal := 0;
while Equal < FUREBuffer.EquivalentList.EquivalentsUsed do
begin
LeftState := @FUREBuffer.States.States[FUREBuffer.EquivalentList.Equivalents[Equal].Left];
RightState := @FUREBuffer.States.States[FUREBuffer.EquivalentList.Equivalents[Equal].Right];
if (LeftState.Accepting <> RightState.Accepting) or
(LeftState.TransitionsUsed <> RightState.TransitionsUsed) then
begin
Done := True;
Break;
end;
K := 0;
while (K < LeftState.TransitionsUsed) and
(LeftState.Transitions[K].LHS = RightState.Transitions[K].LHS) do
Inc(K);
if K < LeftState.TransitionsUsed then
begin
Done := True;
Break;
end;
for K := 0 to LeftState.TransitionsUsed - 1 do
AddEquivalentPair(LeftState.Transitions[K].RHS, RightState.Transitions[K].RHS);
Inc(Equal);
end;
if not Done then
Break;
end;
Inc(J);
end;
if J < I then
begin
with FUREBuffer do
begin
for Equal := 0 to EquivalentList.EquivalentsUsed - 1 do
begin
States.States[EquivalentList.Equivalents[Equal].Right].ID :=
States.States[EquivalentList.Equivalents[Equal].Left].ID;
end;
end;
end;
end;
end;
// Renumber the states appropriately
State1 := @FUREBuffer.States.States[0];
Equal := 0;
for I := 0 to FUREBuffer.States.StatesUsed - 1 do
begin
if State1.ID = Cardinal(I) then
begin
State1.ID := Equal;
Inc(Equal);
end
else
State1.ID := FUREBuffer.States.States[State1.ID].ID;
Inc(State1);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.ClearUREBuffer;
var
I: Integer;
begin
with FUREBuffer do
begin
// quite a few dynamic arrays to free
Stack.List := nil;
ExpressionList.Expressions := nil;
// the symbol table has been handed over to the DFA and will be freed on
// release of the DFA
SymbolTable.SymbolsUsed := 0;
for I := 0 to States.StatesUsed - 1 do
begin
States.States[I].Transitions := nil;
States.States[I].StateList.List := nil;
States.States[I].StateList.ListUsed := 0;
States.States[I].TransitionsUsed := 0;
end;
States.StatesUsed := 0;
States.States := nil;
EquivalentList.Equivalents := nil;
end;
FillChar(FUREBuffer, SizeOf(FUREBuffer), 0);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.CompileURE(RE: PWideChar; RELength: Cardinal; Casefold: Boolean);
var
I, J: Integer;
State: Cardinal;
Run: PUcState;
TP: Integer;
begin
// be paranoid
if (RE <> nil) and (RE^ <> WideNull) and (RELength > 0) then
begin
// Reset the various fields of the compilation buffer. Default the Flags
// to indicate the presence of the "^$" pattern. If any other pattern
// occurs, then this flag will be removed. This is done to catch this
// special pattern and handle it specially when matching.
ClearUREBuffer;
ClearDFA;
FUREBuffer.Flags := _URE_DFA_BLANKLINE;
if Casefold then
FUREBuffer.Flags := FUREBuffer.Flags or _URE_DFA_CASEFOLD;
// Construct the NFA. If this stage returns a 0, then an error occured or an
// empty expression was passed.
State := ConvertRegExpToNFA(RE, RELength);
if State <> _URE_NOOP then
begin
// Do the expression reduction to get the initial DFA.
Reduce(State);
// Merge all the equivalent DFA States.
MergeEquivalents;
// Construct the minimal DFA.
FDFA.Flags := FUREBuffer.Flags and (_URE_DFA_CASEFOLD or _URE_DFA_BLANKLINE);
// Free up the NFA state groups and transfer the symbols from the buffer
// to the DFA.
FDFA.SymbolTable := FUREBuffer.SymbolTable;
FUREBuffer.SymbolTable.Symbols := nil;
// Collect the total number of states and transitions needed for the DFA.
State := 0;
for I := 0 to FUREBuffer.States.StatesUsed - 1 do
begin
if FUREBuffer.States.States[I].ID = State then
begin
Inc(FDFA.StateList.StatesUsed);
Inc(FDFA.TransitionList.TransitionsUsed, FUREBuffer.States.States[I].TransitionsUsed);
Inc(State);
end;
end;
// Allocate enough space for the states and transitions.
SetLength(FDFA.StateList.States, FDFA.StateList.StatesUsed);
SetLength(FDFA.TransitionList.Transitions, FDFA.TransitionList.TransitionsUsed);
// Actually transfer the DFA States from the buffer.
State := 0;
TP := 0;
Run := @FUREBuffer.States.States[0];
for I := 0 to FUREBuffer.States.StatesUsed - 1 do
begin
if Run.ID = State then
begin
FDFA.StateList.States[I].StartTransition := TP;
FDFA.StateList.States[I].NumberTransitions := Run.TransitionsUsed;
FDFA.StateList.States[I].Accepting := Run.Accepting;
// Add the transitions for the state
for J := 0 to FDFA.StateList.States[I].NumberTransitions - 1 do
begin
FDFA.TransitionList.Transitions[TP].Symbol := Run.Transitions[J].LHS;
FDFA.TransitionList.Transitions[TP].NextState :=
FUREBuffer.States.States[Run.Transitions[J].RHS].ID;
Inc(TP);
end;
Inc(State);
end;
Inc(Run);
end;
end
else
begin
// there might be an error while parsing the pattern, show it if so
case FUREBuffer.Error of
_URE_UNEXPECTED_EOS:
raise Exception.CreateFmt(SUREBaseString + SUREUnexpectedEOS, [RE]);
_URE_CCLASS_OPEN:
raise Exception.CreateFmt(SUREBaseString + SURECharacterClassOpen, [RE]);
_URE_UNBALANCED_GROUP:
raise Exception.CreateFmt(SUREBaseString + SUREUnbalancedGroup, [RE]);
_URE_INVALID_PROPERTY:
raise Exception.CreateFmt(SUREBaseString + SUREInvalidCharProperty, [RE]);
_URE_INVALID_RANGE:
raise Exception.CreateFmt(SUREBaseString + SUREInvalidRepeatRange, [RE]);
_URE_RANGE_OPEN:
raise Exception.CreateFmt(SUREBaseString + SURERepeatRangeOpen, [RE]);
else
// expression was empty
raise Exception.Create(SUREExpressionEmpty);
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.ClearDFA;
var
I: Integer;
begin
with FDFA do
begin
for I := 0 to SymbolTable.SymbolsUsed - 1 do
begin
if (SymbolTable.Symbols[I].AType = _URE_CCLASS) or
(SymbolTable.Symbols[I].AType = _URE_NCCLASS) then
SymbolTable.Symbols[I].Symbol.CCL.Ranges := nil;
end;
for I := 0 to SymbolTable.SymbolsUsed - 1 do
begin
FDFA.SymbolTable.Symbols[I].States.List := nil;
FDFA.SymbolTable.Symbols[I].States.ListUsed := 0;
end;
SymbolTable.SymbolsUsed := 0;
SymbolTable.Symbols := nil;
StateList.States := nil;
TransitionList.Transitions := nil;
end;
FillChar(FDFA, SizeOf(FDFA), 0);
end;
//----------------------------------------------------------------------------------------------------------------------
function IsSeparator(C: UCS4Char): Boolean;
begin
Result := (C = $D) or (C = $A) or (C = $2028) or (C = $2029);
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.ExecuteURE(Flags: Cardinal; Text: PUCS2Char; TextLen: Cardinal; var MatchStart,
MatchEnd: Cardinal): Boolean;
var
I, J: Integer;
Matched,
Found: Boolean;
Start, Stop: Integer;
C: UCS4Char;
Run, Tail, lp: PUCS2Char;
LastState: PDFAState;
Symbol: PUcSymbolTableEntry;
Rp: PUcRange;
begin
Result := False;
if Text <> nil then
begin
// Handle the special case of an empty string matching the "^$" pattern.
if (Textlen = 0) and ((FDFA.Flags and _URE_DFA_BLANKLINE) <> 0) then
begin
MatchStart := 0;
MatchEnd := 0;
Result := True;
Exit;
end;
Run := Text;
Tail := Run + TextLen;
Start := -1;
Stop := -1;
LastState := @FDFA.StateList.States[0];
Found := False;
while not Found and (Run < Tail) do
begin
lp := Run;
C := UCS4Char(Run^);
Inc(Run);
// Check to see if this is a high surrogate that should be combined with a
// following low surrogate.
if (Run < Tail) and
(SurrogateHighStart <= C) and (C <= SurrogateHighEnd) and
(SurrogateLowStart <= UCS4Char(Run^)) and (UCS4Char(Run^) <= SurrogateLowEnd) then
begin
C := $10000 + (((C and $03FF) shl 10) or (UCS4Char(Run^) and $03FF));
Inc(Run);
end;
// Determine if the character is non-spacing and should be skipped.
if ((Flags and URE_IGNORE_NONSPACING) <> 0) and UnicodeIsNonSpacingMark(C) then
begin
Inc(Run);
Continue;
end;
if (FDFA.Flags and _URE_DFA_CASEFOLD) <> 0 then
// TODO: use the entire mapping, not only the first character
C := UnicodeToLower(C)[0];
// See if one of the transitions matches.
I := LastState.NumberTransitions - 1;
Matched := False;
while not Matched and (I >= 0) do
begin
Symbol := @FDFA.SymbolTable.Symbols[FDFA.TransitionList.Transitions[LastState.StartTransition + I].Symbol];
case Symbol.AType of
_URE_ANY_CHAR:
if ((Flags and URE_DONT_MATCHES_SEPARATORS) <> 0) or
not IsSeparator(C) then
Matched := True;
_URE_CHAR:
if C = Symbol.Symbol.Chr then
Matched := True;
_URE_BOL_ANCHOR:
if Lp = Text then
begin
Run := lp;
Matched := True;
end
else
begin
if IsSeparator(C) then
begin
if (C = $D) and (Run < Tail) and (Run^ = #$A) then
Inc(Run);
Lp := Run;
Matched := True;
end;
end;
_URE_EOL_ANCHOR:
if IsSeparator(C) then
begin
// Put the pointer back before the separator so the match end
// position will be correct. This will also cause the `Run'
// pointer to be advanced over the current separator once the
// match end point has been recorded.
Run := Lp;
Matched := True;
end;
_URE_CCLASS,
_URE_NCCLASS:
with Symbol^ do
begin
if Categories <> [] then
Matched := CategoryLookup(C, Categories);
if Symbol.CCL.RangesUsed > 0 then
begin
Rp := @Symbol.CCL.Ranges[0];
for J := 0 to Symbol.CCL.RangesUsed - 1 do
begin
if (Rp.MinCode <= C) and (C <= Rp.MaxCode) then
begin
Matched := True;
Break;
end;
Inc(Rp);
end;
end;
if AType = _URE_NCCLASS then
Matched := not Matched;
end;
end;
if Matched then
begin
if Start = -1 then
Start := Lp - Text
else
Stop := Run - Text;
LastState := @FDFA.StateList.States[FDFA.TransitionList.Transitions[LastState.StartTransition +
I].NextState];
// If the match was an EOL anchor, adjust the pointer past the separator
// that caused the match. The correct match position has been recorded
// already.
if Symbol.AType = _URE_EOL_ANCHOR then
begin
// skip the character that caused the match
Inc(Run);
// handle the infamous CRLF situation
if (Run < Tail) and (C = $D) and (Run^ = #$A) then
Inc(Run);
end;
end;
Dec(I);
end;
if not Matched then
begin
Found := LastState.Accepting;
if not Found then
begin
// If the last state was not accepting, then reset and start over.
LastState := @FDFA.StateList.States[0];
Start := -1;
Stop := -1;
end
else
begin
// set start and stop pointer if not yet done
if Start = -1 then
begin
Start := Lp - Text;
Stop := Run - Text;
end
else
begin
if Stop = -1 then
Stop := Lp - Text;
end;
end;
end
else
begin
if Run = Tail then
begin
if not LastState.Accepting then
begin
// This ugly hack is to make sure the end-of-line anchors match
// when the source text hits the end. This is only done if the last
// subexpression matches.
for I := 0 to LastState.NumberTransitions - 1 do
begin
if Found then
Break;
Symbol := @FDFA.SymbolTable.Symbols[FDFA.TransitionList.Transitions[LastState.StartTransition +
I].Symbol];
if Symbol.AType = _URE_EOL_ANCHOR then
begin
LastState := @FDFA.StateList.States[FDFA.TransitionList.Transitions[LastState.StartTransition +
I].NextState];
if LastState.Accepting then
begin
Stop := Run - Text;
Found := True;
end
else
Break;
end;
end;
end
else
begin
// Make sure any conditions that match all the way to the end of
// the string match.
Found := True;
Stop := Run - Text;
end;
end;
end;
end;
if Found then
begin
MatchStart := Start;
MatchEnd := Stop;
end;
Result := Found;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.FindAll(const Text: WideString): Boolean;
begin
Result := FindAll(PWideChar(Text), Length(Text));
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.FindAll(const Text: PWideChar; TextLen: Cardinal): Boolean;
// Looks for all occurences of the pattern passed to FindPrepare and creates an
// internal list of their positions.
var
Start, Stop: Cardinal;
Run: PWideChar;
RunLen: Cardinal;
begin
ClearResults;
Run := Text;
RunLen := TextLen;
// repeat to find all occurences of the pattern
while ExecuteURE(0, Run, RunLen, Start, Stop) do
begin
// store this result (consider text pointer movement)...
AddResult(Start + Run - Text, Stop + Run - Text);
// ... and advance text position and length
Inc(Run, Stop);
Dec(RunLen, Stop);
end;
Result := FResults.Count > 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.FindFirst(const Text: WideString; var Start, Stop: Cardinal): Boolean;
begin
Result := FindFirst(PWideChar(Text), Length(Text), Start, Stop);
end;
//----------------------------------------------------------------------------------------------------------------------
function TURESearch.FindFirst(const Text: PWideChar; TextLen: Cardinal; var Start, Stop: Cardinal): Boolean;
// Looks for the first occurence of the pattern passed to FindPrepare in Text and
// returns True if one could be found (in which case Start and Stop are set to
// the according indices) otherwise False. This function is in particular of
// interest if only one occurence needs to be found.
begin
ClearResults;
Result := ExecuteURE(0, PWideChar(Text), Length(Text), Start, Stop);
if Result then
AddResult(Start, Stop);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.FindPrepare(const Pattern: PWideChar; PatternLength: Cardinal; Options: TSearchFlags);
begin
CompileURE(Pattern, PatternLength, not (sfCaseSensitive in Options));
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TURESearch.FindPrepare(const Pattern: WideString; Options: TSearchFlags);
begin
CompileURE(PWideChar(Pattern), Length(Pattern), not (sfCaseSensitive in Options));
end;
//----------------- TWideStrings -------------------------------------------------------------------
constructor TWideStrings.Create;
begin
inherited;
FLanguage := GetUserDefaultLCID;
FNormalizationForm := nfNone;
FSaveUnicode := True;
end;
//----------------------------------------------------------------------------------------------------------------------
destructor TWideStrings.Destroy;
begin
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetLanguage(Value: LCID);
begin
FLanguage := Value;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.Add(const S: WideString): Integer;
begin
Result := GetCount;
Insert(Result, S);
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.AddObject(const S: WideString; AObject: TObject): Integer;
begin
Result := Add(S);
PutObject(Result, AObject);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.Append(const S: WideString);
begin
Add(S);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.AddStrings(Strings: TStrings);
var
I: Integer;
S: WideString;
CP: Integer;
begin
BeginUpdate;
try
CP := CodePageFromLocale(FLanguage);
for I := 0 to Strings.Count - 1 do
begin
S := StringToWideStringEx(Strings[I], CP);
AddObject(S, Strings.Objects[I]);
end;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.AddStrings(Strings: TWideStrings);
var
I: Integer;
SourceCP,
TargetCP: Integer;
S: WideString;
begin
BeginUpdate;
try
if Strings.FLanguage <> FLanguage then
begin
SourceCP := CodePageFromLocale(Strings.FLanguage);
TargetCP := CodePageFromLocale(FLanguage);
for I := 0 to Strings.Count - 1 do
begin
S := TranslateString(Strings[I], SourceCP, TargetCP);
AddObject(S, Strings.Objects[I]);
end;
end
else
begin
for I := 0 to Strings.Count - 1 do
AddObject(Strings[I], Strings.Objects[I]);
end;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.Assign(Source: TPersistent);
// usual assignment routine, but able to assign wide and small strings
begin
if Source is TWideStrings then
begin
BeginUpdate;
try
Clear;
AddStrings(TWideStrings(Source));
finally
EndUpdate;
end;
end
else
begin
if Source is TStrings then
begin
BeginUpdate;
try
Clear;
AddStrings(TStrings(Source));
finally
EndUpdate;
end;
end
else
inherited Assign(Source);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.AssignTo(Dest: TPersistent);
// need to do also assignment to old style TStrings, but this class doesn't know
// TWideStrings, so we need to do it from here
var
I: Integer;
S: string;
CP: Integer;
begin
if Dest is TStrings then
begin
with Dest as TStrings do
begin
BeginUpdate;
try
CP := CodePageFromLocale(FLanguage);
Clear;
for I := 0 to Self.Count - 1 do
begin
S := WideStringToStringEx(Self[I], CP);
AddObject(S, Self.Objects[I]);
end;
finally
EndUpdate;
end;
end;
end
else
begin
if Dest is TWideStrings then
begin
with Dest as TWideStrings do
begin
BeginUpdate;
try
Clear;
AddStrings(Self);
finally
EndUpdate;
end;
end;
end
else
inherited;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.BeginUpdate;
begin
if FUpdateCount = 0 then
SetUpdateState(True);
Inc(FUpdateCount);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.DefineProperties(Filer: TFiler);
// Defines a private property for the content of the list.
// There's a bug in the handling of text DFMs in Classes.pas which prevents
// WideStrings from loading under some circumstances. Zbysek Hlinka
// (zhlinka@login.cz) brought this to my attention and supplied also a solution.
// See ReadData and WriteData methods for implementation details.
//--------------- local function --------------------------------------------
function DoWrite: Boolean;
begin
if Filer.Ancestor <> nil then
begin
Result := True;
if Filer.Ancestor is TWideStrings then
Result := not Equals(TWideStrings(Filer.Ancestor))
end
else
Result := Count > 0;
end;
//--------------- end local function ----------------------------------------
begin
Filer.DefineProperty('WideStrings', ReadData, WriteData, DoWrite);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.DoConfirmConversion(var Allowed: Boolean);
begin
if Assigned(FOnConfirmConversion) then
FOnConfirmConversion(Self, Allowed);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
SetUpdateState(False);
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.Equals(Strings: TWideStrings): Boolean;
var
I, Count: Integer;
begin
Result := False;
Count := GetCount;
if Count <> Strings.GetCount then
Exit;
// TODO use internal comparation routine as soon as composition is implemented
for I := 0 to Count - 1 do
if Get(I) <> Strings.Get(I) then
Exit;
Result := True;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.Error(const Msg: string; Data: Integer);
//--------------- local function --------------------------------------------
function ReturnAddr: Pointer;
asm
MOV EAX, [EBP + 4]
end;
//--------------- end local function ----------------------------------------
begin
raise EStringListError.CreateFmt(Msg, [Data])at ReturnAddr;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.Exchange(Index1, Index2: Integer);
var
TempObject: TObject;
TempString: WideString;
begin
BeginUpdate;
try
TempString := Strings[Index1];
TempObject := Objects[Index1];
Strings[Index1] := Strings[Index2];
Objects[Index1] := Objects[Index2];
Strings[Index2] := TempString;
Objects[Index2] := TempObject;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetCapacity: Integer;
// Descendants may optionally override/replace this default implementation.
begin
Result := Count;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetCommaText: WideString;
var
S: WideString;
P: PWideChar;
I, Count: Integer;
begin
Count := GetCount;
if (Count = 1) and (Get(0) = '') then
Result := '""'
else
begin
Result := '';
for I := 0 to Count - 1 do
begin
S := Get(I);
P := PWideChar(S);
while not (P^ in [WideNull..WideSpace, WideChar('"'), WideChar(',')]) do
Inc(P);
if P^ <> WideNull then
S := WideQuotedStr(S, '"');
Result := Result + S + ',';
end;
System.Delete(Result, Length(Result), 1);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetName(Index: Integer): WideString;
var
P: Integer;
begin
Result := Get(Index);
P := Pos('=', Result);
if P > 0 then
SetLength(Result, P - 1)
else
Result := '';
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetObject(Index: Integer): TObject;
begin
Result := nil;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetSeparatedText(Separators: WideString): WideString;
// Same as GetText but with customizable separator characters.
var
I, L,
Size,
Count,
SepSize: Integer;
P: PWideChar;
S: WideString;
begin
Count := GetCount;
SepSize := Length(Separators);
Size := 0;
for I := 0 to Count - 1 do
Inc(Size, Length(Get(I)) + SepSize);
// set one separator less, the last line does not need a trailing separator
SetLength(Result, Size - SepSize);
if Size > 0 then
begin
P := Pointer(Result);
I := 0;
while True do
begin
S := Get(I);
L := Length(S);
if L <> 0 then
begin
// add current string
System.Move(Pointer(S)^, P^, 2 * L);
Inc(P, L);
end;
Inc(I);
if I = Count then
Break;
// add separators
System.Move(Pointer(Separators)^, P^, 2 * SepSize);
Inc(P, SepSize);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetText: WideString;
begin
//Result := GetSeparatedText(WideLineSeparator);
Result := GetSeparatedText(WideCRLF);
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.GetValue(const Name: WideString): WideString;
var
I: Integer;
begin
I := IndexOfName(Name);
if I >= 0 then
Result := Copy(Get(I), Length(Name) + 2, MaxInt)
else
Result := '';
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.IndexOf(const S: WideString): Integer;
var
NormString: WideString;
begin
NormString := WideNormalize(S, FNormalizationForm);
for Result := 0 to GetCount - 1 do
if WideCompareText(Get(Result), NormString, FLanguage) = 0 then
Exit;
Result := -1;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.IndexOfName(const Name: WideString): Integer;
var
P: Integer;
S: WideString;
NormName: WideString;
begin
NormName := WideNormalize(Name, FNormalizationForm);
for Result := 0 to GetCount - 1 do
begin
S := Get(Result);
P := Pos('=', S);
if (P > 0) and (WideCompareText(Copy(S, 1, P - 1), NormName, FLanguage) = 0) then
Exit;
end;
Result := -1;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStrings.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to GetCount - 1 do
if GetObject(Result) = AObject then
Exit;
Result := -1;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.InsertObject(Index: Integer; const S: WideString; AObject: TObject);
begin
Insert(Index, S);
PutObject(Index, AObject);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.LoadFromStream(Stream: TStream);
// usual loader routine, but enhanced to handle byte order marks in stream
var
Size,
BytesRead: Integer;
Order: WideChar;
SW: WideString;
SA: string;
begin
BeginUpdate;
try
Size := Stream.Size - Stream.Position;
BytesRead := Stream.Read(Order, 2);
if (Order = BOM_LSB_FIRST) or (Order = BOM_MSB_FIRST) then
begin
FSaveUnicode := True;
SetLength(SW, (Size - 2) div 2);
Stream.Read(PWideChar(SW)^, Size - 2);
if Order = BOM_MSB_FIRST then
StrSwapByteOrder(PWideChar(SW));
SetText(SW);
end
else
begin
// without byte order mark it is assumed that we are loading ANSI text
FSaveUnicode := False;
Stream.Seek(-BytesRead, soFromCurrent);
SetLength(SA, Size);
Stream.Read(PChar(SA)^, Size);
SetText(SA);
end;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.Move(CurIndex, NewIndex: Integer);
var
TempObject: TObject;
TempString: WideString;
begin
if CurIndex <> NewIndex then
begin
BeginUpdate;
try
TempString := Get(CurIndex);
TempObject := GetObject(CurIndex);
Delete(CurIndex);
InsertObject(NewIndex, TempString, TempObject);
finally
EndUpdate;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.ReadData(Reader: TReader);
begin
case Reader.NextValue of
vaLString, vaString:
SetText(Reader.ReadString);
else
SetText(Reader.ReadWideString);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SaveToStream(Stream: TStream; WithBOM: Boolean = True);
// Saves the currently loaded text into the given stream. WithBOM determines whether to write a
// byte order mark or not. Note: when saved as ANSI text there will never be a BOM.
var
SW, BOM: WideString;
SA: string;
Allowed: Boolean;
Run: PWideChar;
begin
// The application can decide in which format to save the content.
// If FSaveUnicode is False then all strings are saved in standard ANSI format
// which is also loadable by TStrings but you should be aware that all Unicode
// strings are then converted to ANSI based on the current system locale.
// An extra event is supplied to ask the user about the potential loss of
// information when converting Unicode to ANSI strings.
SW := GetText;
Allowed := True;
FSaved := False; // be pessimistic
// A check for potential information loss makes only sense if the application has
// set an event to be used as call back to ask about the conversion.
if not FSaveUnicode and Assigned(FOnConfirmConversion) then
begin
// application requests to save only ANSI characters, so check the text and
// call back in case information could be lost
Run := PWideChar(SW);
// only ask if there's at least one Unicode character in the text
while Run^ in [WideChar(#1)..WideChar(#255)] do
Inc(Run);
// Note: The application can still set FSaveUnicode to True in the callback.
if Run^ <> WideNull then
DoConfirmConversion(Allowed);
end;
if Allowed then
begin
// only save if allowed
if FSaveUnicode then
begin
if WithBOM then
begin
BOM := BOM_LSB_FIRST;
Stream.WriteBuffer(PWideChar(BOM)^, 2);
end;
// SW has already been filled
Stream.WriteBuffer(PWideChar(SW)^, 2 * Length(SW));
end
else
begin
SA := WideStringToStringEx(SW, CodePageFromLocale(FLanguage));
if Allowed then
Stream.WriteBuffer(PChar(SA)^, Length(SA));
end;
FSaved := True;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetCapacity(NewCapacity: Integer);
begin
// do nothing - descendants may optionally implement this method
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetCommaText(const Value: WideString);
var
P, P1: PWideChar;
S: WideString;
begin
BeginUpdate;
try
Clear;
P := PWideChar(Value);
while P^ in [WideChar(#1)..WideSpace] do
Inc(P);
while P^ <> WideNull do
begin
if P^ = '"' then
S := WideExtractQuotedStr(P, '"')
else
begin
P1 := P;
while (P^ > WideSpace) and (P^ <> ',') do
Inc(P);
SetString(S, P1, P - P1);
end;
Add(S);
while P^ in [WideChar(#1)..WideSpace] do
Inc(P);
if P^ = ', ' then
begin
repeat
Inc(P);
until not (P^ in [WideChar(#1)..WideSpace]);
end;
end;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetText(const Value: WideString);
var
Head,
Tail: PWideChar;
S: WideString;
begin
BeginUpdate;
try
Clear;
Head := PWideChar(Value);
while Head^ <> WideNull do
begin
Tail := Head;
while not (Tail^ in [WideNull, WideLineFeed, WideCarriageReturn, WideVerticalTab, WideFormFeed]) and
(Tail^ <> WideLineSeparator) and (Tail^ <> WideParagraphSeparator) do
Inc(Tail);
SetString(S, Head, Tail - Head);
Add(S);
Head := Tail;
if Head^ <> WideNull then
begin
Inc(Head);
if (Tail^ = WideCarriageReturn) and (Head^ = WideLineFeed) then
Inc(Head);
end;
end;
finally
EndUpdate;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetUpdateState(Updating: Boolean);
begin
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetNormalizationForm(const Value: TNormalizationForm);
var
I: Integer;
begin
if FNormalizationForm <> Value then
begin
FNormalizationForm := Value;
if FNormalizationForm <> nfNone then
begin
// renormalize all strings according to the new form
for I := 0 to GetCount - 1 do
Put(I, WideNormalize(Get(I), FNormalizationForm));
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.SetValue(const Name, Value: WideString);
var
I: Integer;
begin
I := IndexOfName(Name);
if Value <> '' then
begin
if I < 0 then
I := Add('');
Put(I, Name + '=' + Value);
end
else
begin
if I >= 0 then
Delete(I);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStrings.WriteData(Writer: TWriter);
begin
Writer.WriteWideString(GetText);
end;
//----------------- TWideStringList ----------------------------------------------------------------
destructor TWideStringList.Destroy;
begin
Clear;
inherited;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.Add(const S: WideString): Integer;
begin
if not Sorted then
Result := FCount
else
begin
if Find(S, Result) then
begin
case Duplicates of
dupIgnore:
Exit;
dupError:
Error(SDuplicateString, 0);
end;
end;
end;
InsertItem(Result, S);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Changed;
begin
if (FUpdateCount = 0) and Assigned(FOnChange) then
FOnChange(Self);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Changing;
begin
if (FUpdateCount = 0) and Assigned(FOnChanging) then
FOnChanging(Self);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Clear;
begin
if FCount <> 0 then
begin
Changing;
// this will automatically finalize the array
FList := nil;
FCount := 0;
SetCapacity(0);
Changed;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Delete(Index: Integer);
begin
if (Index < 0) or (Index >= FCount) then
Error(SListIndexError, Index);
Changing;
FList[Index].FString := '';
Dec(FCount);
if Index < FCount then
begin
System.Move(FList[Index + 1], FList[Index], (FCount - Index) * SizeOf(TWideStringItem));
Pointer(FList[FCount].FString) := nil; // avoid freeing the string, the address is now used in another element
end;
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Exchange(Index1, Index2: Integer);
begin
if (Index1 < 0) or (Index1 >= FCount) then
Error(SListIndexError, Index1);
if (Index2 < 0) or (Index2 >= FCount) then
Error(SListIndexError, Index2);
Changing;
ExchangeItems(Index1, Index2);
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.ExchangeItems(Index1, Index2: Integer);
var
Temp: TWideStringItem;
begin
Temp := FList[Index1];
FList[Index1] := FList[Index2];
FList[Index2] := Temp;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.Find(const S: WideString; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
NormString: WideString;
begin
Result := False;
NormString := WideNormalize(S, FNormalizationForm);
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := WideCompareText(FList[I].FString, NormString, FLanguage);
if C < 0 then
L := I + 1
else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> dupAccept then
L := I;
end;
end;
end;
Index := L;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.Get(Index: Integer): WideString;
begin
if (Index < 0) or (Index >= FCount) then
Error(SListIndexError, Index);
Result := FList[Index].FString;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.GetCapacity: Integer;
begin
Result := Length(FList);
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.GetCount: Integer;
begin
Result := FCount;
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.GetObject(Index: Integer): TObject;
begin
if (Index < 0) or (Index >= FCount) then
Error(SListIndexError, Index);
Result := FList[Index].FObject;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Grow;
var
Delta,
Len: Integer;
begin
Len := Length(FList);
if Len > 64 then
Delta := Len div 4
else
begin
if Len > 8 then
Delta := 16
else
Delta := 4;
end;
SetCapacity(Len + Delta);
end;
//----------------------------------------------------------------------------------------------------------------------
function TWideStringList.IndexOf(const S: WideString): Integer;
begin
if not Sorted then
Result := inherited IndexOf(S)
else
if not Find(S, Result) then
Result := -1;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Insert(Index: Integer; const S: WideString);
begin
if Sorted then
Error(SSortedListError, 0);
if (Index < 0) or (Index > FCount) then
Error(SListIndexError, Index);
InsertItem(Index, S);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.InsertItem(Index: Integer; const S: WideString);
begin
Changing;
if FCount = Length(FList) then
Grow;
if Index < FCount then
System.Move(FList[Index], FList[Index + 1], (FCount - Index) * SizeOf(TWideStringItem));
with FList[Index] do
begin
Pointer(FString) := nil; // avoid freeing the string, the address is now used in another element
FObject := nil;
if (FNormalizationForm <> nfNone) and (Length(S) > 0) then
FString := WideNormalize(S, FNormalizationForm)
else
FString := S;
end;
Inc(FCount);
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Put(Index: Integer; const S: WideString);
begin
if Sorted then
Error(SSortedListError, 0);
if (Index < 0) or (Index >= FCount) then
Error(SListIndexError, Index);
Changing;
if (FNormalizationForm <> nfNone) and (Length(S) > 0) then
FList[Index].FString := WideNormalize(S, FNormalizationForm)
else
FList[Index].FString := S;
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.PutObject(Index: Integer; AObject: TObject);
begin
if (Index < 0) or (Index >= FCount) then
Error(SListIndexError, Index);
Changing;
FList[Index].FObject := AObject;
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.QuickSort(L, R: Integer);
var
I, J: Integer;
P: WideString;
begin
repeat
I := L;
J := R;
P := FList[(L + R) shr 1].FString;
repeat
while WideCompareText(FList[I].FString, P, FLanguage) < 0 do
Inc(I);
while WideCompareText(FList[J].FString, P, FLanguage) > 0 do
Dec(J);
if I <= J then
begin
ExchangeItems(I, J);
Inc(I);
Dec(J);
end;
until I > J;
if L < J then
QuickSort(L, J);
L := I;
until I >= R;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.SetCapacity(NewCapacity: Integer);
begin
SetLength(FList, NewCapacity);
if NewCapacity < FCount then
FCount := NewCapacity;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.SetSorted(Value: Boolean);
begin
if FSorted <> Value then
begin
if Value then
Sort;
FSorted := Value;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.SetUpdateState(Updating: Boolean);
begin
if Updating then
Changing
else
Changed;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.Sort;
begin
if not Sorted and (FCount > 1) then
begin
Changing;
QuickSort(0, FCount - 1);
Changed;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure TWideStringList.SetLanguage(Value: LCID);
begin
inherited;
if Sorted then
Sort;
end;
//----------------- functions for null terminated strings ------------------------------------------
function StrLenW(Str: PWideChar): Cardinal;
// returns number of characters in a string excluding the null terminator
asm
MOV EDX, EDI
MOV EDI, EAX
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
MOV EAX, 0FFFFFFFEH
SUB EAX, ECX
MOV EDI, EDX
end;
//----------------------------------------------------------------------------------------------------------------------
function StrEndW(Str: PWideChar): PWideChar;
// returns a pointer to the end of a null terminated string
asm
MOV EDX, EDI
MOV EDI, EAX
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
LEA EAX, [EDI - 2]
MOV EDI, EDX
end;
//----------------------------------------------------------------------------------------------------------------------
function StrMoveW(Dest, Source: PWideChar; Count: Cardinal): PWideChar;
// Copies the specified number of characters to the destination string and returns Dest
// also as result. Dest must have enough room to store at least Count characters.
asm
PUSH ESI
PUSH EDI
MOV ESI, EDX
MOV EDI, EAX
MOV EDX, ECX
CMP EDI, ESI
JG @@1
JE @@2
SHR ECX, 1
REP MOVSD
MOV ECX, EDX
AND ECX, 1
REP MOVSW
JMP @@2
@@1:
LEA ESI, [ESI + 2 * ECX - 2]
LEA EDI, [EDI + 2 * ECX - 2]
STD
AND ECX, 1
REP MOVSW
SUB EDI, 2
SUB ESI, 2
MOV ECX, EDX
SHR ECX, 1
REP MOVSD
CLD
@@2:
POP EDI
POP ESI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrCopyW(Dest, Source: PWideChar): PWideChar;
// copies Source to Dest and returns Dest
asm
PUSH EDI
PUSH ESI
MOV ESI, EAX
MOV EDI, EDX
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
NOT ECX
MOV EDI, ESI
MOV ESI, EDX
MOV EDX, ECX
MOV EAX, EDI
SHR ECX, 1
REP MOVSD
MOV ECX, EDX
AND ECX, 1
REP MOVSW
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrECopyW(Dest, Source: PWideChar): PWideChar;
// copies Source to Dest and returns a pointer to the null character ending the string
asm
PUSH EDI
PUSH ESI
MOV ESI, EAX
MOV EDI, EDX
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
NOT ECX
MOV EDI, ESI
MOV ESI, EDX
MOV EDX, ECX
SHR ECX, 1
REP MOVSD
MOV ECX, EDX
AND ECX, 1
REP MOVSW
LEA EAX, [EDI - 2]
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrLCopyW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
// copies a specified maximum number of characters from Source to Dest
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV ESI, EAX
MOV EDI, EDX
MOV EBX, ECX
XOR AX, AX
TEST ECX, ECX
JZ @@1
REPNE SCASW
JNE @@1
INC ECX
@@1:
SUB EBX, ECX
MOV EDI, ESI
MOV ESI, EDX
MOV EDX, EDI
MOV ECX, EBX
SHR ECX, 1
REP MOVSD
MOV ECX, EBX
AND ECX, 1
REP MOVSW
STOSW
MOV EAX, EDX
POP EBX
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrPCopyW(Dest: PWideChar; const Source: string): PWideChar;
// copies a Pascal-style string to a null-terminated wide string
begin
Result := StrPLCopyW(Dest, Source, Length(Source));
Result[Length(Source)] := WideNull;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrPLCopyW(Dest: PWideChar; const Source: string; MaxLen: Cardinal): PWideChar;
// copies characters from a Pascal-style string into a null-terminated wide string
asm
PUSH EDI
PUSH ESI
MOV EDI, EAX
MOV ESI, EDX
MOV EDX, EAX
XOR AX, AX
@@1:
LODSB
STOSW
DEC ECX
JNZ @@1
MOV EAX, EDX
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrCatW(Dest, Source: PWideChar): PWideChar;
// appends a copy of Source to the end of Dest and returns the concatenated string
begin
StrCopyW(StrEndW(Dest), Source);
Result := Dest;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrLCatW(Dest, Source: PWideChar; MaxLen: Cardinal): PWideChar;
// appends a specified maximum number of WideCharacters to string
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV EDI, Dest
MOV ESI, Source
MOV EBX, MaxLen
SHL EBX, 1
CALL StrEndW
MOV ECX, EDI
ADD ECX, EBX
SUB ECX, EAX
JBE @@1
MOV EDX, ESI
SHR ECX, 1
CALL StrLCopyW
@@1:
MOV EAX, EDI
POP EBX
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
const
// data used to bring UTF-16 coded strings into correct UTF-32 order for correct comparation
UTF16Fixup: array[0..31] of Word = (
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,
$2000, $F800, $F800, $F800, $F800
);
function StrCompW(Str1, Str2: PWideChar): Integer;
// Binary comparation of Str1 and Str2 with surrogate fix-up.
// Returns < 0 if Str1 is smaller in binary order than Str2, = 0 if both strings are
// equal and > 0 if Str1 is larger than Str2.
//
// This code is based on an idea of Markus W. Scherer (IBM).
// Note: The surrogate fix-up is necessary because some single value code points have
// larger values than surrogates which are in UTF-32 actually larger.
var
C1, C2: Word;
Run1,
Run2: PWideChar;
begin
Run1 := Str1;
Run2 := Str2;
repeat
C1 := Word(Run1^);
C1 := Word(C1 + UTF16Fixup[C1 shr 11]);
C2 := Word(Run2^);
C2 := Word(C2 + UTF16Fixup[C2 shr 11]);
// now C1 and C2 are in UTF-32-compatible order
Result := Integer(C1) - Integer(C2);
if (Result <> 0) or (C1 = 0) or (C2 = 0) then
Break;
Inc(Run1);
Inc(Run2);
until False;
// If the strings have different lengths but the comparation returned equity so far
// then adjust the result so that the longer string is marked as the larger one.
if Result = 0 then
Result := (Run1 - Str1) - (Run2 - Str2);
end;
//----------------------------------------------------------------------------------------------------------------------
function StrICompW(Str1, Str2: PWideChar): Integer;
// Compares Str1 to Str2 without case sensitivity.
// See also comments in StrCompW, but keep in mind that case folding might result in
// one-to-many mappings which must be considered here.
var
C1, C2: Word;
Run1,
Run2: PWideChar;
Folded1,
Folded2: WideString;
begin
// Because of size changes of the string when doing case folding
// it is unavoidable to convert both strings completely in advance.
Folded1 := '';
while Str1^ <> #0 do
begin
Folded1 := Folded1 + WideCaseFolding(Str1^);
Inc(Str1);
end;
Folded2 := '';
while Str2^ <> #0 do
begin
Folded2 := Folded2 + WideCaseFolding(Str2^);
Inc(Str2);
end;
Run1 := PWideChar(Folded1);
Run2 := PWideChar(Folded2);
repeat
C1 := Word(Run1^);
C1 := Word(C1 + UTF16Fixup[C1 shr 11]);
C2 := Word(Run2^);
C2 := Word(C2 + UTF16Fixup[C2 shr 11]);
// now C1 and C2 are in UTF-32-compatible order
Result := Integer(C1) - Integer(C2);
if (Result <> 0) or (C1 = 0) or (C2 = 0) then
Break;
Inc(Run1);
Inc(Run2);
until False;
// If the strings have different lengths but the comparation returned equity so far
// then adjust the result so that the longer string is marked as the larger one.
if Result = 0 then
Result := (Run1 - PWideChar(Folded1)) - (Run2 - PWideChar(Folded2));
end;
//----------------------------------------------------------------------------------------------------------------------
function StrLICompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
// compares strings up to MaxLen code points
// see also StrICompW
var
C1, C2: Word;
Run1,
Run2: PWideChar;
Folded1,
Folded2: WideString;
begin
if MaxLen > 0 then
begin
// Because of size changes of the string when doing case folding
// it is unavoidable to convert both strings completely in advance.
Folded1 := '';
while Str1^ <> #0 do
begin
Folded1 := Folded1 + WideCaseFolding(Str1^);
Inc(Str1);
end;
Folded2 := '';
while Str2^ <> #0 do
begin
Folded2 := Folded2 + WideCaseFolding(Str2^);
Inc(Str2);
end;
Run1 := PWideChar(Folded1);
Run2 := PWideChar(Folded2);
repeat
C1 := Word(Run1^);
C1 := Word(C1 + UTF16Fixup[C1 shr 11]);
C2 := Word(Run2^);
C2 := Word(C2 + UTF16Fixup[C2 shr 11]);
// now C1 and C2 are in UTF-32-compatible order
// TODO: surrogates take up 2 words and are counted twice here, count them only once
Result := Integer(C1) - Integer(C2);
Dec(MaxLen);
if (Result <> 0) or (C1 = 0) or (C2 = 0) or (MaxLen = 0) then
Break;
Inc(Run1);
Inc(Run2);
until False;
end
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrLCompW(Str1, Str2: PWideChar; MaxLen: Cardinal): Integer;
// compares strings up to MaxLen code points
// see also StrCompW
var
C1, C2: Word;
begin
if MaxLen > 0 then
begin
repeat
C1 := Word(Str1^);
C1 := Word(C1 + UTF16Fixup[C1 shr 11]);
C2 := Word(Str2^);
C2 := Word(C2 + UTF16Fixup[C2 shr 11]);
// now C1 and C2 are in UTF-32-compatible order
// TODO: surrogates take up 2 words and are counted twice here, count them only once
Result := Integer(C1) - Integer(C2);
Dec(MaxLen);
if (Result <> 0) or (C1 = 0) or (C2 = 0) or (MaxLen = 0) then
Break;
Inc(Str1);
Inc(Str2);
until False;
end
else
Result := 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrNScanW(S1, S2: PWideChar): Integer;
// Determines where (in S1) the first time one of the characters of S2 appear.
// The result is the length of a string part of S1 where none of the characters of
// S2 do appear (not counting the trailing #0 and starting with position 0 in S1).
var
Run: PWideChar;
begin
Result := -1;
if (S1 <> nil) and (S2 <> nil) then
begin
Run := S1;
while (Run^ <> #0) do
begin
if StrScanW(S2, Run^) <> nil then
Break;
Inc(Run);
end;
Result := Run - S1;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrRNScanW(S1, S2: PWideChar): Integer;
// This function does the same as StrRNScanW but uses S1 in reverse order. This
// means S1 points to the last character of a string, is traversed reversely
// and terminates with a starting #0. This is useful for parsing strings stored
// in reversed macro buffers etc.
var
Run: PWideChar;
begin
Result := -1;
if (S1 <> nil) and (S2 <> nil) then
begin
Run := S1;
while (Run^ <> #0) do
begin
if StrScanW(S2, Run^) <> nil then
Break;
Dec(Run);
end;
Result := S1 - Run;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrScanW(Str: PWideChar; Chr: WideChar): PWideChar;
// returns a pointer to first occurrence of a specified character in a string
asm
PUSH EDI
PUSH EAX
MOV EDI, Str
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
NOT ECX
POP EDI
MOV AX, Chr
REPNE SCASW
MOV EAX, 0
JNE @@1
MOV EAX, EDI
SUB EAX, 2
@@1:
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrScanW(Str: PWideChar; Chr: WideChar; StrLen: Cardinal): PWideChar;
// Returns a pointer to first occurrence of a specified character in a string
// or nil if not found.
// Note: this is just a binary search for the specified character and there's no
// check for a terminating null. Instead at most StrLen characters are
// searched. This makes this function extremly fast.
//
// on enter EAX contains Str, EDX contains Chr and ECX StrLen
// on exit EAX contains result pointer or nil
asm
TEST EAX, EAX
JZ @@Exit // get out if the string is nil or StrLen is 0
JCXZ @@Exit
@@Loop:
CMP [EAX], DX // this unrolled loop is actually faster on modern processors
JE @@Exit // than REP SCASW
ADD EAX, 2
DEC ECX
JNZ @@Loop
XOR EAX, EAX
@@Exit:
end;
//----------------------------------------------------------------------------------------------------------------------
function StrRScanW(Str: PWideChar; Chr: WideChar): PWideChar;
// returns a pointer to the last occurance of Chr in Str
asm
PUSH EDI
MOV EDI, Str
MOV ECX, 0FFFFFFFFH
XOR AX, AX
REPNE SCASW
NOT ECX
STD
SUB EDI, 2
MOV AX, Chr
REPNE SCASW
MOV EAX, 0
JNE @@1
MOV EAX, EDI
ADD EAX, 2
@@1:
CLD
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrPosW(Str, SubStr: PWideChar): PWideChar;
// returns a pointer to the first occurance of SubStr in Str
asm
PUSH EDI
PUSH ESI
PUSH EBX
OR EAX, EAX
JZ @@2
OR EDX, EDX
JZ @@2
MOV EBX, EAX
MOV EDI, EDX
XOR AX, AX
MOV ECX, 0FFFFFFFFH
REPNE SCASW
NOT ECX
DEC ECX
JZ @@2
MOV ESI, ECX
MOV EDI, EBX
MOV ECX, 0FFFFFFFFH
REPNE SCASW
NOT ECX
SUB ECX, ESI
JBE @@2
MOV EDI, EBX
LEA EBX, [ESI - 1]
@@1:
MOV ESI, EDX
LODSW
REPNE SCASW
JNE @@2
MOV EAX, ECX
PUSH EDI
MOV ECX, EBX
REPE CMPSW
POP EDI
MOV ECX, EAX
JNE @@1
LEA EAX, [EDI - 2]
JMP @@3
@@2:
XOR EAX, EAX
@@3:
POP EBX
POP ESI
POP EDI
end;
//----------------------------------------------------------------------------------------------------------------------
function StrAllocW(Size: Cardinal): PWideChar;
// Allocates a buffer for a null-terminated wide string and returns a pointer
// to the first character of the string.
begin
Size := SizeOf(WideChar) * Size + SizeOf(Cardinal);
GetMem(Result, Size);
FillChar(Result^, Size, 0);
Cardinal(Pointer(Result)^) := Size;
Inc(Result, SizeOf(Cardinal) div SizeOf(WideChar));
end;
//----------------------------------------------------------------------------------------------------------------------
function StrBufSizeW(Str: PWideChar): Cardinal;
// Returns max number of wide characters that can be stored in a buffer
// allocated by StrAllocW.
begin
Dec(Str, SizeOf(Cardinal) div SizeOf(WideChar));
Result := (Cardinal(Pointer(Str)^) - SizeOf(Cardinal)) div 2;
end;
//----------------------------------------------------------------------------------------------------------------------
function StrNewW(Str: PWideChar): PWideChar;
// Duplicates the given string (if not nil) and returns the address of the new string.
var
Size: Cardinal;
begin
if Str = nil then
Result := nil
else
begin
Size := StrLenW(Str) + 1;
Result := StrMoveW(StrAllocW(Size), Str, Size);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure StrDisposeW(Str: PWideChar);
// releases a string allocated with StrNew
begin
if Str <> nil then
begin
Dec(Str, SizeOf(Cardinal) div SizeOf(WideChar));
FreeMem(Str, Cardinal(Pointer(Str)^));
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure StrSwapByteOrder(Str: PWideChar);
// exchanges in each character of the given string the low order and high order
// byte to go from LSB to MSB and vice versa.
// EAX contains address of string
asm
PUSH ESI
PUSH EDI
MOV ESI, EAX
MOV EDI, ESI
XOR EAX, EAX // clear high order byte to be able to use 32bit operand below
@@1:
LODSW
OR EAX, EAX
JZ @@2
XCHG AL, AH
STOSW
JMP @@1
@@2:
POP EDI
POP ESI
end;
//----------------------------------------------------------------------------------------------------------------------
function WideAdjustLineBreaks(const S: WideString): WideString;
var
Source,
SourceEnd,
Dest: PWideChar;
Extra: Integer;
begin
Source := Pointer(S);
SourceEnd := Source + Length(S);
Extra := 0;
while Source < SourceEnd do
begin
case Source^ of
WideLF:
Inc(Extra);
WideCR:
if Source[1] = WideLineFeed then
Inc(Source)
else
Inc(Extra);
end;
Inc(Source);
end;
Source := Pointer(S);
SetString(Result, nil, SourceEnd - Source + Extra);
Dest := Pointer(Result);
while Source < SourceEnd do
begin
case Source^ of
WideLineFeed:
begin
Dest^ := WideLineSeparator;
Inc(Dest);
Inc(Source);
end;
WideCarriageReturn:
begin
Dest^ := WideLineSeparator;
Inc(Dest);
Inc(Source);
if Source^ = WideLineFeed then
Inc(Source);
end;
else
Dest^ := Source^;
Inc(Dest);
Inc(Source);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideQuotedStr(const S: WideString; Quote: WideChar): WideString;
// works like QuotedStr from SysUtils.pas but can insert any quotation character
var
P, Src,
Dest: PWideChar;
AddCount: Integer;
begin
AddCount := 0;
P := StrScanW(PWideChar(S), Quote);
while (P <> nil) do
begin
Inc(P);
Inc(AddCount);
P := StrScanW(P, Quote);
end;
if AddCount = 0 then
Result := Quote + S + Quote
else
begin
SetLength(Result, Length(S) + AddCount + 2);
Dest := PWideChar(Result);
Dest^ := Quote;
Inc(Dest);
Src := PWideChar(S);
P := StrScanW(Src, Quote);
repeat
Inc(P);
Move(Src^, Dest^, 2 * (P - Src));
Inc(Dest, P - Src);
Dest^ := Quote;
Inc(Dest);
Src := P;
P := StrScanW(Src, Quote);
until P = nil;
P := StrEndW(Src);
Move(Src^, Dest^, 2 * (P - Src));
Inc(Dest, P - Src);
Dest^ := Quote;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideExtractQuotedStr(var Src: PWideChar; Quote: WideChar): WideString;
// extracts a string enclosed in quote characters given by Quote
var
P, Dest: PWideChar;
DropCount: Integer;
begin
Result := '';
if (Src = nil) or (Src^ <> Quote) then
Exit;
Inc(Src);
DropCount := 1;
P := Src;
Src := StrScanW(Src, Quote);
while Src <> nil do // count adjacent pairs of quote chars
begin
Inc(Src);
if Src^ <> Quote then
Break;
Inc(Src);
Inc(DropCount);
Src := StrScanW(Src, Quote);
end;
if Src = nil then
Src := StrEndW(P);
if (Src - P) <= 1 then
Exit;
if DropCount = 1 then
SetString(Result, P, Src - P - 1)
else
begin
SetLength(Result, Src - P - DropCount);
Dest := PWideChar(Result);
Src := StrScanW(P, Quote);
while Src <> nil do
begin
Inc(Src);
if Src^ <> Quote then
Break;
Move(P^, Dest^, 2 * (Src - P));
Inc(Dest, Src - P);
Inc(Src);
P := Src;
Src := StrScanW(Src, Quote);
end;
if Src = nil then
Src := StrEndW(P);
Move(P^, Dest^, 2 * (Src - P - 1));
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideStringOfChar(C: WideChar; Count: Cardinal): WideString;
// returns a string of Count characters filled with C
var
I: Integer;
begin
SetLength(Result, Count);
for I := 1 to Count do
Result[I] := C;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideTrim(const S: WideString): WideString;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (UnicodeIsWhiteSpace(UCS4Char(S[I])) or UnicodeIsControl(UCS4Char(S[I]))) do
Inc(I);
if I > L then
Result := ''
else
begin
while UnicodeIsWhiteSpace(UCS4Char(S[L])) or UnicodeIsControl(UCS4Char(S[L])) do
Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideTrimLeft(const S: WideString): WideString;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (UnicodeIsWhiteSpace(UCS4Char(S[I])) or UnicodeIsControl(UCS4Char(S[I]))) do
Inc(I);
Result := Copy(S, I, Maxint);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideTrimRight(const S: WideString): WideString;
var
I: Integer;
begin
I := Length(S);
while (I > 0) and (UnicodeIsWhiteSpace(UCS4Char(S[I])) or UnicodeIsControl(UCS4Char(S[I]))) do
Dec(I);
Result := Copy(S, 1, I);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideCharPos(const S: WideString; const Ch: WideChar; const Index: Integer): Integer;
// returns the index of character Ch in S, starts searching at index Index
// Note: This is a quick memory search. No attempt is made to interpret either
// the given charcter nor the string (ligatures, modifiers, surrogates etc.)
// Code from Azret Botash.
asm
TEST EAX,EAX // make sure we are not null
JZ @@StrIsNil
DEC ECX // make index zero based
JL @@IdxIsSmall
PUSH EBX
PUSH EDI
MOV EDI, EAX // EDI := S
XOR EAX, EAX
MOV AX, DX // AX := Ch
MOV EDX, [EDI - 4] // EDX := Length(S) * 2
SHR EDX, 1 // EDX := EDX div 2
MOV EBX, EDX // save the length to calc. result
SUB EDX, ECX // EDX = EDX - Index = # of chars to scan
JLE @@IdxIsBig
SHL ECX, 1 // two bytes per char
ADD EDI, ECX // point to index'th char
MOV ECX, EDX // loop counter
REPNE SCASW
JNE @@NoMatch
MOV EAX, EBX // result := saved length -
SUB EAX, ECX // loop counter value
POP EDI
POP EBX
RET
@@IdxIsBig:
@@NoMatch:
XOR EAX,EAX
POP EDI
POP EBX
RET
@@IdxIsSmall:
XOR EAX, EAX
@@StrIsNil:
end;
//----------------------------------------------------------------------------------------------------------------------
function WideComposeHangul(const Source: WideString): WideString;
var
Len: Integer;
Ch, Last: WideChar;
I: Integer;
LIndex, VIndex,
SIndex, TIndex: Integer;
begin
Result := '';
Len := Length(Source);
if Len > 0 then
begin
Last := Source[1];
Result := Last;
for I := 2 to Len do
begin
Ch := Source[I];
// 1. check to see if two current characters are L and V
LIndex := Word(Last) - LBase;
if (0 <= LIndex) and (LIndex < LCount) then
begin
VIndex := Word(Ch) - VBase;
if (0 <= VIndex) and (VIndex < VCount) then
begin
// make syllable of form LV
Last := WideChar((SBase + (LIndex * VCount + VIndex) * TCount));
Result[Length(Result)] := Last; // reset last
Continue; // discard Ch
end;
end;
// 2. check to see if two current characters are LV and T
SIndex := Word(Last) - SBase;
if (0 <= SIndex) and (SIndex < SCount) and ((SIndex mod TCount) = 0) then
begin
TIndex := Word(Ch) - TBase;
if (0 <= TIndex) and (TIndex <= TCount) then
begin
// make syllable of form LVT
Inc(Word(Last), TIndex);
Result[Length(Result)] := Last; // reset last
Continue; // discard Ch
end;
end;
// if neither case was true, just add the character
Last := Ch;
Result := Result + Ch;
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideCompose(const S: WideString): WideString;
// Returns canonical composition of characters in S.
var
StarterPos,
CompPos,
DecompPos: Integer;
Composite: UCS4Char;
Ch,
StarterChar: WideChar;
LastClass,
CurrentClass: Cardinal;
begin
// Set an arbitrary length for the result. This is automatically done when checking
// for hangul composition.
Result := WideComposeHangul(S);
StarterPos := 1;
CompPos := 2;
StarterChar := Result[StarterPos];
LastClass := CanonicalCombiningClass(UCS4Char(StarterChar));
if LastClass <> 0 then
LastClass := 256; // fix for irregular combining sequence
// Loop on the (decomposed) characters, combining where possible.
for DecompPos := 2 to Length(Result) do
begin
Ch := Result[DecompPos];
CurrentClass := CanonicalCombiningClass(UCS4Char(Ch));
if UnicodeComposePair(UCS4Char(StarterChar), UCS4Char(Ch), Composite) and
((LastClass < CurrentClass) or (LastClass = 0)) then
begin
Result[StarterPos] := UCS2Char(Composite);
StarterChar := UCS2Char(Composite);
end
else
begin
if CurrentClass = 0 then
begin
StarterPos := CompPos;
StarterChar := Ch;
end;
LastClass := CurrentClass;
Result[CompPos] := Ch;
Inc(CompPos);
end;
end;
// since we have likely shortened the source string we have to set the correct length on exit
SetLength(Result, CompPos - 1);
end;
//----------------------------------------------------------------------------------------------------------------------
procedure FixCanonical(var S: WideString);
// Examines S and reorders all combining marks in the string so that they are in canonical order.
var
I: Integer;
Temp: WideChar;
CurrentClass,
LastClass: Cardinal;
begin
I := Length(S);
if I > 1 then
begin
CurrentClass := CanonicalCombiningClass(UCS4Char(S[I]));
repeat
Dec(I);
LastClass := CurrentClass;
CurrentClass := CanonicalCombiningClass(UCS4Char(S[I]));
// A swap is presumed to be rare (and a double-swap very rare),
// so don't worry about efficiency here.
if (CurrentClass > LastClass) and (LastClass > 0) then
begin
// swap characters
Temp := S[I];
S[I] := S[I + 1];
S[I + 1] := Temp;
// if not at end, backup (one further, to compensate for loop)
if I < Length(S) - 1 then
Inc(I, 2);
// reset type, since we swapped.
CurrentClass := CanonicalCombiningClass(UCS4Char(S[I]));
end;
until I = 1;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure GetDecompositions(Compatible: Boolean; Code: UCS4Char; var Buffer: UCS4String);
// helper function to recursively decompose a code point
var
Decomp: UCS4String;
I: Integer;
begin
Decomp := UnicodeDecompose(Code, Compatible);
if Assigned(Decomp) then
begin
for I := 0 to High(Decomp) do
GetDecompositions(Compatible, Decomp[I], Buffer);
end
else // if no decomp, append
begin
I := Length(Buffer);
SetLength(Buffer, I + 1);
Buffer[I] := Code;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideDecompose(const S: WideString; Compatible: Boolean): WideString;
// returns a string with all characters of S but decomposed, e.g. is returned as E^ etc.
var
I, J: Integer;
Decomp: UCS4String;
begin
Result := '';
Decomp := nil;
// iterate through each source code point
for I := 1 to Length(S) do
begin
Decomp := nil;
GetDecompositions(Compatible, UCS4Char(S[I]), Decomp);
if Decomp = nil then
Result := Result + S[I]
else
for J := 0 to High(Decomp) do
Result := Result + WideChar(Decomp[J]);
end;
// combining marks must be sorted according to their canonical combining class
FixCanonical(Result);
end;
//----------------- general purpose case mapping ---------------------------------------------------
// Note that most of the assigned code points don't have a case mapping and are therefore
// returned as they are. Other code points, however, might be converted into several characters
// like the german (eszett) whose upper case mapping is SS.
function WideCaseFolding(C: WideChar): WideString;
// Special case folding function to map a string to either its lower case or
// to special cases. This can be used for case-insensitive comparation.
var
I: Integer;
Mapping: UCS4String;
begin
Mapping := UnicodeCaseFold(UCS4Char(C));
SetLength(Result, Length(Mapping));
for I := 0 to High(Mapping) do
Result[I + 1] := WideChar(Mapping[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideCaseFolding(const S: WideString): WideString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
Result := Result + WideCaseFolding(S[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideLowerCase(C: WideChar): WideString;
var
I: Integer;
Mapping: UCS4String;
begin
Mapping := UnicodeToLower(UCS4Char(C));
SetLength(Result, Length(Mapping));
for I := 0 to High(Mapping) do
Result[I + 1] := WideChar(Mapping[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideLowerCase(const S: WideString): WideString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
Result := Result + WideLowerCase(S[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideNormalize(const S: WideString; Form: TNormalizationForm): WideString;
var
Temp: WideString;
Compatible: Boolean;
begin
if Form = nfNone then
Result := S
else
begin
Compatible := Form in [nfKC, nfKD];
if Form in [nfD, nfKD] then
Result := WideDecompose(S, Compatible)
else
begin
Temp := WideDecompose(S, Compatible);
Result := WideCompose(Temp);
end;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideSameText(const Str1, Str2: WideString): Boolean;
// Compares both strings case-insensitively and returns True if both are equal, otherwise False is returned.
begin
Result := Length(Str1) = Length(Str2);
if Result then
Result := StrICompW(PWideChar(Str1), PWideChar(Str2)) = 0;
end;
//----------------------------------------------------------------------------------------------------------------------
function WideTitleCase(C: WideChar): WideString;
var
I: Integer;
Mapping: UCS4String;
begin
Mapping := UnicodeToTitle(UCS4Char(C));
SetLength(Result, Length(Mapping));
for I := 0 to High(Mapping) do
Result[I + 1] := WideChar(Mapping[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideTitleCase(const S: WideString): WideString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
Result := Result + WideTitleCase(S[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideUpperCase(C: WideChar): WideString;
var
I: Integer;
Mapping: UCS4String;
begin
Mapping := UnicodeToUpper(UCS4Char(C));
SetLength(Result, Length(Mapping));
for I := 0 to High(Mapping) do
Result[I + 1] := WideChar(Mapping[I]);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideUpperCase(const S: WideString): WideString;
var
I: Integer;
begin
Result := '';
for I := 1 to Length(S) do
Result := Result + WideUpperCase(S[I]);
end;
//----------------- character test routines --------------------------------------------------------
function UnicodeIsAlpha(C: UCS4Char): Boolean;
// Is the character alphabetic?
begin
Result := CategoryLookup(C, ClassLetter);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsDigit(C: UCS4Char): Boolean;
// Is the character a digit?
begin
Result := CategoryLookup(C, [ccNumberDecimalDigit]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsAlphaNum(C: UCS4Char): Boolean;
// Is the character alphabetic or a number?
begin
Result := CategoryLookup(C, ClassLetter + [ccNumberDecimalDigit]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsCased(C: UCS4Char): Boolean;
// Is the character a "cased" character, i.e. either lower case, title case or upper case
begin
Result := CategoryLookup(C, [ccLetterLowercase, ccLetterTitleCase, ccLetterUppercase]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsControl(C: UCS4Char): Boolean;
// Is the character a control character?
begin
Result := CategoryLookup(C, [ccOtherControl, ccOtherFormat]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSpace(C: UCS4Char): Boolean;
// Is the character a spacing character?
begin
Result := CategoryLookup(C, ClassSpace);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsWhiteSpace(C: UCS4Char): Boolean;
// Is the character a white space character (same as UnicodeIsSpace plus
// tabulator, new line etc.)?
begin
Result := CategoryLookup(C, ClassSpace + [ccWhiteSpace, ccSeparatorParagraph, ccSegmentSeparator]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsBlank(C: UCS4Char): Boolean;
// Is the character a space separator?
begin
Result := CategoryLookup(C, [ccSeparatorSpace]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsPunctuation(C: UCS4Char): Boolean;
// Is the character a punctuation mark?
begin
Result := CategoryLookup(C, ClassPunctuation);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsGraph(C: UCS4Char): Boolean;
// Is the character graphical?
begin
Result := CategoryLookup(C, ClassMark + ClassNumber + ClassLetter + ClassPunctuation + ClassSymbol);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsPrintable(C: UCS4Char): Boolean;
// Is the character printable?
begin
Result := CategoryLookup(C, ClassMark + ClassNumber + ClassLetter + ClassPunctuation + ClassSymbol +
[ccSeparatorSpace]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsUpper(C: UCS4Char): Boolean;
// Is the character already upper case?
begin
Result := CategoryLookup(C, [ccLetterUppercase]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsLower(C: UCS4Char): Boolean;
// Is the character already lower case?
begin
Result := CategoryLookup(C, [ccLetterLowercase]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsTitle(C: UCS4Char): Boolean;
// Is the character already title case?
begin
Result := CategoryLookup(C, [ccLetterTitlecase]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsHexDigit(C: UCS4Char): Boolean;
// Is the character a hex digit?
begin
// TODO: switch to ccHexDigit once it is set while compiling Unicode data.
// Result := CategoryLookup(C, [ccHexDigit]);
Result := ((C and $FF) = C) and (Char(C) in ['a'..'f', 'A'..'F', '0'..'9']);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsIsoControl(C: UCS4Char): Boolean;
// Is the character a C0 control character (< 32)?
begin
Result := CategoryLookup(C, [ccOtherControl]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsFormatControl(C: UCS4Char): Boolean;
// Is the character a format control character?
begin
Result := CategoryLookup(C, [ccOtherFormat]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSymbol(C: UCS4Char): Boolean;
// Is the character a symbol?
begin
Result := CategoryLookup(C, ClassSymbol);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsNumber(C: UCS4Char): Boolean;
// Is the character a number or digit?
begin
Result := CategoryLookup(C, ClassNumber);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsNonSpacing(C: UCS4Char): Boolean;
// Is the character non-spacing?
begin
Result := CategoryLookup(C, [ccMarkNonSpacing]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsOpenPunctuation(C: UCS4Char): Boolean;
// Is the character an open/left punctuation (e.g. '[')?
begin
Result := CategoryLookup(C, [ccPunctuationOpen]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsClosePunctuation(C: UCS4Char): Boolean;
// Is the character an close/right punctuation (e.g. ']')?
begin
Result := CategoryLookup(C, [ccPunctuationClose]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsInitialPunctuation(C: UCS4Char): Boolean;
// Is the character an initial punctuation (e.g. U+2018 LEFT SINGLE QUOTATION MARK)?
begin
Result := CategoryLookup(C, [ccPunctuationInitialQuote]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsFinalPunctuation(C: UCS4Char): Boolean;
// Is the character a final punctuation (e.g. U+2019 RIGHT SINGLE QUOTATION MARK)?
begin
Result := CategoryLookup(C, [ccPunctuationFinalQuote]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsComposed(C: UCS4Char): Boolean;
// Can the character be decomposed into a set of other characters?
begin
Result := CategoryLookup(C, [ccComposed]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsQuotationMark(C: UCS4Char): Boolean;
// Is the character one of the many quotation marks?
begin
Result := CategoryLookup(C, [ccQuotationMark]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSymmetric(C: UCS4Char): Boolean;
// Is the character one that has an opposite form (i.e. <>)?
begin
Result := CategoryLookup(C, [ccSymmetric]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsMirroring(C: UCS4Char): Boolean;
// Is the character mirroring (superset of symmetric)?
begin
Result := CategoryLookup(C, [ccMirroring]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsNonBreaking(C: UCS4Char): Boolean;
// Is the character non-breaking (i.e. non-breaking space)?
begin
Result := CategoryLookup(C, [ccNonBreaking]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsRightToLeft(C: UCS4Char): Boolean;
// Does the character have strong right-to-left directionality (i.e. Arabic letters)?
begin
Result := CategoryLookup(C, [ccRightToLeft]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsLeftToRight(C: UCS4Char): Boolean;
// Does the character have strong left-to-right directionality (i.e. Latin letters)?
begin
Result := CategoryLookup(C, [ccLeftToRight]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsStrong(C: UCS4Char): Boolean;
// Does the character have strong directionality?
begin
Result := CategoryLookup(C, [ccLeftToRight, ccRightToLeft]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsWeak(C: UCS4Char): Boolean;
// Does the character have weak directionality (i.e. numbers)?
begin
Result := CategoryLookup(C, ClassEuropeanNumber + [ccArabicNumber, ccCommonNumberSeparator]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsNeutral(C: UCS4Char): Boolean;
// Does the character have neutral directionality (i.e. whitespace)?
begin
Result := CategoryLookup(C, [ccSeparatorParagraph, ccSegmentSeparator, ccWhiteSpace, ccOtherNeutrals]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSeparator(C: UCS4Char): Boolean;
// Is the character a block or segment separator?
begin
Result := CategoryLookup(C, [ccSeparatorParagraph, ccSegmentSeparator]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsMark(C: UCS4Char): Boolean;
// Is the character a mark of some kind?
begin
Result := CategoryLookup(C, ClassMark);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsModifier(C: UCS4Char): Boolean;
// Is the character a letter modifier?
begin
Result := CategoryLookup(C, [ccLetterModifier]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsLetterNumber(C: UCS4Char): Boolean;
// Is the character a number represented by a letter?
begin
Result := CategoryLookup(C, [ccNumberLetter]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsConnectionPunctuation(C: UCS4Char): Boolean;
// Is the character connecting punctuation?
begin
Result := CategoryLookup(C, [ccPunctuationConnector]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsDash(C: UCS4Char): Boolean;
// Is the character a dash punctuation?
begin
Result := CategoryLookup(C, [ccPunctuationDash]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsMath(C: UCS4Char): Boolean;
// Is the character a math character?
begin
Result := CategoryLookup(C, [ccSymbolMath]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsCurrency(C: UCS4Char): Boolean;
// Is the character a currency character?
begin
Result := CategoryLookup(C, [ccSymbolCurrency]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsModifierSymbol(C: UCS4Char): Boolean;
// Is the character a modifier symbol?
begin
Result := CategoryLookup(C, [ccSymbolModifier]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsNonSpacingMark(C: UCS4Char): Boolean;
// Is the character a non-spacing mark?
begin
Result := CategoryLookup(C, [ccMarkNonSpacing]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSpacingMark(C: UCS4Char): Boolean;
// Is the character a spacing mark?
begin
Result := CategoryLookup(C, [ccMarkSpacingCombining]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsEnclosing(C: UCS4Char): Boolean;
// Is the character enclosing (i.e. enclosing box)?
begin
Result := CategoryLookup(C, [ccMarkEnclosing]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsPrivate(C: UCS4Char): Boolean;
// Is the character from the Private Use Area?
begin
Result := CategoryLookup(C, [ccOtherPrivate]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsSurrogate(C: UCS4Char): Boolean;
// Is the character one of the surrogate codes?
begin
Result := CategoryLookup(C, [ccOtherSurrogate]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsLineSeparator(C: UCS4Char): Boolean;
// Is the character a line separator?
begin
Result := CategoryLookup(C, [ccSeparatorLine]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsParagraphSeparator(C: UCS4Char): Boolean;
// Is th character a paragraph separator;
begin
Result := CategoryLookup(C, [ccSeparatorParagraph]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsIdentifierStart(C: UCS4Char): Boolean;
// Can the character begin an identifier?
begin
Result := CategoryLookup(C, ClassLetter + [ccNumberLetter]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsIdentifierPart(C: UCS4Char): Boolean;
// Can the character appear in an identifier?
begin
Result := CategoryLookup(C, ClassLetter + [ccNumberLetter, ccMarkNonSpacing, ccMarkSpacingCombining,
ccNumberDecimalDigit, ccPunctuationConnector, ccOtherFormat]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsDefined(C: UCS4Char): Boolean;
// Is the character defined (appears in one of the data files)?
begin
Result := CategoryLookup(C, [ccAssigned]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsUndefined(C: UCS4Char): Boolean;
// Is the character undefined (not assigned in the Unicode database)?
begin
Result := not CategoryLookup(C, [ccAssigned]);
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsHan(C: UCS4Char): Boolean;
// Is the character a Han ideograph?
begin
Result := ((C >= $4E00) and (C <= $9FFF)) or ((C >= $F900) and (C <= $FAFF));
end;
//----------------------------------------------------------------------------------------------------------------------
function UnicodeIsHangul(C: UCS4Char): Boolean;
// Is the character a pre-composed Hangul syllable?
begin
Result := (C >= $AC00) and (C <= $D7FF);
end;
//----------------------------------------------------------------------------------------------------------------------
// I need to fix a problem (introduced by MS) here. The first parameter can be a pointer
// (and is so defined) or can be a normal DWORD, depending on the dwFlags parameter.
// As usual, lpSrc has been translated to a var parameter. But this does not work in
// our case, hence the redeclaration of the function with a pointer as first parameter.
function TranslateCharsetInfoEx(lpSrc: PDWORD; var lpCs: TCharsetInfo; dwFlags: DWORD): BOOL; stdcall;
external 'gdi32.dll' name 'TranslateCharsetInfo';
function CharSetFromLocale(Language: LCID): TFontCharSet;
var
CP: Cardinal;
CSI: TCharsetInfo;
begin
CP := CodePageFromLocale(Language);
TranslateCharsetInfoEx(Pointer(CP), CSI, TCI_SRCCODEPAGE);
Result := CSI.ciCharset;
end;
//----------------------------------------------------------------------------------------------------------------------
function CodePageFromLocale(Language: LCID): Integer;
// determines the code page for a given locale
var
Buf: array[0..6] of Char;
begin
GetLocaleInfo(Language, LOCALE_IDefaultAnsiCodePage, Buf, 6);
Result := StrToIntDef(Buf, GetACP);
end;
//----------------------------------------------------------------------------------------------------------------------
function KeyboardCodePage: Word;
begin
Result := CodePageFromLocale(GetKeyboardLayout(0) and $FFFF);
end;
//----------------------------------------------------------------------------------------------------------------------
function KeyUnicode(C: Char): WideChar;
// converts the given character (as it comes with a WM_CHAR message) into its
// corresponding Unicode character depending on the active keyboard layout
begin
MultiByteToWideChar(KeyboardCodePage, MB_USEGLYPHCHARS, @C, 1, @Result, 1);
end;
//----------------------------------------------------------------------------------------------------------------------
function CodeBlockFromChar(const C: UCS4Char): TUnicodeBlock;
// Returns an ID for the Unicode code block to which C belongs.
// If C does not belong to any of the defined blocks then ubUndefined is returned.
// Note: the code blocks listed here are based on Unicode Version 3.1.
begin
case C of
$0000..$007F:
Result := ubBasicLatin;
$0080..$00FF:
Result := ubLatin1Supplement;
$0100..$017F:
Result := ubLatinExtendedA;
$0180..$024F:
Result := ubLatinExtendedB;
$0250..$02AF:
Result := ubIPAExtensions;
$02B0..$02FF:
Result := ubSpacingModifierLetters;
$0300..$036F:
Result := ubCombiningDiacriticalMarks;
$0370..$03FF:
Result := ubGreek;
$0400..$04FF:
Result := ubCyrillic;
$0530..$058F:
Result := ubArmenian;
$0590..$05FF:
Result := ubHebrew;
$0600..$06FF:
Result := ubArabic;
$0700..$074F:
Result := ubSyriac;
$0780..$07BF:
Result := ubThaana;
$0900..$097F:
Result := ubDevanagari;
$0980..$09FF:
Result := ubBengali;
$0A00..$0A7F:
Result := ubGurmukhi;
$0A80..$0AFF:
Result := ubGujarati;
$0B00..$0B7F:
Result := ubOriya;
$0B80..$0BFF:
Result := ubTamil;
$0C00..$0C7F:
Result := ubTelugu;
$0C80..$0CFF:
Result := ubKannada;
$0D00..$0D7F:
Result := ubMalayalam;
$0D80..$0DFF:
Result := ubSinhala;
$0E00..$0E7F:
Result := ubThai;
$0E80..$0EFF:
Result := ubLao;
$0F00..$0FFF:
Result := ubTibetan;
$1000..$109F:
Result := ubMyanmar;
$10A0..$10FF:
Result := ubGeorgian;
$1100..$11FF:
Result := ubHangulJamo;
$1200..$137F:
Result := ubEthiopic;
$13A0..$13FF:
Result := ubCherokee;
$1400..$167F:
Result := ubUnifiedCanadianAboriginalSyllabics;
$1680..$169F:
Result := ubOgham;
$16A0..$16FF:
Result := ubRunic;
$1780..$17FF:
Result := ubKhmer;
$1800..$18AF:
Result := ubMongolian;
$1E00..$1EFF:
Result := ubLatinExtendedAdditional;
$1F00..$1FFF:
Result := ubGreekExtended;
$2000..$206F:
Result := ubGeneralPunctuation;
$2070..$209F:
Result := ubSuperscriptsAndSubscripts;
$20A0..$20CF:
Result := ubCurrencySymbols;
$20D0..$20FF:
Result := ubCombiningMarksForSymbols;
$2100..$214F:
Result := ubLetterlikeSymbols;
$2150..$218F:
Result := ubNumberForms;
$2190..$21FF:
Result := ubArrows;
$2200..$22FF:
Result := ubMathematicalOperators;
$2300..$23FF:
Result := ubMiscellaneousTechnical;
$2400..$243F:
Result := ubControlPictures;
$2440..$245F:
Result := ubOpticalCharacterRecognition;
$2460..$24FF:
Result := ubEnclosedAlphanumerics;
$2500..$257F:
Result := ubBoxDrawing;
$2580..$259F:
Result := ubBlockElements;
$25A0..$25FF:
Result := ubGeometricShapes;
$2600..$26FF:
Result := ubMiscellaneousSymbols;
$2700..$27BF:
Result := ubDingbats;
$2800..$28FF:
Result := ubBraillePatterns;
$2E80..$2EFF:
Result := ubCJKRadicalsSupplement;
$2F00..$2FDF:
Result := ubKangxiRadicals;
$2FF0..$2FFF:
Result := ubIdeographicDescriptionCharacters;
$3000..$303F:
Result := ubCJKSymbolsAndPunctuation;
$3040..$309F:
Result := ubHiragana;
$30A0..$30FF:
Result := ubKatakana;
$3100..$312F:
Result := ubBopomofo;
$3130..$318F:
Result := ubHangulCompatibilityJamo;
$3190..$319F:
Result := ubKanbun;
$31A0..$31BF:
Result := ubBopomofoExtended;
$3200..$32FF:
Result := ubEnclosedCJKLettersAndMonths;
$3300..$33FF:
Result := ubCJKCompatibility;
$3400..$4DB5:
Result := ubCJKUnifiedIdeographsExtensionA;
$4E00..$9FFF:
Result := ubCJKUnifiedIdeographs;
$A000..$A48F:
Result := ubYiSyllables;
$A490..$A4CF:
Result := ubYiRadicals;
$AC00..$D7A3:
Result := ubHangulSyllables;
$D800..$DB7F:
Result := ubHighSurrogates;
$DB80..$DBFF:
Result := ubHighPrivateUseSurrogates;
$DC00..$DFFF:
Result := ubLowSurrogates;
$E000..$F8FF,
$F0000..$FFFFD,
$100000..$10FFFD:
Result := ubPrivateUse;
$F900..$FAFF:
Result := ubCJKCompatibilityIdeographs;
$FB00..$FB4F:
Result := ubAlphabeticPresentationForms;
$FB50..$FDFF:
Result := ubArabicPresentationFormsA;
$FE20..$FE2F:
Result := ubCombiningHalfMarks;
$FE30..$FE4F:
Result := ubCJKCompatibilityForms;
$FE50..$FE6F:
Result := ubSmallFormVariants;
$FE70..$FEFE:
Result := ubArabicPresentationFormsB;
$FEFF..$FEFF,
$FFF0..$FFFD:
Result := ubSpecials;
$FF00..$FFEF:
Result := ubHalfwidthAndFullwidthForms;
$10300..$1032F:
Result := ubOldItalic;
$10330..$1034F:
Result := ubGothic;
$10400..$1044F:
Result := ubDeseret;
$1D000..$1D0FF:
Result := ubByzantineMusicalSymbols;
$1D100..$1D1FF:
Result := ubMusicalSymbols;
$1D400..$1D7FF:
Result := ubMathematicalAlphanumericSymbols;
$20000..$2A6D6:
Result := ubCJKUnifiedIdeographsExtensionB;
$2F800..$2FA1F:
Result := ubCJKCompatibilityIdeographsSupplement;
$E0000..$E007F:
Result := ubTags;
else
Result := ubUndefined;
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function CompareTextWin95(W1, W2: WideString; Locale: LCID): Integer;
// special comparation function for Win9x since there's no system defined
// comparation function, returns -1 if W1 < W2, 0 if W1 = W2 or 1 if W1 > W2
var
S1, S2: string;
CP: Integer;
L1, L2: Integer;
begin
L1 := Length(W1);
L2 := Length(W2);
SetLength(S1, L1);
SetLength(S2, L2);
CP := CodePageFromLocale(Locale);
WideCharToMultiByte(CP, 0, PWideChar(W1), L1, PChar(S1), L1, nil, nil);
WideCharToMultiByte(CP, 0, PWideChar(W2), L2, PChar(S2), L2, nil, nil);
Result := CompareStringA(Locale, NORM_IGNORECASE, PChar(S1), Length(S1),
PChar(S2), Length(S2)) - 2;
end;
//----------------------------------------------------------------------------------------------------------------------
function CompareTextWinNT(W1, W2: WideString; Locale: LCID): Integer;
// Wrapper function for WinNT since there's no system defined comparation function
// in Win9x and we need a central comparation function for TWideStringList.
// Returns -1 if W1 < W2, 0 if W1 = W2 or 1 if W1 > W2
begin
Result := CompareStringW(Locale, NORM_IGNORECASE, PWideChar(W1), Length(W1),
PWideChar(W2), Length(W2)) - 2;
end;
//----------------------------------------------------------------------------------------------------------------------
function StringToWideStringEx(const S: string; CodePage: Word): WideString;
var
InputLength,
OutputLength: Integer;
begin
InputLength := Length(S);
OutputLength := MultiByteToWideChar(CodePage, 0, PChar(S), InputLength, nil, 0);
SetLength(Result, OutputLength);
MultiByteToWideChar(CodePage, 0, PChar(S), InputLength, PWideChar(Result), OutputLength);
end;
//----------------------------------------------------------------------------------------------------------------------
function WideStringToStringEx(const WS: WideString; CodePage: Word): string;
var
InputLength,
OutputLength: Integer;
begin
InputLength := Length(WS);
OutputLength := WideCharToMultiByte(CodePage, 0, PWideChar(WS), InputLength, nil, 0, nil, nil);
SetLength(Result, OutputLength);
WideCharToMultiByte(CodePage, 0, PWideChar(WS), InputLength, PChar(Result), OutputLength, nil, nil);
end;
//----------------------------------------------------------------------------------------------------------------------
function TranslateString(const S: string; CP1, CP2: Word): string;
begin
Result := WideStringToStringEx(StringToWideStringEx(S, CP1), CP2);
end;
//----------------- conversion routines ------------------------------------------------------------
procedure ExpandANSIString(const Source: PChar; Target: PWideChar; Count: Cardinal);
// Converts the given source ANSI string into a Unicode string by expanding each character
// from one byte to two bytes.
// EAX contains Source, EDX contains Target, ECX contains Count
asm
JECXZ @@Finish // go out if there is nothing to do
PUSH ESI
MOV ESI, EAX
XOR EAX, EAX
@@1:
MOV AL, [ESI]
INC ESI
MOV [EDX], AX
ADD EDX, 2
DEC ECX
JNZ @@1
POP ESI
@@Finish:
end;
//----------------------------------------------------------------------------------------------------------------------
const
HalfShift: Integer = 10;
HalfBase: UCS4Char = $0010000;
HalfMask: UCS4Char = $3FF;
OffsetsFromUTF8: array[0..5] of UCS4Char = ($00000000, $00003080, $000E2080, $03C82080, $FA082080, $82082080);
BytesFromUTF8: array[0..255] of Byte = (
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 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, 5, 5);
FirstByteMark: array[0..6] of Byte = ($00, $00, $C0, $E0, $F0, $F8, $FC);
//----------------------------------------------------------------------------------------------------------------------
function WideStringToUTF8(S: WideString): AnsiString;
var
Ch: UCS4Char;
L, J, T,
BytesToWrite: Cardinal;
ByteMask: UCS4Char;
ByteMark: UCS4Char;
begin
if Length(S) = 0 then
Result := ''
else
begin
SetLength(Result, Length(S) * 6); // assume worst case
T := 1;
ByteMask := $BF;
ByteMark := $80;
for J := 1 to Length(S) do
begin
Ch := UCS4Char(S[J]);
if Ch < $80 then
BytesToWrite := 1
else
if Ch < $800 then
BytesToWrite := 2
else
if Ch < $10000 then
BytesToWrite := 3
else
if Ch < $200000 then
BytesToWrite := 4
else
if Ch < $4000000 then
BytesToWrite := 5
else
if Ch <= MaximumUCS4 then
BytesToWrite := 6
else
begin
BytesToWrite := 2;
Ch := ReplacementCharacter;
end;
for L := BytesToWrite downto 2 do
begin
Result[T + L - 1] := Char((Ch or ByteMark) and ByteMask);
Ch := Ch shr 6;
end;
Result[T] := Char(Ch or FirstByteMark[BytesToWrite]);
Inc(T, BytesToWrite);
end;
SetLength(Result, T - 1); // set to actual length
end;
end;
//----------------------------------------------------------------------------------------------------------------------
function UTF8ToWideString(S: AnsiString): WideString;
var
L, J, T: Cardinal;
Ch: UCS4Char;
ExtraBytesToWrite: Word;
begin
if Length(S) = 0 then
Result := ''
else
begin
SetLength(Result, Length(S)); // create enough room
L := 1;
T := 1;
while L <= Cardinal(Length(S)) do
begin
Ch := 0;
ExtraBytesToWrite := BytesFromUTF8[Ord(S[L])];
for J := ExtraBytesToWrite downto 1 do
begin
Ch := Ch + Ord(S[L]);
Inc(L);
Ch := Ch shl 6;
end;
Ch := Ch + Ord(S[L]);
Inc(L);
Ch := Ch - OffsetsFromUTF8[ExtraBytesToWrite];
if Ch <= MaximumUCS2 then
begin
Result[T] := WideChar(Ch);
Inc(T);
end
else
if Ch > MaximumUCS4 then
begin
Result[T] := WideChar(ReplacementCharacter);
Inc(T);
end
else
begin
Ch := Ch - HalfBase;
Result[T] := WideChar((Ch shr HalfShift) + SurrogateHighStart);
Inc(T);
Result[T] := WideChar((Ch and HalfMask) + SurrogateLowStart);
Inc(T);
end;
end;
SetLength(Result, T - 1); // now fix up length
end;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure PrepareUnicodeData;
// Prepares structures which are globally needed.
begin
LoadInProgress := TCriticalSection.Create;
if (Win32Platform and VER_PLATFORM_WIN32_NT) <> 0 then
@WideCompareText := @CompareTextWinNT
else
@WideCompareText := @CompareTextWin95;
end;
//----------------------------------------------------------------------------------------------------------------------
procedure FreeUnicodeData;
// Frees all data which has been allocated and which is not automatically freed by Delphi.
begin
FreeAndNil(LoadInProgress);
end;
//----------------------------------------------------------------------------------------------------------------------
initialization
PrepareUnicodeData;
finalization
FreeUnicodeData;
end.
|