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
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 1997-2016, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* File SMPDTFMT.CPP
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/31/97 aliu Modified extensively to work with 50 locales.
* 04/01/97 aliu Added support for centuries.
* 07/09/97 helena Made ParsePosition into a class.
* 07/21/98 stephen Added initializeDefaultCentury.
* Removed getZoneIndex (added in DateFormatSymbols)
* Removed subParseLong
* Removed chk
* 02/22/99 stephen Removed character literals for EBCDIC safety
* 10/14/99 aliu Updated 2-digit year parsing so that only "00" thru
* "99" are recognized. {j28 4182066}
* 11/15/99 weiv Added support for week of year/day of week format
********************************************************************************
*/
#define ZID_KEY_MAX 128
#include <_foundation_unicode/utypes.h>
#if !UCONFIG_NO_FORMATTING
#include <_foundation_unicode/smpdtfmt.h>
#include <_foundation_unicode/dtfmtsym.h>
#include <_foundation_unicode/ures.h>
#include <_foundation_unicode/msgfmt.h>
#include <_foundation_unicode/calendar.h>
#include <_foundation_unicode/gregocal.h>
#include <_foundation_unicode/timezone.h>
#include <_foundation_unicode/decimfmt.h>
#include <_foundation_unicode/dcfmtsym.h>
#include <_foundation_unicode/uchar.h>
#include <_foundation_unicode/uniset.h>
#include <_foundation_unicode/ustring.h>
#include <_foundation_unicode/basictz.h>
#include <_foundation_unicode/simpleformatter.h>
#include <_foundation_unicode/simplenumberformatter.h>
#include <_foundation_unicode/simpletz.h>
#include <_foundation_unicode/rbtz.h>
#include <_foundation_unicode/tzfmt.h>
#include <_foundation_unicode/ucasemap.h>
#include <_foundation_unicode/utf16.h>
#include <_foundation_unicode/vtzone.h>
#include <_foundation_unicode/udisplaycontext.h>
#include <_foundation_unicode/brkiter.h>
#include <_foundation_unicode/rbnf.h>
#include <_foundation_unicode/dtptngen.h>
#include "uresimp.h"
#include "olsontz.h"
#include "patternprops.h"
#include "fphdlimp.h"
#include "hebrwcal.h"
#include "cstring.h"
#include "uassert.h"
#include "cmemory.h"
#include "umutex.h"
#include "mutex.h"
#include <float.h>
#include "smpdtfst.h"
#include "sharednumberformat.h"
#include "ucasemap_imp.h"
#include "ulocimp.h"
#include "ustr_imp.h"
#include "charstr.h"
#include "uvector.h"
#include "cstr.h"
#include "dayperiodrules.h"
#include "tznames_impl.h" // ZONE_NAME_U16_MAX
#include "number_utypes.h"
#if APPLE_ICU_CHANGES
// rdar://
#include "dtptngen_impl.h" // for datePatternHasNumericCore()
// rdar://106782612 compatibility: format with plain spaces for specific app(s)
#include <stdlib.h> // for getprogname()
#if U_PLATFORM_IS_DARWIN_BASED
#include <os/log.h>
#endif // U_PLATFORM_IS_DARWIN_BASED
#endif // APPLE_ICU_CHANGES
#if APPLE_ICU_CHANGES
// rdar://
#define DEBUG_SYNTHETIC_TIMEFMTS 0
#if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL) || DEBUG_SYNTHETIC_TIMEFMTS
#include <stdio.h>
#endif
#else
#if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
#include <stdio.h>
#endif
#endif // APPLE_ICU_CHANGES
// *****************************************************************************
// class SimpleDateFormat
// *****************************************************************************
U_NAMESPACE_BEGIN
/**
* Last-resort string to use for "GMT" when constructing time zone strings.
*/
// For time zones that have no names, use strings GMT+minutes and
// GMT-minutes. For instance, in France the time zone is GMT+60.
// Also accepted are GMT+H:MM or GMT-H:MM.
// Currently not being used
//static const char16_t gGmt[] = {0x0047, 0x004D, 0x0054, 0x0000}; // "GMT"
//static const char16_t gGmtPlus[] = {0x0047, 0x004D, 0x0054, 0x002B, 0x0000}; // "GMT+"
//static const char16_t gGmtMinus[] = {0x0047, 0x004D, 0x0054, 0x002D, 0x0000}; // "GMT-"
//static const char16_t gDefGmtPat[] = {0x0047, 0x004D, 0x0054, 0x007B, 0x0030, 0x007D, 0x0000}; /* GMT{0} */
//static const char16_t gDefGmtNegHmsPat[] = {0x002D, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x003A, 0x0073, 0x0073, 0x0000}; /* -HH:mm:ss */
//static const char16_t gDefGmtNegHmPat[] = {0x002D, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x0000}; /* -HH:mm */
//static const char16_t gDefGmtPosHmsPat[] = {0x002B, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x003A, 0x0073, 0x0073, 0x0000}; /* +HH:mm:ss */
//static const char16_t gDefGmtPosHmPat[] = {0x002B, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x0000}; /* +HH:mm */
//static const char16_t gUt[] = {0x0055, 0x0054, 0x0000}; // "UT"
//static const char16_t gUtc[] = {0x0055, 0x0054, 0x0043, 0x0000}; // "UT"
typedef enum GmtPatSize {
kGmtLen = 3,
kGmtPatLen = 6,
kNegHmsLen = 9,
kNegHmLen = 6,
kPosHmsLen = 9,
kPosHmLen = 6,
kUtLen = 2,
kUtcLen = 3
} GmtPatSize;
// Stuff needed for numbering system overrides
typedef enum OvrStrType {
kOvrStrDate = 0,
kOvrStrTime = 1,
kOvrStrBoth = 2
} OvrStrType;
static const UDateFormatField kDateFields[] = {
UDAT_YEAR_FIELD,
UDAT_MONTH_FIELD,
UDAT_DATE_FIELD,
UDAT_DAY_OF_YEAR_FIELD,
UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
UDAT_WEEK_OF_YEAR_FIELD,
UDAT_WEEK_OF_MONTH_FIELD,
UDAT_YEAR_WOY_FIELD,
UDAT_EXTENDED_YEAR_FIELD,
UDAT_JULIAN_DAY_FIELD,
UDAT_STANDALONE_DAY_FIELD,
UDAT_STANDALONE_MONTH_FIELD,
UDAT_QUARTER_FIELD,
UDAT_STANDALONE_QUARTER_FIELD,
UDAT_YEAR_NAME_FIELD,
UDAT_RELATED_YEAR_FIELD };
static const int8_t kDateFieldsCount = 16;
static const UDateFormatField kTimeFields[] = {
UDAT_HOUR_OF_DAY1_FIELD,
UDAT_HOUR_OF_DAY0_FIELD,
UDAT_MINUTE_FIELD,
UDAT_SECOND_FIELD,
UDAT_FRACTIONAL_SECOND_FIELD,
UDAT_HOUR1_FIELD,
UDAT_HOUR0_FIELD,
UDAT_MILLISECONDS_IN_DAY_FIELD,
UDAT_TIMEZONE_RFC_FIELD,
UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD };
static const int8_t kTimeFieldsCount = 10;
// This is a pattern-of-last-resort used when we can't load a usable pattern out
// of a resource.
static const char16_t gDefaultPattern[] =
{
0x79, 0x4D, 0x4D, 0x64, 0x64, 0x20, 0x68, 0x68, 0x3A, 0x6D, 0x6D, 0x20, 0x61, 0
}; /* "yMMdd hh:mm a" */
// This prefix is designed to NEVER MATCH real text, in order to
// suppress the parsing of negative numbers. Adjust as needed (if
// this becomes valid Unicode).
static const char16_t SUPPRESS_NEGATIVE_PREFIX[] = {0xAB00, 0};
/**
* These are the tags we expect to see in normal resource bundle files associated
* with a locale.
*/
static const char16_t QUOTE = 0x27; // Single quote
/*
* The field range check bias for each UDateFormatField.
* The bias is added to the minimum and maximum values
* before they are compared to the parsed number.
* For example, the calendar stores zero-based month numbers
* but the parsed month numbers start at 1, so the bias is 1.
*
* A value of -1 means that the value is not checked.
*/
static const int32_t gFieldRangeBias[] = {
-1, // 'G' - UDAT_ERA_FIELD
-1, // 'y' - UDAT_YEAR_FIELD
1, // 'M' - UDAT_MONTH_FIELD
0, // 'd' - UDAT_DATE_FIELD
-1, // 'k' - UDAT_HOUR_OF_DAY1_FIELD
-1, // 'H' - UDAT_HOUR_OF_DAY0_FIELD
0, // 'm' - UDAT_MINUTE_FIELD
0, // 's' - UDAT_SECOND_FIELD
-1, // 'S' - UDAT_FRACTIONAL_SECOND_FIELD (0-999?)
-1, // 'E' - UDAT_DAY_OF_WEEK_FIELD (1-7?)
-1, // 'D' - UDAT_DAY_OF_YEAR_FIELD (1 - 366?)
-1, // 'F' - UDAT_DAY_OF_WEEK_IN_MONTH_FIELD (1-5?)
-1, // 'w' - UDAT_WEEK_OF_YEAR_FIELD (1-52?)
-1, // 'W' - UDAT_WEEK_OF_MONTH_FIELD (1-5?)
-1, // 'a' - UDAT_AM_PM_FIELD
-1, // 'h' - UDAT_HOUR1_FIELD
-1, // 'K' - UDAT_HOUR0_FIELD
-1, // 'z' - UDAT_TIMEZONE_FIELD
-1, // 'Y' - UDAT_YEAR_WOY_FIELD
-1, // 'e' - UDAT_DOW_LOCAL_FIELD
-1, // 'u' - UDAT_EXTENDED_YEAR_FIELD
-1, // 'g' - UDAT_JULIAN_DAY_FIELD
-1, // 'A' - UDAT_MILLISECONDS_IN_DAY_FIELD
-1, // 'Z' - UDAT_TIMEZONE_RFC_FIELD
-1, // 'v' - UDAT_TIMEZONE_GENERIC_FIELD
0, // 'c' - UDAT_STANDALONE_DAY_FIELD
1, // 'L' - UDAT_STANDALONE_MONTH_FIELD
-1, // 'Q' - UDAT_QUARTER_FIELD (1-4?)
-1, // 'q' - UDAT_STANDALONE_QUARTER_FIELD
-1, // 'V' - UDAT_TIMEZONE_SPECIAL_FIELD
-1, // 'U' - UDAT_YEAR_NAME_FIELD
-1, // 'O' - UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD
-1, // 'X' - UDAT_TIMEZONE_ISO_FIELD
-1, // 'x' - UDAT_TIMEZONE_ISO_LOCAL_FIELD
-1, // 'r' - UDAT_RELATED_YEAR_FIELD
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
-1, // ':' - UDAT_TIME_SEPARATOR_FIELD
#else
-1, // (no pattern character currently) - UDAT_TIME_SEPARATOR_FIELD
#endif
};
#if APPLE_ICU_CHANGES
// rdar://
// A slightly looser range check for lenient parsing
static const int32_t gFieldRangeBiasLenient[] = {
-1, // 'G' - UDAT_ERA_FIELD
-1, // 'y' - UDAT_YEAR_FIELD
8, // 'M' - UDAT_MONTH_FIELD (allow calendar max + 7, e.g. 19 for grego 1-based month)
18, // 'd' - UDAT_DATE_FIELD (allow calendar max + 18, e.g. 49 for grego; tests require at least 40 for grego)
-1, // 'k' - UDAT_HOUR_OF_DAY1_FIELD
-1, // 'H' - UDAT_HOUR_OF_DAY0_FIELD
40, // 'm' - UDAT_MINUTE_FIELD (allow calendar max + 40, e.g. 99)
40, // 's' - UDAT_SECOND_FIELD (allow calendar max + 40, e.g. 99)
-1, // 'S' - UDAT_FRACTIONAL_SECOND_FIELD (0-999?)
-1, // 'E' - UDAT_DAY_OF_WEEK_FIELD (1-7?)
-1, // 'D' - UDAT_DAY_OF_YEAR_FIELD (1 - 366?)
-1, // 'F' - UDAT_DAY_OF_WEEK_IN_MONTH_FIELD (1-5?)
-1, // 'w' - UDAT_WEEK_OF_YEAR_FIELD (1-52?)
-1, // 'W' - UDAT_WEEK_OF_MONTH_FIELD (1-5?)
-1, // 'a' - UDAT_AM_PM_FIELD
-1, // 'h' - UDAT_HOUR1_FIELD
-1, // 'K' - UDAT_HOUR0_FIELD
-1, // 'z' - UDAT_TIMEZONE_FIELD
-1, // 'Y' - UDAT_YEAR_WOY_FIELD
-1, // 'e' - UDAT_DOW_LOCAL_FIELD
-1, // 'u' - UDAT_EXTENDED_YEAR_FIELD
-1, // 'g' - UDAT_JULIAN_DAY_FIELD
-1, // 'A' - UDAT_MILLISECONDS_IN_DAY_FIELD
-1, // 'Z' - UDAT_TIMEZONE_RFC_FIELD
-1, // 'v' - UDAT_TIMEZONE_GENERIC_FIELD
18, // 'c' - UDAT_STANDALONE_DAY_FIELD (allow calendar max + 18, e.g. 49 for grego)
8, // 'L' - UDAT_STANDALONE_MONTH_FIELD (allow calendar max + 7, e.g. 19 for grego 1-based month)
-1, // 'Q' - UDAT_QUARTER_FIELD (1-4?)
-1, // 'q' - UDAT_STANDALONE_QUARTER_FIELD
-1, // 'V' - UDAT_TIMEZONE_SPECIAL_FIELD
-1, // 'U' - UDAT_YEAR_NAME_FIELD
-1, // 'O' - UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD
-1, // 'X' - UDAT_TIMEZONE_ISO_FIELD
-1, // 'x' - UDAT_TIMEZONE_ISO_LOCAL_FIELD
-1, // 'r' - UDAT_RELATED_YEAR_FIELD
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
-1, // ':' - UDAT_TIME_SEPARATOR_FIELD
#else
-1, // (no pattern character currently) - UDAT_TIME_SEPARATOR_FIELD
#endif
};
#endif // APPLE_ICU_CHANGES
// When calendar uses hebr numbering (i.e. he@calendar=hebrew),
// offset the years within the current millennium down to 1-999
static const int32_t HEBREW_CAL_CUR_MILLENIUM_START_YEAR = 5000;
static const int32_t HEBREW_CAL_CUR_MILLENIUM_END_YEAR = 6000;
/**
* Maximum range for detecting daylight offset of a time zone when parsed time zone
* string indicates it's daylight saving time, but the detected time zone does not
* observe daylight saving time at the parsed date.
*/
static const double MAX_DAYLIGHT_DETECTION_RANGE = 30*365*24*60*60*1000.0;
static UMutex LOCK;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SimpleDateFormat)
SimpleDateFormat::NSOverride::~NSOverride() {
if (snf != nullptr) {
snf->removeRef();
}
}
void SimpleDateFormat::NSOverride::free() {
NSOverride *cur = this;
while (cur) {
NSOverride *next_temp = cur->next;
delete cur;
cur = next_temp;
}
}
// no matter what the locale's default number format looked like, we want
// to modify it so that it doesn't use thousands separators, doesn't always
// show the decimal point, and recognizes integers only when parsing
static void fixNumberFormatForDates(NumberFormat &nf) {
#if APPLE_ICU_CHANGES
// rdar://
// Use new group setter equivalent to
// setGroupingUsed(false);
// setDecimalSeparatorAlwaysShown(false);
// setParseIntegerOnly(true);
// setMinimumFractionDigits(0); // To prevent "Jan 1.00, 1997.00"
nf.setDateSettings(); // Apple rdar://50064762
#else
nf.setGroupingUsed(false);
DecimalFormat* decfmt = dynamic_cast<DecimalFormat*>(&nf);
if (decfmt != nullptr) {
decfmt->setDecimalSeparatorAlwaysShown(false);
}
nf.setParseIntegerOnly(true);
nf.setMinimumFractionDigits(0); // To prevent "Jan 1.00, 1997.00"
#endif // APPLE_ICU_CHANGES
}
static const SharedNumberFormat *createSharedNumberFormat(
NumberFormat *nfToAdopt) {
fixNumberFormatForDates(*nfToAdopt);
const SharedNumberFormat *result = new SharedNumberFormat(nfToAdopt);
if (result == nullptr) {
delete nfToAdopt;
}
return result;
}
static const SharedNumberFormat *createSharedNumberFormat(
const Locale &loc, UErrorCode &status) {
NumberFormat *nf = NumberFormat::createInstance(loc, status);
if (U_FAILURE(status)) {
return nullptr;
}
const SharedNumberFormat *result = createSharedNumberFormat(nf);
if (result == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
return result;
}
static const SharedNumberFormat **allocSharedNumberFormatters() {
const SharedNumberFormat **result = (const SharedNumberFormat**)
uprv_malloc(UDAT_FIELD_COUNT * sizeof(const SharedNumberFormat*));
if (result == nullptr) {
return nullptr;
}
for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
result[i] = nullptr;
}
return result;
}
static void freeSharedNumberFormatters(const SharedNumberFormat ** list) {
for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
SharedObject::clearPtr(list[i]);
}
uprv_free(list);
}
const NumberFormat *SimpleDateFormat::getNumberFormatByIndex(
UDateFormatField index) const {
if (fSharedNumberFormatters == nullptr ||
fSharedNumberFormatters[index] == nullptr) {
return fNumberFormat;
}
return &(**fSharedNumberFormatters[index]);
}
//----------------------------------------------------------------------
SimpleDateFormat::~SimpleDateFormat()
{
delete fSymbols;
if (fSharedNumberFormatters) {
freeSharedNumberFormatters(fSharedNumberFormatters);
}
if (fTimeZoneFormat) {
delete fTimeZoneFormat;
}
delete fSimpleNumberFormatter;
#if !UCONFIG_NO_BREAK_ITERATION
delete fCapitalizationBrkIter;
#endif
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(UErrorCode& status)
: fLocale(Locale::getDefault())
{
initializeBooleanAttributes();
construct(kShort, (EStyle) (kShort + kDateOffset), fLocale, status);
initializeDefaultCentury();
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
UErrorCode &status)
: fPattern(pattern),
fLocale(Locale::getDefault())
{
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr,fLocale,status);
fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
initialize(fLocale, status);
initializeDefaultCentury();
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
const UnicodeString& override,
UErrorCode &status)
: fPattern(pattern),
fLocale(Locale::getDefault())
{
fDateOverride.setTo(override);
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr,fLocale,status);
fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
initialize(fLocale, status);
initializeDefaultCentury();
processOverrideString(fLocale,override,kOvrStrBoth,status);
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
const Locale& locale,
UErrorCode& status)
: fPattern(pattern),
fLocale(locale)
{
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr,fLocale,status);
fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
initialize(fLocale, status);
initializeDefaultCentury();
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
const UnicodeString& override,
const Locale& locale,
UErrorCode& status)
: fPattern(pattern),
fLocale(locale)
{
fDateOverride.setTo(override);
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr,fLocale,status);
fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
initialize(fLocale, status);
initializeDefaultCentury();
processOverrideString(locale,override,kOvrStrBoth,status);
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
DateFormatSymbols* symbolsToAdopt,
UErrorCode& status)
: fPattern(pattern),
fLocale(Locale::getDefault()),
fSymbols(symbolsToAdopt)
{
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr,fLocale,status);
initialize(fLocale, status);
initializeDefaultCentury();
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
const DateFormatSymbols& symbols,
UErrorCode& status)
: fPattern(pattern),
fLocale(Locale::getDefault()),
fSymbols(new DateFormatSymbols(symbols))
{
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
initializeBooleanAttributes();
initializeCalendar(nullptr, fLocale, status);
initialize(fLocale, status);
initializeDefaultCentury();
}
//----------------------------------------------------------------------
// Not for public consumption; used by DateFormat
SimpleDateFormat::SimpleDateFormat(EStyle timeStyle,
EStyle dateStyle,
const Locale& locale,
UErrorCode& status)
: fLocale(locale)
{
initializeBooleanAttributes();
construct(timeStyle, dateStyle, fLocale, status);
if(U_SUCCESS(status)) {
initializeDefaultCentury();
}
}
//----------------------------------------------------------------------
/**
* Not for public consumption; used by DateFormat. This constructor
* never fails. If the resource data is not available, it uses the
* the last resort symbols.
*/
SimpleDateFormat::SimpleDateFormat(const Locale& locale,
UErrorCode& status)
: fPattern(gDefaultPattern),
fLocale(locale)
{
if (U_FAILURE(status)) return;
initializeBooleanAttributes();
initializeCalendar(nullptr, fLocale, status);
fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
if (U_FAILURE(status))
{
status = U_ZERO_ERROR;
delete fSymbols;
// This constructor doesn't fail; it uses last resort data
fSymbols = new DateFormatSymbols(status);
/* test for nullptr */
if (fSymbols == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
initialize(fLocale, status);
if(U_SUCCESS(status)) {
initializeDefaultCentury();
}
}
//----------------------------------------------------------------------
SimpleDateFormat::SimpleDateFormat(const SimpleDateFormat& other)
: DateFormat(other),
fLocale(other.fLocale)
{
initializeBooleanAttributes();
*this = other;
}
//----------------------------------------------------------------------
SimpleDateFormat& SimpleDateFormat::operator=(const SimpleDateFormat& other)
{
if (this == &other) {
return *this;
}
// fSimpleNumberFormatter references fNumberFormatter, delete it
// before we call the = operator which may invalidate fNumberFormatter
delete fSimpleNumberFormatter;
fSimpleNumberFormatter = nullptr;
DateFormat::operator=(other);
fDateOverride = other.fDateOverride;
fTimeOverride = other.fTimeOverride;
delete fSymbols;
fSymbols = nullptr;
if (other.fSymbols)
fSymbols = new DateFormatSymbols(*other.fSymbols);
fDefaultCenturyStart = other.fDefaultCenturyStart;
fDefaultCenturyStartYear = other.fDefaultCenturyStartYear;
fHaveDefaultCentury = other.fHaveDefaultCentury;
fPattern = other.fPattern;
fHasMinute = other.fHasMinute;
fHasSecond = other.fHasSecond;
#if APPLE_ICU_CHANGES
// rdar://106782612 compatibility: format with plain spaces for specific app(s)
fUsePlainSpaces = other.fUsePlainSpaces;
#endif // APPLE_ICU_CHANGES
fLocale = other.fLocale;
// TimeZoneFormat can now be set independently via setter.
// If it is nullptr, it will be lazily initialized from locale.
delete fTimeZoneFormat;
fTimeZoneFormat = nullptr;
TimeZoneFormat *otherTZFormat;
{
// Synchronization is required here, when accessing other.fTimeZoneFormat,
// because another thread may be concurrently executing other.tzFormat(),
// a logically const function that lazily creates other.fTimeZoneFormat.
//
// Without synchronization, reordered memory writes could allow us
// to see a non-null fTimeZoneFormat before the object itself was
// fully initialized. In case of a race, it doesn't matter whether
// we see a null or a fully initialized other.fTimeZoneFormat,
// only that we avoid seeing a partially initialized object.
//
// Once initialized, no const function can modify fTimeZoneFormat,
// meaning that once we have safely grabbed the other.fTimeZoneFormat
// pointer, continued synchronization is not required to use it.
Mutex m(&LOCK);
otherTZFormat = other.fTimeZoneFormat;
}
if (otherTZFormat) {
fTimeZoneFormat = new TimeZoneFormat(*otherTZFormat);
}
#if !UCONFIG_NO_BREAK_ITERATION
if (other.fCapitalizationBrkIter != nullptr) {
fCapitalizationBrkIter = (other.fCapitalizationBrkIter)->clone();
}
#endif
if (fSharedNumberFormatters != nullptr) {
freeSharedNumberFormatters(fSharedNumberFormatters);
fSharedNumberFormatters = nullptr;
}
if (other.fSharedNumberFormatters != nullptr) {
fSharedNumberFormatters = allocSharedNumberFormatters();
if (fSharedNumberFormatters) {
for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
SharedObject::copyPtr(
other.fSharedNumberFormatters[i],
fSharedNumberFormatters[i]);
}
}
}
UErrorCode localStatus = U_ZERO_ERROR;
// SimpleNumberFormatter does not have a copy constructor. Furthermore,
// it references data from an internal field, fNumberFormatter,
// so we must rematerialize that reference after copying over the number formatter.
initSimpleNumberFormatter(localStatus);
return *this;
}
//----------------------------------------------------------------------
SimpleDateFormat*
SimpleDateFormat::clone() const
{
return new SimpleDateFormat(*this);
}
//----------------------------------------------------------------------
bool
SimpleDateFormat::operator==(const Format& other) const
{
if (DateFormat::operator==(other)) {
// The DateFormat::operator== check for fCapitalizationContext equality above
// is sufficient to check equality of all derived context-related data.
// DateFormat::operator== guarantees following cast is safe
SimpleDateFormat* that = (SimpleDateFormat*)&other;
return (fPattern == that->fPattern &&
fSymbols != nullptr && // Check for pathological object
that->fSymbols != nullptr && // Check for pathological object
*fSymbols == *that->fSymbols &&
fHaveDefaultCentury == that->fHaveDefaultCentury &&
#if APPLE_ICU_CHANGES
// rdar://
fDefaultCenturyStart == that->fDefaultCenturyStart &&
// Check fTimeZoneFormat, it can be set independently via setter
((fTimeZoneFormat == NULL && that->fTimeZoneFormat == NULL) ||
(fTimeZoneFormat != NULL && that->fTimeZoneFormat != NULL && *fTimeZoneFormat == *that->fTimeZoneFormat)) &&
// Check override strings (these also indicate any relevant
// differences in fNumberFormatters, fOverrideList)
fDateOverride == that->fDateOverride &&
fTimeOverride == that->fTimeOverride) &&
// rdar://106782612 compatibility: format with plain spaces for specific app(s)
!fUsePlainSpaces == !that->fUsePlainSpaces; // comparing negation to compare as boolean, not numeric
#else
fDefaultCenturyStart == that->fDefaultCenturyStart);
#endif // APPLE_ICU_CHANGES
}
return false;
}
//----------------------------------------------------------------------
#if !APPLE_ICU_CHANGES
// rdar://106179361
static const char16_t* timeSkeletons[4] = {
u"jmmsszzzz", // kFull
u"jmmssz", // kLong
u"jmmss", // kMedium
u"jmm", // kShort
};
#else
static const char16_t* timeSkeletons[4] = {
u"Cmmsszzzz", // kFull
u"Cmmssz", // kLong
u"Cmmss", // kMedium
u"Cmm", // kShort
};
#endif // APPLE_ICU_CHANGES
#if APPLE_ICU_CHANGES
// rdar://
enum { kBaseNameMax = ULOC_LANG_CAPACITY + ULOC_SCRIPT_CAPACITY + ULOC_COUNTRY_CAPACITY }; // includes separators and 0 term
#endif // APPLE_ICU_CHANGES
void SimpleDateFormat::construct(EStyle timeStyle,
EStyle dateStyle,
const Locale& locale,
UErrorCode& status)
{
// called by several constructors to load pattern data from the resources
if (U_FAILURE(status)) return;
// We will need the calendar to know what type of symbols to load.
initializeCalendar(nullptr, locale, status);
if (U_FAILURE(status)) return;
// Load date time patterns directly from resources.
#if APPLE_ICU_CHANGES
// rdar://26911014: If no resource bundle exists for the requested locale, we generally want to bias ourselves
// toward preserving the country (rather than the language, which is how things normally work) when retrieving certain
// date/time formatting patterns. We want to do this for date patterns, but not for time and date+time patterns
// (this might change-- see rdar://62242807 ). We use countryBundle below for these patterns. Note that
// countryBundle isn't _always_ what you get from calling ures_openWithCountryFallback() because date patterns are
// complicated and sometimes include language-based text. The openResourceBundleForDatePatterns() function in
// dtptngen_impl.h handles the exceptions and goves us either the result of ures_openWithCountryFallback() or
// ures_open() depending on the actual patterns.
// rdar://112976115 (SEED: 21A5291h/iPhone13,3: Date format incorrect with en_US@rg=dkzzzz)
// We have code in the country-fallback logic to honor the @rg subtag, but it only works under the normal
// circumstances where we do country fallback (no actual resource file, short date format, etc.). In this
// case, there _is_ a real resource file, and so the country-fallback stuff (including handling of the @rg subtag)
// doesn't get executed. The change here is to honor the @rg subtag ALL the time, so that if it leads to
// a real resource file, we just use it (en_US@rg=DKzzzz maps to en_DK, which exists). I hesitate a bit
// because I'm not really sure this is how the @rg subtag is supposed to work, but it's consistent with
// how we were already behaving on short date formats.
UErrorCode localStatus = U_ZERO_ERROR;
char correctedLocaleID[ULOC_FULLNAME_CAPACITY];
int32_t correctedIdLen = ulocimp_setRegionToSupplementalRegion(locale.getName(), correctedLocaleID, ULOC_FULLNAME_CAPACITY, &localStatus);
if (U_FAILURE(localStatus) || correctedIdLen == 0) {
uprv_strcpy(correctedLocaleID, locale.getName());
}
const char* cType = fCalendar ? fCalendar->getType() : nullptr;
UBool fallingBackByCountry = false;
LocalUResourceBundlePointer bundle(ures_open(nullptr, correctedLocaleID, &status));
LocalUResourceBundlePointer countryBundle(ures_openWithCountryFallback(nullptr, locale.getName(), &fallingBackByCountry, &status));
if (U_FAILURE(status)) return;
// If we're potentially falling back by country, check to see whether the language and country fallback locales
// have the same numbering system. If they don't, fall back by language instead. (Many date/time patterns have
// embedded assumptions about which numbering system they're being used with and don't behave well with other ones,
// especially if different writing directions are involved-- see rdar://69523017.)
if (fallingBackByCountry) {
int32_t dummy = -1;
const UChar* languageLocaleNumbers = ures_getStringByKeyWithFallback(bundle.getAlias(), "NumberElements/default", &dummy, &status);
const UChar* countryLocaleNumbers = ures_getStringByKeyWithFallback(countryBundle.getAlias(), "NumberElements/default", &dummy, &status);
if (U_FAILURE(status) || u_strcmp(languageLocaleNumbers, countryLocaleNumbers) != 0) {
fallingBackByCountry = false;
}
}
#else
const char* cType = fCalendar ? fCalendar->getType() : nullptr;
LocalUResourceBundlePointer bundle(ures_open(nullptr, locale.getBaseName(), &status));
if (U_FAILURE(status)) return;
#endif // APPLE_ICU_CHANGES
UBool cTypeIsGregorian = true;
LocalUResourceBundlePointer dateTimePatterns;
#if APPLE_ICU_CHANGES
// rdar://
LocalUResourceBundlePointer countryDateTimePatterns;
#endif // APPLE_ICU_CHANGES
if (cType != nullptr && uprv_strcmp(cType, "gregorian") != 0) {
CharString resourcePath("calendar/", status);
resourcePath.append(cType, status).append("/DateTimePatterns", status);
dateTimePatterns.adoptInstead(
ures_getByKeyWithFallback(bundle.getAlias(), resourcePath.data(),
(UResourceBundle*)nullptr, &status));
#if APPLE_ICU_CHANGES
// rdar://
countryDateTimePatterns.adoptInstead(
ures_getByKeyWithFallback(countryBundle.getAlias(), resourcePath.data(),
(UResourceBundle*)nullptr, &status));
#endif // APPLE_ICU_CHANGES
cTypeIsGregorian = false;
}
// Check for "gregorian" fallback.
if (cTypeIsGregorian || status == U_MISSING_RESOURCE_ERROR) {
status = U_ZERO_ERROR;
dateTimePatterns.adoptInstead(
ures_getByKeyWithFallback(bundle.getAlias(),
"calendar/gregorian/DateTimePatterns",
(UResourceBundle*)nullptr, &status));
#if APPLE_ICU_CHANGES
// rdar://
countryDateTimePatterns.adoptInstead(
ures_getByKeyWithFallback(countryBundle.getAlias(),
"calendar/gregorian/DateTimePatterns",
(UResourceBundle*)nullptr, &status));
#endif // APPLE_ICU_CHANGES
}
if (U_FAILURE(status)) return;
#if APPLE_ICU_CHANGES
// rdar://
#else
LocalUResourceBundlePointer currentBundle;
#endif // APPLE_ICU_CHANGES
if (ures_getSize(dateTimePatterns.getAlias()) <= kDateTime)
{
status = U_INVALID_FORMAT_ERROR;
return;
}
setLocaleIDs(ures_getLocaleByType(dateTimePatterns.getAlias(), ULOC_VALID_LOCALE, &status),
ures_getLocaleByType(dateTimePatterns.getAlias(), ULOC_ACTUAL_LOCALE, &status));
// create a symbols object from the locale
fSymbols = DateFormatSymbols::createForLocale(locale, status);
if (U_FAILURE(status)) return;
/* test for nullptr */
if (fSymbols == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
#if APPLE_ICU_CHANGES
// rdar://
const char16_t *resStr;
int32_t resStrLen;
#else
const char16_t *resStr,*ovrStr;
int32_t resStrLen,ovrStrLen = 0;
#endif // APPLE_ICU_CHANGES
fDateOverride.setToBogus();
fTimeOverride.setToBogus();
#if APPLE_ICU_CHANGES
// rdar://
#else
UnicodeString timePattern;
if (timeStyle >= kFull && timeStyle <= kShort) {
bool hasRgOrHcSubtag = false;
// also use DTPG if the locale has the "rg" or "hc" ("hours") subtag-- even if the overriding region
// or hour cycle is the same as the one we get by default, we go through the DateTimePatternGenerator
UErrorCode dummyErr1 = U_ZERO_ERROR, dummyErr2 = U_ZERO_ERROR;
if (locale.getKeywordValue("rg", nullptr, 0, dummyErr1) > 0 || locale.getKeywordValue("hours", nullptr, 0, dummyErr2) > 0) {
hasRgOrHcSubtag = true;
}
const char* baseLocID = locale.getBaseName();
if (baseLocID[0]!=0 && uprv_strcmp(baseLocID,"und")!=0) {
UErrorCode useStatus = U_ZERO_ERROR;
Locale baseLoc(baseLocID);
Locale validLoc(getLocale(ULOC_VALID_LOCALE, useStatus));
if (hasRgOrHcSubtag || (U_SUCCESS(useStatus) && validLoc!=baseLoc)) {
bool useDTPG = hasRgOrHcSubtag;
const char* baseReg = baseLoc.getCountry(); // empty string if no region
if ((baseReg[0]!=0 && uprv_strncmp(baseReg,validLoc.getCountry(),ULOC_COUNTRY_CAPACITY)!=0)
|| uprv_strncmp(baseLoc.getLanguage(),validLoc.getLanguage(),ULOC_LANG_CAPACITY)!=0) {
// use DTPG if
// * baseLoc has a region and validLoc does not have the same one (or has none), OR
// * validLoc has a different language code than baseLoc
// * the original locale has the rg or hc subtag
useDTPG = true;
}
if (useDTPG) {
// The standard time formats may have the wrong time cycle, because:
// the valid locale differs in important ways (region, language) from
// the base locale.
// We could *also* check whether they do actually have a mismatch with
// the time cycle preferences for the region, but that is a lot more
// work for little or no additional benefit, since just going ahead
// and always synthesizing the time format as per the following should
// create a locale-appropriate pattern with cycle that matches the
// region preferences anyway.
LocalPointer<DateTimePatternGenerator> dtpg(DateTimePatternGenerator::createInstanceNoStdPat(locale, useStatus));
if (U_SUCCESS(useStatus)) {
UnicodeString timeSkeleton(true, timeSkeletons[timeStyle], -1);
timePattern = dtpg->getBestPattern(timeSkeleton, useStatus);
}
}
}
}
}
#endif // APPLE_ICU_CHANGES
// if the pattern should include both date and time information, use the date/time
// pattern string as a guide to tell use how to glue together the appropriate date
// and time pattern strings.
if ((timeStyle != kNone) && (dateStyle != kNone))
{
#if APPLE_ICU_CHANGES
// rdar://
UnicodeString ovrStr;
UnicodeString tempus1 = getPatternForTimeStyle(timeStyle, locale, dateTimePatterns.getAlias(), ovrStr, status);
if (!ovrStr.isEmpty()) {
fTimeOverride = ovrStr;
}
UnicodeString tempus2 = getPatternForDateStyle(dateStyle, dateTimePatterns.getAlias(), countryDateTimePatterns.getAlias(), fallingBackByCountry, ovrStr, status);
if (!ovrStr.isEmpty()) {
fDateOverride = ovrStr;
}
#else
UnicodeString tempus1(timePattern);
if (tempus1.length() == 0) {
currentBundle.adoptInstead(
ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)timeStyle, nullptr, &status));
if (U_FAILURE(status)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
switch (ures_getType(currentBundle.getAlias())) {
case URES_STRING: {
resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
break;
}
case URES_ARRAY: {
resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
fTimeOverride.setTo(true, ovrStr, ovrStrLen);
break;
}
default: {
status = U_INVALID_FORMAT_ERROR;
return;
}
}
tempus1.setTo(true, resStr, resStrLen);
}
currentBundle.adoptInstead(
ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)dateStyle, nullptr, &status));
if (U_FAILURE(status)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
switch (ures_getType(currentBundle.getAlias())) {
case URES_STRING: {
resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
break;
}
case URES_ARRAY: {
resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
fDateOverride.setTo(true, ovrStr, ovrStrLen);
break;
}
default: {
status = U_INVALID_FORMAT_ERROR;
return;
}
}
UnicodeString tempus2(true, resStr, resStrLen);
#endif // APPLE_ICU_CHANGES
// Currently, for compatibility with pre-CLDR-42 data, we default to the "atTime"
// combining patterns. Depending on guidance in CLDR 42 spec and on DisplayOptions,
// we may change this.
LocalUResourceBundlePointer dateAtTimePatterns;
if (!cTypeIsGregorian) {
CharString resourcePath("calendar/", status);
resourcePath.append(cType, status).append("/DateTimePatterns%atTime", status);
dateAtTimePatterns.adoptInstead(
ures_getByKeyWithFallback(bundle.getAlias(), resourcePath.data(),
nullptr, &status));
}
if (cTypeIsGregorian || status == U_MISSING_RESOURCE_ERROR) {
status = U_ZERO_ERROR;
dateAtTimePatterns.adoptInstead(
ures_getByKeyWithFallback(bundle.getAlias(),
"calendar/gregorian/DateTimePatterns%atTime",
nullptr, &status));
}
if (U_SUCCESS(status) && ures_getSize(dateAtTimePatterns.getAlias()) >= 4) {
resStr = ures_getStringByIndex(dateAtTimePatterns.getAlias(), dateStyle - kDateOffset, &resStrLen, &status);
} else {
status = U_ZERO_ERROR;
int32_t glueIndex = kDateTime;
int32_t patternsSize = ures_getSize(dateTimePatterns.getAlias());
if (patternsSize >= (kDateTimeOffset + kShort + 1)) {
// Get proper date time format
glueIndex = (int32_t)(kDateTimeOffset + (dateStyle - kDateOffset));
}
resStr = ures_getStringByIndex(dateTimePatterns.getAlias(), glueIndex, &resStrLen, &status);
}
SimpleFormatter(UnicodeString(true, resStr, resStrLen), 2, 2, status).
format(tempus1, tempus2, fPattern, status);
}
// if the pattern includes just time data or just date date, load the appropriate
// pattern string from the resources
// setTo() - see DateFormatSymbols::assignArray comments
else if (timeStyle != kNone) {
#if APPLE_ICU_CHANGES
// rdar://
UnicodeString ovrStr;
UnicodeString timePattern = getPatternForTimeStyle(timeStyle, locale, dateTimePatterns.getAlias(), ovrStr, status);
if (!ovrStr.isEmpty()) {
fDateOverride = ovrStr; // is this right? This is what the original code had...
}
fPattern = timePattern;
#else
fPattern.setTo(timePattern);
if (fPattern.length() == 0) {
currentBundle.adoptInstead(
ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)timeStyle, nullptr, &status));
if (U_FAILURE(status)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
switch (ures_getType(currentBundle.getAlias())) {
case URES_STRING: {
resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
break;
}
case URES_ARRAY: {
resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
fDateOverride.setTo(true, ovrStr, ovrStrLen);
break;
}
default: {
status = U_INVALID_FORMAT_ERROR;
return;
}
}
fPattern.setTo(true, resStr, resStrLen);
}
#endif // APPLE_ICU_CHANGES
}
else if (dateStyle != kNone) {
#if APPLE_ICU_CHANGES
// rdar://
UnicodeString ovrStr;
UnicodeString datePattern = getPatternForDateStyle(dateStyle, dateTimePatterns.getAlias(), countryDateTimePatterns.getAlias(), fallingBackByCountry, ovrStr, status);
if (!ovrStr.isEmpty()) {
fDateOverride = ovrStr;
}
fPattern = datePattern;
#else
currentBundle.adoptInstead(
ures_getByIndex(dateTimePatterns.getAlias(), (int32_t)dateStyle, nullptr, &status));
if (U_FAILURE(status)) {
status = U_INVALID_FORMAT_ERROR;
return;
}
switch (ures_getType(currentBundle.getAlias())) {
case URES_STRING: {
resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
break;
}
case URES_ARRAY: {
resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
fDateOverride.setTo(true, ovrStr, ovrStrLen);
break;
}
default: {
status = U_INVALID_FORMAT_ERROR;
return;
}
}
fPattern.setTo(true, resStr, resStrLen);
#endif // APPLE_ICU_CHANGES
}
// and if it includes _neither_, that's an error
else
status = U_INVALID_FORMAT_ERROR;
// finally, finish initializing by creating a Calendar and a NumberFormat
initialize(locale, status);
}
#if APPLE_ICU_CHANGES
// rdar://
UnicodeString
SimpleDateFormat::getPatternForTimeStyle(EStyle timeStyle,
const Locale& locale,
UResourceBundle* dateTimePatterns,
UnicodeString& ovrStr,
UErrorCode& status) {
UnicodeString timePattern;
if (timeStyle >= kFull && timeStyle <= kShort) {
const char* baseLoc = NULL;
char altLocale[ULOC_FULLNAME_CAPACITY];
int32_t altLocaleLength = ulocimp_setRegionToSupplementalRegion(locale.getName(), altLocale, ULOC_FULLNAME_CAPACITY, &status);
if (U_SUCCESS(status) && altLocaleLength > 0) {
baseLoc = altLocale;
} else {
baseLoc = locale.getBaseName();
}
bool hasHcSubtag = false;
UErrorCode dummyErr = U_ZERO_ERROR;
if (locale.getKeywordValue("hours", nullptr, 0, dummyErr) > 0) {
hasHcSubtag = true;
}
if (baseLoc!=NULL && baseLoc[0]!=0 && uprv_strcmp(baseLoc,"und")!=0) {
UErrorCode useStatus = U_ZERO_ERROR;
const char* validLoc = getLocaleID(ULOC_VALID_LOCALE, useStatus);
if (hasHcSubtag || (U_SUCCESS(useStatus) && uprv_strcmp(validLoc,baseLoc)!=0)) {
bool useDTPG = hasHcSubtag;
char minLoc[kBaseNameMax];
uloc_minimizeSubtags(baseLoc, minLoc, kBaseNameMax, &useStatus);
minLoc[kBaseNameMax-1] = 0; // ensure zero term
const char* actualLoc = getLocaleID(ULOC_ACTUAL_LOCALE, useStatus);
if (U_SUCCESS(useStatus) && uprv_strcmp(actualLoc,minLoc)!=0) {
// use DTPG if
// * baseLoc and validLoc are different
// * actualLoc and the minimized version of baseLoc are different
// * the original locale has the hc subtag
useDTPG = true;
}
if (useDTPG) {
// The standard time formats may have the wrong time cycle, because:
// * the valid locale is not the same as the base locale, or
// * the actual locale the patterns are coming from is not the same
// as the minimized locale.
// We could *also* check whether they do actually have a mismatch with
// the time cycle preferences for the region, but that is a lot more
// work for little or no additional benefit, since just going ahead
// and always synthesizing the time format as per the following should
// create a locale-appropriate pattern with cycle that matches the
// region preferences anyway (for completely unsupported languages,
// this will use root patterns for the appropriate cycle for the
// likely subtags resion).
LocalPointer<DateTimePatternGenerator> dtpg(DateTimePatternGenerator::createInstance(locale, useStatus, true));
if (U_SUCCESS(useStatus)) {
UnicodeString timeSkeleton(true, timeSkeletons[timeStyle], -1);
timePattern = dtpg->getBestPattern(timeSkeleton, useStatus);
#if DEBUG_SYNTHETIC_TIMEFMTS
if (timePattern.length() != 0) {
char bbuf[32];
timePattern.extract(0,timePattern.length(),bbuf,32);
printf("\n## for locale %s, validLoc %s, minLoc %s, actualLoc %s, synth timePat %s\n", locale.getName(), validLoc, minLoc, actualLoc, bbuf);
}
#endif
}
}
}
}
}
if (timePattern.isEmpty()) {
timePattern = getPatternString((int32_t)timeStyle, dateTimePatterns, ovrStr, status);
}
return timePattern;
}
UnicodeString
SimpleDateFormat::getPatternForDateStyle(EStyle dateStyle,
UResourceBundle* languageDateTimePatterns,
UResourceBundle* countryDateTimePatterns,
UBool& fallingBackByCountry,
UnicodeString& ovrStr,
UErrorCode& status) {
UnicodeString languageOverride;
UnicodeString languagePattern = getPatternString((int32_t)dateStyle, languageDateTimePatterns, languageOverride, status);
// by default, we should fetch the pattern from the language resource
UnicodeString result = languagePattern;
ovrStr = languageOverride;
// but IF the country resource is actually different from the lanuguage resource AND the caller is asking
// for a medium or short date format AND that format in the country resource is all-numeric, return the
// pattern from the country resource instead
if (fallingBackByCountry) {
fallingBackByCountry = false;
if ((dateStyle == kDateOffset + kMedium || dateStyle == kDateOffset + kShort)) {
UnicodeString countryOverride;
UnicodeString countryPattern = getPatternString((int32_t)dateStyle, countryDateTimePatterns, countryOverride, status);
UBool stripRTLmarks = uloc_isRightToLeft(ures_getLocaleByType(countryDateTimePatterns, ULOC_ACTUAL_LOCALE, &status)) && !uloc_isRightToLeft(ures_getLocaleByType(languageDateTimePatterns, ULOC_ACTUAL_LOCALE, &status));
if (U_SUCCESS(status)) {
if (datePatternHasNumericCore(countryPattern)) {
ovrStr = countryOverride;
result = countryPattern;
fallingBackByCountry = true;
if (stripRTLmarks) {
// the date formats for RTL languages often include Unicode right-to-left marks to get the format
// to lay out correctly. If we got the pattern from a RTL locale and the requested language is
// not a RTL language, we need to strip those out (same comment below)
result.findAndReplace(UnicodeString(u'\u200f'), UnicodeString());
}
} else if (dateStyle == kDateOffset + kMedium && datePatternHasNumericCore(languagePattern)) {
// if the user asked for the MEDIUM format, it's NOT all-numeric in the country resource, but it IS
// all-numeric in the language resource, return the SHORT format from the country resource
countryPattern = getPatternString(kDateOffset + kShort, countryDateTimePatterns, countryOverride, status);
if (datePatternHasNumericCore(countryPattern)) {
ovrStr = countryOverride;
result = countryPattern;
fallingBackByCountry = true;
if (stripRTLmarks) {
result.findAndReplace(UnicodeString(u'\u200f'), UnicodeString());
}
}
}
}
}
}
return result;
}
UnicodeString
SimpleDateFormat::getPatternString(int32_t index,
UResourceBundle* dateTimePatterns,
UnicodeString& ovrStr,
UErrorCode& status) {
UnicodeString resStr;
LocalUResourceBundlePointer currentBundle(ures_getByIndex(dateTimePatterns, index, NULL, &status));
ovrStr.remove();
if (U_FAILURE(status)) {
status = U_INVALID_FORMAT_ERROR;
return resStr;
}
switch (ures_getType(currentBundle.getAlias())) {
case URES_STRING: {
resStr = ures_getUnicodeString(currentBundle.getAlias(), &status);
break;
}
case URES_ARRAY: {
resStr = ures_getUnicodeStringByIndex(currentBundle.getAlias(), 0, &status);
ovrStr = ures_getUnicodeStringByIndex(currentBundle.getAlias(), 1, &status);
break;
}
default: {
status = U_INVALID_FORMAT_ERROR;
return resStr;
}
}
return resStr;
}
#endif // APPLE_ICU_CHANGES
//----------------------------------------------------------------------
Calendar*
SimpleDateFormat::initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status)
{
if(!U_FAILURE(status)) {
fCalendar = Calendar::createInstance(
adoptZone ? adoptZone : TimeZone::forLocaleOrDefault(locale), locale, status);
}
return fCalendar;
}
void
SimpleDateFormat::initialize(const Locale& locale,
UErrorCode& status)
{
if (U_FAILURE(status)) return;
#if APPLE_ICU_CHANGES && U_PLATFORM_IS_DARWIN_BASED
// rdar://106782612&108035771 compatibility: format with plain spaces for specific app(s).
// This needs to be before the call to parsePattern(), which will do the space adjust.
fUsePlainSpaces = false;
const char* progname = getprogname();
if (progname!=nullptr && (
uprv_strncmp(progname,"Wells_Fargo_Mobile_Banking",26)==0 ||
uprv_strncmp(progname,"FioSB2",6)==0 )) { // FioSB2cz or FioSB2sk
// (Just checking the prefix of the full app name here)
// We may eventually have more programs that need this hack, in which case we
// may need to create a set of program names.
fUsePlainSpaces = true;
os_log(OS_LOG_DEFAULT, "ICU using compatibility space for date formatting");
}
#else
fUsePlainSpaces = false;
#endif // APPLE_ICU_CHANGES && U_PLATFORM_IS_DARWIN_BASED
parsePattern(); // Need this before initNumberFormatters(), to set fHasHanYearChar
#if APPLE_ICU_CHANGES
// rdar://
// If the locale has @[....]numbers=hanidays we want to *delete* that (so it
// it is not used for every field) and then set fDateOverride to "d=hanidays"
// (as with std formats for zh@calendar=chinese) to use hanidays for d field.
static const UChar hanidaysOverride[] = {0x64,0x3D,0x68,0x61,0x6E,0x69,0x64,0x61,0x79,0x73,0}; // "d=hanidays"
char numbersValue[ULOC_KEYWORDS_CAPACITY];
UErrorCode numbersStatus = U_ZERO_ERROR;
Locale localeNoHanidays(locale);
int32_t numbersLen = localeNoHanidays.getKeywordValue("numbers", numbersValue, ULOC_KEYWORDS_CAPACITY, numbersStatus);
if ( U_SUCCESS(numbersStatus) && numbersLen > 0 ) {
if ( uprv_strcmp(numbersValue, "hanidays") == 0 ) {
localeNoHanidays.setKeywordValue("numbers", NULL, numbersStatus);
fDateOverride.setTo(hanidaysOverride,-1);
}
}
#endif // APPLE_ICU_CHANGES
// Simple-minded hack to force Gannen year numbering for ja@calendar=japanese
// if format is non-numeric (includes 年) and fDateOverride is not already specified.
// Now this does get updated if applyPattern subsequently changes the pattern type.
if (fDateOverride.isBogus() && fHasHanYearChar &&
fCalendar != nullptr && uprv_strcmp(fCalendar->getType(),"japanese") == 0 &&
uprv_strcmp(fLocale.getLanguage(),"ja") == 0) {
fDateOverride.setTo(u"y=jpanyear", -1);
}
// We don't need to check that the row count is >= 1, since all 2d arrays have at
// least one row
#if APPLE_ICU_CHANGES
// rdar://
fNumberFormat = NumberFormat::createInstance(localeNoHanidays, status);
#else
fNumberFormat = NumberFormat::createInstance(locale, status);
#endif // APPLE_ICU_CHANGES
if (fNumberFormat != nullptr && U_SUCCESS(status))
{
fixNumberFormatForDates(*fNumberFormat);
//fNumberFormat->setLenient(true); // Java uses a custom DateNumberFormat to format/parse
initNumberFormatters(locale, status);
initSimpleNumberFormatter(status);
}
else if (U_SUCCESS(status))
{
status = U_MISSING_RESOURCE_ERROR;
}
}
/* Initialize the fields we use to disambiguate ambiguous years. Separate
* so we can call it from readObject().
*/
void SimpleDateFormat::initializeDefaultCentury()
{
if(fCalendar) {
fHaveDefaultCentury = fCalendar->haveDefaultCentury();
if(fHaveDefaultCentury) {
fDefaultCenturyStart = fCalendar->defaultCenturyStart();
fDefaultCenturyStartYear = fCalendar->defaultCenturyStartYear();
} else {
fDefaultCenturyStart = DBL_MIN;
fDefaultCenturyStartYear = -1;
}
}
}
/*
* Initialize the boolean attributes. Separate so we can call it from all constructors.
*/
void SimpleDateFormat::initializeBooleanAttributes()
{
UErrorCode status = U_ZERO_ERROR;
setBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, true, status);
setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, true, status);
setBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, true, status);
setBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, true, status);
}
/* Define one-century window into which to disambiguate dates using
* two-digit years. Make public in JDK 1.2.
*/
void SimpleDateFormat::parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status)
{
if(U_FAILURE(status)) {
return;
}
if(!fCalendar) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
fCalendar->setTime(startDate, status);
if(U_SUCCESS(status)) {
fHaveDefaultCentury = true;
fDefaultCenturyStart = startDate;
fDefaultCenturyStartYear = fCalendar->get(UCAL_YEAR, status);
}
}
//----------------------------------------------------------------------
UnicodeString&
SimpleDateFormat::format(Calendar& cal, UnicodeString& appendTo, FieldPosition& pos) const
{
UErrorCode status = U_ZERO_ERROR;
FieldPositionOnlyHandler handler(pos);
return _format(cal, appendTo, handler, status);
}
//----------------------------------------------------------------------
UnicodeString&
SimpleDateFormat::format(Calendar& cal, UnicodeString& appendTo,
FieldPositionIterator* posIter, UErrorCode& status) const
{
FieldPositionIteratorHandler handler(posIter, status);
return _format(cal, appendTo, handler, status);
}
//----------------------------------------------------------------------
UnicodeString&
SimpleDateFormat::_format(Calendar& cal, UnicodeString& appendTo,
FieldPositionHandler& handler, UErrorCode& status) const
{
if ( U_FAILURE(status) ) {
return appendTo;
}
Calendar* workCal = &cal;
Calendar* calClone = nullptr;
if (&cal != fCalendar && uprv_strcmp(cal.getType(), fCalendar->getType()) != 0) {
// Different calendar type
// We use the time and time zone from the input calendar, but
// do not use the input calendar for field calculation.
calClone = fCalendar->clone();
if (calClone != nullptr) {
UDate t = cal.getTime(status);
calClone->setTime(t, status);
calClone->setTimeZone(cal.getTimeZone());
workCal = calClone;
} else {
status = U_MEMORY_ALLOCATION_ERROR;
return appendTo;
}
}
UBool inQuote = false;
char16_t prevCh = 0;
int32_t count = 0;
int32_t fieldNum = 0;
UDisplayContext capitalizationContext = getContext(UDISPCTX_TYPE_CAPITALIZATION, status);
// loop through the pattern string character by character
for (int32_t i = 0; i < fPattern.length() && U_SUCCESS(status); ++i) {
char16_t ch = fPattern[i];
// Use subFormat() to format a repeated pattern character
// when a different pattern or non-pattern character is seen
if (ch != prevCh && count > 0) {
subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
prevCh, handler, *workCal, status);
count = 0;
}
if (ch == QUOTE) {
// Consecutive single quotes are a single quote literal,
// either outside of quotes or between quotes
if ((i+1) < fPattern.length() && fPattern[i+1] == QUOTE) {
appendTo += (char16_t)QUOTE;
++i;
} else {
inQuote = ! inQuote;
}
}
else if (!inQuote && isSyntaxChar(ch)) {
// ch is a date-time pattern character to be interpreted
// by subFormat(); count the number of times it is repeated
prevCh = ch;
++count;
}
else {
// Append quoted characters and unquoted non-pattern characters
appendTo += ch;
}
}
// Format the last item in the pattern, if any
if (count > 0) {
subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
prevCh, handler, *workCal, status);
}
if (calClone != nullptr) {
delete calClone;
}
return appendTo;
}
//----------------------------------------------------------------------
/* Map calendar field into calendar field level.
* the larger the level, the smaller the field unit.
* For example, UCAL_ERA level is 0, UCAL_YEAR level is 10,
* UCAL_MONTH level is 20.
* NOTE: if new fields adds in, the table needs to update.
*/
const int32_t
SimpleDateFormat::fgCalendarFieldToLevel[] =
{
/*GyM*/ 0, 10, 20,
/*wW*/ 20, 30,
/*dDEF*/ 30, 20, 30, 30,
/*ahHm*/ 40, 50, 50, 60,
/*sS*/ 70, 80,
/*z?Y*/ 0, 0, 10,
/*eug*/ 30, 10, 0,
/*A?.*/ 40, 0, 0
};
int32_t SimpleDateFormat::getLevelFromChar(char16_t ch) {
// Map date field LETTER into calendar field level.
// the larger the level, the smaller the field unit.
// NOTE: if new fields adds in, the table needs to update.
static const int32_t mapCharToLevel[] = {
-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,
// ! " # $ % & ' ( ) * + , - . /
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1,
#else
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
#endif
// @ A B C D E F G H I J K L M N O
-1, 40, -1, -1, 20, 30, 30, 0, 50, -1, -1, 50, 20, 20, -1, 0,
// P Q R S T U V W X Y Z [ \ ] ^ _
-1, 20, -1, 80, -1, 10, 0, 30, 0, 10, 0, -1, -1, -1, -1, -1,
// ` a b c d e f g h i j k l m n o
-1, 40, -1, 30, 30, 30, -1, 0, 50, -1, -1, 50, 0, 60, -1, -1,
// p q r s t u v w x y z { | } ~
-1, 20, 10, 70, -1, 10, 0, 20, 0, 10, 0, -1, -1, -1, -1, -1
};
return ch < UPRV_LENGTHOF(mapCharToLevel) ? mapCharToLevel[ch] : -1;
}
UBool SimpleDateFormat::isSyntaxChar(char16_t ch) {
static const UBool mapCharToIsSyntax[] = {
//
false, false, false, false, false, false, false, false,
//
false, false, false, false, false, false, false, false,
//
false, false, false, false, false, false, false, false,
//
false, false, false, false, false, false, false, false,
// ! " # $ % & '
false, false, false, false, false, false, false, false,
// ( ) * + , - . /
false, false, false, false, false, false, false, false,
// 0 1 2 3 4 5 6 7
false, false, false, false, false, false, false, false,
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
// 8 9 : ; < = > ?
false, false, true, false, false, false, false, false,
#else
// 8 9 : ; < = > ?
false, false, false, false, false, false, false, false,
#endif
// @ A B C D E F G
false, true, true, true, true, true, true, true,
// H I J K L M N O
true, true, true, true, true, true, true, true,
// P Q R S T U V W
true, true, true, true, true, true, true, true,
// X Y Z [ \ ] ^ _
true, true, true, false, false, false, false, false,
// ` a b c d e f g
false, true, true, true, true, true, true, true,
// h i j k l m n o
true, true, true, true, true, true, true, true,
// p q r s t u v w
true, true, true, true, true, true, true, true,
// x y z { | } ~
true, true, true, false, false, false, false, false
};
return ch < UPRV_LENGTHOF(mapCharToIsSyntax) ? mapCharToIsSyntax[ch] : false;
}
// Map index into pattern character string to Calendar field number.
const UCalendarDateFields
SimpleDateFormat::fgPatternIndexToCalendarField[] =
{
/*GyM*/ UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
/*dkH*/ UCAL_DATE, UCAL_HOUR_OF_DAY, UCAL_HOUR_OF_DAY,
/*msS*/ UCAL_MINUTE, UCAL_SECOND, UCAL_MILLISECOND,
/*EDF*/ UCAL_DAY_OF_WEEK, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK_IN_MONTH,
/*wWa*/ UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_AM_PM,
/*hKz*/ UCAL_HOUR, UCAL_HOUR, UCAL_ZONE_OFFSET,
/*Yeu*/ UCAL_YEAR_WOY, UCAL_DOW_LOCAL, UCAL_EXTENDED_YEAR,
/*gAZ*/ UCAL_JULIAN_DAY, UCAL_MILLISECONDS_IN_DAY, UCAL_ZONE_OFFSET,
/*v*/ UCAL_ZONE_OFFSET,
/*c*/ UCAL_DOW_LOCAL,
/*L*/ UCAL_MONTH,
/*Q*/ UCAL_MONTH,
/*q*/ UCAL_MONTH,
/*V*/ UCAL_ZONE_OFFSET,
/*U*/ UCAL_YEAR,
/*O*/ UCAL_ZONE_OFFSET,
/*Xx*/ UCAL_ZONE_OFFSET, UCAL_ZONE_OFFSET,
/*r*/ UCAL_EXTENDED_YEAR,
/*bB*/ UCAL_FIELD_COUNT, UCAL_FIELD_COUNT, // no mappings to calendar fields
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
/*:*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
#else
/*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
#endif
};
// Map index into pattern character string to DateFormat field number
const UDateFormatField
SimpleDateFormat::fgPatternIndexToDateFormatField[] = {
/*GyM*/ UDAT_ERA_FIELD, UDAT_YEAR_FIELD, UDAT_MONTH_FIELD,
/*dkH*/ UDAT_DATE_FIELD, UDAT_HOUR_OF_DAY1_FIELD, UDAT_HOUR_OF_DAY0_FIELD,
/*msS*/ UDAT_MINUTE_FIELD, UDAT_SECOND_FIELD, UDAT_FRACTIONAL_SECOND_FIELD,
/*EDF*/ UDAT_DAY_OF_WEEK_FIELD, UDAT_DAY_OF_YEAR_FIELD, UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
/*wWa*/ UDAT_WEEK_OF_YEAR_FIELD, UDAT_WEEK_OF_MONTH_FIELD, UDAT_AM_PM_FIELD,
/*hKz*/ UDAT_HOUR1_FIELD, UDAT_HOUR0_FIELD, UDAT_TIMEZONE_FIELD,
/*Yeu*/ UDAT_YEAR_WOY_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_EXTENDED_YEAR_FIELD,
/*gAZ*/ UDAT_JULIAN_DAY_FIELD, UDAT_MILLISECONDS_IN_DAY_FIELD, UDAT_TIMEZONE_RFC_FIELD,
/*v*/ UDAT_TIMEZONE_GENERIC_FIELD,
/*c*/ UDAT_STANDALONE_DAY_FIELD,
/*L*/ UDAT_STANDALONE_MONTH_FIELD,
/*Q*/ UDAT_QUARTER_FIELD,
/*q*/ UDAT_STANDALONE_QUARTER_FIELD,
/*V*/ UDAT_TIMEZONE_SPECIAL_FIELD,
/*U*/ UDAT_YEAR_NAME_FIELD,
/*O*/ UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD,
/*Xx*/ UDAT_TIMEZONE_ISO_FIELD, UDAT_TIMEZONE_ISO_LOCAL_FIELD,
/*r*/ UDAT_RELATED_YEAR_FIELD,
/*bB*/ UDAT_AM_PM_MIDNIGHT_NOON_FIELD, UDAT_FLEXIBLE_DAY_PERIOD_FIELD,
#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
/*:*/ UDAT_TIME_SEPARATOR_FIELD,
#else
/*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UDAT_TIME_SEPARATOR_FIELD,
#endif
};
//----------------------------------------------------------------------
/**
* Append symbols[value] to dst. Make sure the array index is not out
* of bounds.
*/
static inline void
_appendSymbol(UnicodeString& dst,
int32_t value,
const UnicodeString* symbols,
int32_t symbolsCount) {
U_ASSERT(0 <= value && value < symbolsCount);
if (0 <= value && value < symbolsCount) {
dst += symbols[value];
}
}
static inline void
_appendSymbolWithMonthPattern(UnicodeString& dst, int32_t value, const UnicodeString* symbols, int32_t symbolsCount,
const UnicodeString* monthPattern, UErrorCode& status) {
U_ASSERT(0 <= value && value < symbolsCount);
if (0 <= value && value < symbolsCount) {
if (monthPattern == nullptr) {
dst += symbols[value];
} else {
SimpleFormatter(*monthPattern, 1, 1, status).format(symbols[value], dst, status);
}
}
}
//----------------------------------------------------------------------
void
SimpleDateFormat::initSimpleNumberFormatter(UErrorCode &status) {
if (U_FAILURE(status)) {
return;
}
#if APPLE_ICU_CHANGES
// rdar://
auto* df = dynamic_cast<DecimalFormat*>(fNumberFormat);
#else
auto* df = dynamic_cast<const DecimalFormat*>(fNumberFormat);
#endif // APPLE_ICU_CHANGES
if (df == nullptr) {
return;
}
const DecimalFormatSymbols* syms = df->getDecimalFormatSymbols();
if (syms == nullptr) {
return;
}
fSimpleNumberFormatter = new number::SimpleNumberFormatter(
number::SimpleNumberFormatter::forLocaleAndSymbolsAndGroupingStrategy(
fLocale, *syms, UNUM_GROUPING_OFF, status
)
);
if (fSimpleNumberFormatter == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
}
void
SimpleDateFormat::initNumberFormatters(const Locale &locale,UErrorCode &status) {
if (U_FAILURE(status)) {
return;
}
if ( fDateOverride.isBogus() && fTimeOverride.isBogus() ) {
return;
}
umtx_lock(&LOCK);
if (fSharedNumberFormatters == nullptr) {
fSharedNumberFormatters = allocSharedNumberFormatters();
if (fSharedNumberFormatters == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
}
}
umtx_unlock(&LOCK);
if (U_FAILURE(status)) {
return;
}
processOverrideString(locale,fDateOverride,kOvrStrDate,status);
processOverrideString(locale,fTimeOverride,kOvrStrTime,status);
}
void
SimpleDateFormat::processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status) {
if (str.isBogus() || U_FAILURE(status)) {
return;
}
int32_t start = 0;
int32_t len;
UnicodeString nsName;
UnicodeString ovrField;
UBool moreToProcess = true;
NSOverride *overrideList = nullptr;
while (moreToProcess) {
int32_t delimiterPosition = str.indexOf((char16_t)ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE,start);
if (delimiterPosition == -1) {
moreToProcess = false;
len = str.length() - start;
} else {
len = delimiterPosition - start;
}
UnicodeString currentString(str,start,len);
int32_t equalSignPosition = currentString.indexOf((char16_t)ULOC_KEYWORD_ASSIGN_UNICODE,0);
if (equalSignPosition == -1) { // Simple override string such as "hebrew"
nsName.setTo(currentString);
ovrField.setToBogus();
} else { // Field specific override string such as "y=hebrew"
nsName.setTo(currentString,equalSignPosition+1);
ovrField.setTo(currentString,0,1); // We just need the first character.
}
int32_t nsNameHash = nsName.hashCode();
// See if the numbering system is in the override list, if not, then add it.
NSOverride *curr = overrideList;
const SharedNumberFormat *snf = nullptr;
UBool found = false;
while ( curr && !found ) {
if ( curr->hash == nsNameHash ) {
snf = curr->snf;
found = true;
}
curr = curr->next;
}
if (!found) {
LocalPointer<NSOverride> cur(new NSOverride);
if (!cur.isNull()) {
char kw[ULOC_KEYWORD_AND_VALUES_CAPACITY];
uprv_strcpy(kw,"numbers=");
nsName.extract(0,len,kw+8,ULOC_KEYWORD_AND_VALUES_CAPACITY-8,US_INV);
Locale ovrLoc(locale.getLanguage(),locale.getCountry(),locale.getVariant(),kw);
cur->hash = nsNameHash;
cur->next = overrideList;
SharedObject::copyPtr(
createSharedNumberFormat(ovrLoc, status), cur->snf);
if (U_FAILURE(status)) {
if (overrideList) {
overrideList->free();
}
return;
}
snf = cur->snf;
overrideList = cur.orphan();
} else {
status = U_MEMORY_ALLOCATION_ERROR;
if (overrideList) {
overrideList->free();
}
return;
}
}
// Now that we have an appropriate number formatter, fill in the appropriate spaces in the
// number formatters table.
if (ovrField.isBogus()) {
switch (type) {
case kOvrStrDate:
case kOvrStrBoth: {
for ( int8_t i=0 ; i<kDateFieldsCount; i++ ) {
SharedObject::copyPtr(snf, fSharedNumberFormatters[kDateFields[i]]);
}
if (type==kOvrStrDate) {
break;
}
U_FALLTHROUGH;
}
case kOvrStrTime : {
for ( int8_t i=0 ; i<kTimeFieldsCount; i++ ) {
SharedObject::copyPtr(snf, fSharedNumberFormatters[kTimeFields[i]]);
}
break;
}
}
} else {
// if the pattern character is unrecognized, signal an error and bail out
UDateFormatField patternCharIndex =
DateFormatSymbols::getPatternCharIndex(ovrField.charAt(0));
if (patternCharIndex == UDAT_FIELD_COUNT) {
status = U_INVALID_FORMAT_ERROR;
if (overrideList) {
overrideList->free();
}
return;
}
SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
}
start = delimiterPosition + 1;
}
if (overrideList) {
overrideList->free();
}
}
//---------------------------------------------------------------------
void
SimpleDateFormat::subFormat(UnicodeString &appendTo,
char16_t ch,
int32_t count,
UDisplayContext capitalizationContext,
int32_t fieldNum,
char16_t fieldToOutput,
FieldPositionHandler& handler,
Calendar& cal,
UErrorCode& status) const
{
if (U_FAILURE(status)) {
return;
}
// this function gets called by format() to produce the appropriate substitution
// text for an individual pattern symbol (e.g., "HH" or "yyyy")
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
const int32_t maxIntCount = 10;
int32_t beginOffset = appendTo.length();
const NumberFormat *currentNumberFormat;
DateFormatSymbols::ECapitalizationContextUsageType capContextUsageType = DateFormatSymbols::kCapContextUsageOther;
UBool isHebrewCalendar = (uprv_strcmp(cal.getType(),"hebrew") == 0);
UBool isChineseCalendar = (uprv_strcmp(cal.getType(),"chinese") == 0 || uprv_strcmp(cal.getType(),"dangi") == 0);
// if the pattern character is unrecognized, signal an error and dump out
if (patternCharIndex == UDAT_FIELD_COUNT)
{
if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
status = U_INVALID_FORMAT_ERROR;
}
return;
}
UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex];
int32_t value = 0;
// Don't get value unless it is useful
if (field < UCAL_FIELD_COUNT) {
value = (patternCharIndex != UDAT_RELATED_YEAR_FIELD)? cal.get(field, status): cal.getRelatedYear(status);
}
if (U_FAILURE(status)) {
return;
}
currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
if (currentNumberFormat == nullptr) {
status = U_INTERNAL_PROGRAM_ERROR;
return;
}
UnicodeString hebr("hebr", 4, US_INV);
switch (patternCharIndex) {
// for any "G" symbol, write out the appropriate era string
// "GGGG" is wide era name, "GGGGG" is narrow era name, anything else is abbreviated name
case UDAT_ERA_FIELD:
if (isChineseCalendar) {
zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, 9); // as in ICU4J
} else {
if (count == 5) {
_appendSymbol(appendTo, value, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageEraNarrow;
} else if (count == 4) {
_appendSymbol(appendTo, value, fSymbols->fEraNames, fSymbols->fEraNamesCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageEraWide;
} else {
_appendSymbol(appendTo, value, fSymbols->fEras, fSymbols->fErasCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageEraAbbrev;
}
}
break;
case UDAT_YEAR_NAME_FIELD:
if (fSymbols->fShortYearNames != nullptr && value <= fSymbols->fShortYearNamesCount) {
// the Calendar YEAR field runs 1 through 60 for cyclic years
_appendSymbol(appendTo, value - 1, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount);
break;
}
// else fall through to numeric year handling, do not break here
U_FALLTHROUGH;
// OLD: for "yyyy", write out the whole year; for "yy", write out the last 2 digits
// NEW: UTS#35:
//Year y yy yyy yyyy yyyyy
//AD 1 1 01 001 0001 00001
//AD 12 12 12 012 0012 00012
//AD 123 123 23 123 0123 00123
//AD 1234 1234 34 1234 1234 01234
//AD 12345 12345 45 12345 12345 12345
case UDAT_YEAR_FIELD:
case UDAT_YEAR_WOY_FIELD:
if (fDateOverride.compare(hebr)==0 && value>HEBREW_CAL_CUR_MILLENIUM_START_YEAR && value<HEBREW_CAL_CUR_MILLENIUM_END_YEAR) {
value-=HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
}
if(count == 2)
zeroPaddingNumber(currentNumberFormat, appendTo, value, 2, 2);
else
zeroPaddingNumber(currentNumberFormat, appendTo, value, count, maxIntCount);
break;
// for "MMMM"/"LLLL", write out the whole month name, for "MMM"/"LLL", write out the month
// abbreviation, for "M"/"L" or "MM"/"LL", write out the month as a number with the
// appropriate number of digits
// for "MMMMM"/"LLLLL", use the narrow form
case UDAT_MONTH_FIELD:
case UDAT_STANDALONE_MONTH_FIELD:
if ( isHebrewCalendar ) {
HebrewCalendar *hc = (HebrewCalendar*)&cal;
if (hc->isLeapYear(hc->get(UCAL_YEAR,status)) && value == 6 && count >= 3 )
value = 13; // Show alternate form for Adar II in leap years in Hebrew calendar.
if (!hc->isLeapYear(hc->get(UCAL_YEAR,status)) && value >= 6 && count < 3 )
value--; // Adjust the month number down 1 in Hebrew non-leap years, i.e. Adar is 6, not 7.
}
{
int32_t isLeapMonth = (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount)?
cal.get(UCAL_IS_LEAP_MONTH, status): 0;
// should consolidate the next section by using arrays of pointers & counts for the right symbols...
if (count == 5) {
if (patternCharIndex == UDAT_MONTH_FIELD) {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fNarrowMonths, fSymbols->fNarrowMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatNarrow]): nullptr, status);
} else {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneNarrowMonths, fSymbols->fStandaloneNarrowMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneNarrow]): nullptr, status);
}
capContextUsageType = DateFormatSymbols::kCapContextUsageMonthNarrow;
} else if (count == 4) {
if (patternCharIndex == UDAT_MONTH_FIELD) {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fMonths, fSymbols->fMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide]): nullptr, status);
capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
} else {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide]): nullptr, status);
capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
}
} else if (count == 3) {
if (patternCharIndex == UDAT_MONTH_FIELD) {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fShortMonths, fSymbols->fShortMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev]): nullptr, status);
capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
} else {
_appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev]): nullptr, status);
capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
}
} else {
UnicodeString monthNumber;
zeroPaddingNumber(currentNumberFormat,monthNumber, value + 1, count, maxIntCount);
_appendSymbolWithMonthPattern(appendTo, 0, &monthNumber, 1,
(isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric]): nullptr, status);
}
}
break;
// for "k" and "kk", write out the hour, adjusting midnight to appear as "24"
case UDAT_HOUR_OF_DAY1_FIELD:
if (value == 0)
zeroPaddingNumber(currentNumberFormat,appendTo, cal.getMaximum(UCAL_HOUR_OF_DAY) + 1, count, maxIntCount);
else
zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
break;
case UDAT_FRACTIONAL_SECOND_FIELD:
// Fractional seconds left-justify
{
int32_t minDigits = (count > 3) ? 3 : count;
if (count == 1) {
value /= 100;
} else if (count == 2) {
value /= 10;
}
zeroPaddingNumber(currentNumberFormat, appendTo, value, minDigits, maxIntCount);
if (count > 3) {
zeroPaddingNumber(currentNumberFormat, appendTo, 0, count - 3, maxIntCount);
}
}
break;
// for "ee" or "e", use local numeric day-of-the-week
// for "EEEEEE" or "eeeeee", write out the short day-of-the-week name
// for "EEEEE" or "eeeee", write out the narrow day-of-the-week name
// for "EEEE" or "eeee", write out the wide day-of-the-week name
// for "EEE" or "EE" or "E" or "eee", write out the abbreviated day-of-the-week name
case UDAT_DOW_LOCAL_FIELD:
if ( count < 3 ) {
zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
break;
}
// fall through to EEEEE-EEE handling, but for that we don't want local day-of-week,
// we want standard day-of-week, so first fix value to work for EEEEE-EEE.
value = cal.get(UCAL_DAY_OF_WEEK, status);
if (U_FAILURE(status)) {
return;
}
// fall through, do not break here
U_FALLTHROUGH;
case UDAT_DAY_OF_WEEK_FIELD:
if (count == 5) {
_appendSymbol(appendTo, value, fSymbols->fNarrowWeekdays,
fSymbols->fNarrowWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
} else if (count == 4) {
_appendSymbol(appendTo, value, fSymbols->fWeekdays,
fSymbols->fWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
} else if (count == 6) {
_appendSymbol(appendTo, value, fSymbols->fShorterWeekdays,
fSymbols->fShorterWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
} else {
_appendSymbol(appendTo, value, fSymbols->fShortWeekdays,
fSymbols->fShortWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
}
break;
// for "ccc", write out the abbreviated day-of-the-week name
// for "cccc", write out the wide day-of-the-week name
// for "ccccc", use the narrow day-of-the-week name
// for "ccccc", use the short day-of-the-week name
case UDAT_STANDALONE_DAY_FIELD:
if ( count < 3 ) {
zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, maxIntCount);
break;
}
// fall through to alpha DOW handling, but for that we don't want local day-of-week,
// we want standard day-of-week, so first fix value.
value = cal.get(UCAL_DAY_OF_WEEK, status);
if (U_FAILURE(status)) {
return;
}
if (count == 5) {
_appendSymbol(appendTo, value, fSymbols->fStandaloneNarrowWeekdays,
fSymbols->fStandaloneNarrowWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
} else if (count == 4) {
_appendSymbol(appendTo, value, fSymbols->fStandaloneWeekdays,
fSymbols->fStandaloneWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
} else if (count == 6) {
_appendSymbol(appendTo, value, fSymbols->fStandaloneShorterWeekdays,
fSymbols->fStandaloneShorterWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
} else { // count == 3
_appendSymbol(appendTo, value, fSymbols->fStandaloneShortWeekdays,
fSymbols->fStandaloneShortWeekdaysCount);
capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
}
break;
// for "a" symbol, write out the whole AM/PM string
case UDAT_AM_PM_FIELD:
if (count < 5) {
_appendSymbol(appendTo, value, fSymbols->fAmPms,
fSymbols->fAmPmsCount);
} else {
_appendSymbol(appendTo, value, fSymbols->fNarrowAmPms,
fSymbols->fNarrowAmPmsCount);
}
break;
// if we see pattern character for UDAT_TIME_SEPARATOR_FIELD (none currently defined),
// write out the time separator string. Leave support in for future definition.
case UDAT_TIME_SEPARATOR_FIELD:
{
UnicodeString separator;
appendTo += fSymbols->getTimeSeparatorString(separator);
}
break;
// for "h" and "hh", write out the hour, adjusting noon and midnight to show up
// as "12"
case UDAT_HOUR1_FIELD:
if (value == 0)
zeroPaddingNumber(currentNumberFormat,appendTo, cal.getLeastMaximum(UCAL_HOUR) + 1, count, maxIntCount);
else
zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
break;
case UDAT_TIMEZONE_FIELD: // 'z'
case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
case UDAT_TIMEZONE_ISO_FIELD: // 'X'
case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
{
char16_t zsbuf[ZONE_NAME_U16_MAX];
UnicodeString zoneString(zsbuf, 0, UPRV_LENGTHOF(zsbuf));
const TimeZone& tz = cal.getTimeZone();
UDate date = cal.getTime(status);
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
if (patternCharIndex == UDAT_TIMEZONE_FIELD) {
if (count < 4) {
// "z", "zz", "zzz"
tzfmt->format(UTZFMT_STYLE_SPECIFIC_SHORT, tz, date, zoneString);
capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
} else {
// "zzzz" or longer
tzfmt->format(UTZFMT_STYLE_SPECIFIC_LONG, tz, date, zoneString);
capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
}
}
else if (patternCharIndex == UDAT_TIMEZONE_RFC_FIELD) {
if (count < 4) {
// "Z"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
} else if (count == 5) {
// "ZZZZZ"
tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
} else {
// "ZZ", "ZZZ", "ZZZZ"
tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
}
}
else if (patternCharIndex == UDAT_TIMEZONE_GENERIC_FIELD) {
if (count == 1) {
// "v"
tzfmt->format(UTZFMT_STYLE_GENERIC_SHORT, tz, date, zoneString);
capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
} else if (count == 4) {
// "vvvv"
tzfmt->format(UTZFMT_STYLE_GENERIC_LONG, tz, date, zoneString);
capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
}
}
else if (patternCharIndex == UDAT_TIMEZONE_SPECIAL_FIELD) {
if (count == 1) {
// "V"
tzfmt->format(UTZFMT_STYLE_ZONE_ID_SHORT, tz, date, zoneString);
} else if (count == 2) {
// "VV"
tzfmt->format(UTZFMT_STYLE_ZONE_ID, tz, date, zoneString);
} else if (count == 3) {
// "VVV"
tzfmt->format(UTZFMT_STYLE_EXEMPLAR_LOCATION, tz, date, zoneString);
} else if (count == 4) {
// "VVVV"
tzfmt->format(UTZFMT_STYLE_GENERIC_LOCATION, tz, date, zoneString);
capContextUsageType = DateFormatSymbols::kCapContextUsageZoneLong;
}
}
else if (patternCharIndex == UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD) {
if (count == 1) {
// "O"
tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT_SHORT, tz, date, zoneString);
} else if (count == 4) {
// "OOOO"
tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
}
}
else if (patternCharIndex == UDAT_TIMEZONE_ISO_FIELD) {
if (count == 1) {
// "X"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_SHORT, tz, date, zoneString);
} else if (count == 2) {
// "XX"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FIXED, tz, date, zoneString);
} else if (count == 3) {
// "XXX"
tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FIXED, tz, date, zoneString);
} else if (count == 4) {
// "XXXX"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FULL, tz, date, zoneString);
} else if (count == 5) {
// "XXXXX"
tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
}
}
else if (patternCharIndex == UDAT_TIMEZONE_ISO_LOCAL_FIELD) {
if (count == 1) {
// "x"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT, tz, date, zoneString);
} else if (count == 2) {
// "xx"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED, tz, date, zoneString);
} else if (count == 3) {
// "xxx"
tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED, tz, date, zoneString);
} else if (count == 4) {
// "xxxx"
tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
} else if (count == 5) {
// "xxxxx"
tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL, tz, date, zoneString);
}
}
else {
UPRV_UNREACHABLE_EXIT;
}
}
appendTo += zoneString;
}
break;
case UDAT_QUARTER_FIELD:
if (count >= 5)
_appendSymbol(appendTo, value/3, fSymbols->fNarrowQuarters,
fSymbols->fNarrowQuartersCount);
else if (count == 4)
_appendSymbol(appendTo, value/3, fSymbols->fQuarters,
fSymbols->fQuartersCount);
else if (count == 3)
_appendSymbol(appendTo, value/3, fSymbols->fShortQuarters,
fSymbols->fShortQuartersCount);
else
zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
break;
case UDAT_STANDALONE_QUARTER_FIELD:
if (count >= 5)
_appendSymbol(appendTo, value/3, fSymbols->fStandaloneNarrowQuarters,
fSymbols->fStandaloneNarrowQuartersCount);
else if (count == 4)
_appendSymbol(appendTo, value/3, fSymbols->fStandaloneQuarters,
fSymbols->fStandaloneQuartersCount);
else if (count == 3)
_appendSymbol(appendTo, value/3, fSymbols->fStandaloneShortQuarters,
fSymbols->fStandaloneShortQuartersCount);
else
zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
break;
case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
{
const UnicodeString *toAppend = nullptr;
int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
// Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
// For ICU 57 output of "midnight" is temporarily suppressed.
// For "midnight" and "noon":
// Time, as displayed, must be exactly noon or midnight.
// This means minutes and seconds, if present, must be zero.
if ((/*hour == 0 ||*/ hour == 12) &&
(!fHasMinute || cal.get(UCAL_MINUTE, status) == 0) &&
(!fHasSecond || cal.get(UCAL_SECOND, status) == 0)) {
// Stealing am/pm value to use as our array index.
// It works out: am/midnight are both 0, pm/noon are both 1,
// 12 am is 12 midnight, and 12 pm is 12 noon.
int32_t val = cal.get(UCAL_AM_PM, status);
if (count <= 3) {
toAppend = &fSymbols->fAbbreviatedDayPeriods[val];
} else if (count == 4 || count > 5) {
toAppend = &fSymbols->fWideDayPeriods[val];
} else { // count == 5
toAppend = &fSymbols->fNarrowDayPeriods[val];
}
}
// toAppend is nullptr if time isn't exactly midnight or noon (as displayed).
// toAppend is bogus if time is midnight or noon, but no localized string exists.
// In either case, fall back to am/pm.
if (toAppend == nullptr || toAppend->isBogus()) {
// Reformat with identical arguments except ch, now changed to 'a'.
// We are passing a different fieldToOutput because we want to add
// 'b' to field position. This makes this fallback stable when
// there is a data change on locales.
subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'b', handler, cal, status);
return;
} else {
appendTo += *toAppend;
}
break;
}
case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
{
// TODO: Maybe fetch the DayperiodRules during initialization (instead of at the first
// loading of an instance) if a relevant pattern character (b or B) is used.
const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
if (U_FAILURE(status)) {
// Data doesn't conform to spec, therefore loading failed.
break;
}
if (ruleSet == nullptr) {
// Data doesn't exist for the locale we're looking for.
// Falling back to am/pm.
// We are passing a different fieldToOutput because we want to add
// 'B' to field position. This makes this fallback stable when
// there is a data change on locales.
subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
return;
}
// Get current display time.
int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
int32_t minute = 0;
if (fHasMinute) {
minute = cal.get(UCAL_MINUTE, status);
}
int32_t second = 0;
if (fHasSecond) {
second = cal.get(UCAL_SECOND, status);
}
// Determine day period.
DayPeriodRules::DayPeriod periodType;
if (hour == 0 && minute == 0 && second == 0 && ruleSet->hasMidnight()) {
periodType = DayPeriodRules::DAYPERIOD_MIDNIGHT;
} else if (hour == 12 && minute == 0 && second == 0 && ruleSet->hasNoon()) {
periodType = DayPeriodRules::DAYPERIOD_NOON;
} else {
periodType = ruleSet->getDayPeriodForHour(hour);
}
// Rule set exists, therefore periodType can't be UNKNOWN.
// Get localized string.
U_ASSERT(periodType != DayPeriodRules::DAYPERIOD_UNKNOWN);
UnicodeString *toAppend = nullptr;
int32_t index;
// Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
// For ICU 57 output of "midnight" is temporarily suppressed.
if (periodType != DayPeriodRules::DAYPERIOD_AM &&
periodType != DayPeriodRules::DAYPERIOD_PM &&
periodType != DayPeriodRules::DAYPERIOD_MIDNIGHT) {
index = (int32_t)periodType;
if (count <= 3) {
toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
} else if (count == 4 || count > 5) {
toAppend = &fSymbols->fWideDayPeriods[index];
} else { // count == 5
toAppend = &fSymbols->fNarrowDayPeriods[index];
}
}
// Fallback schedule:
// Midnight/Noon -> General Periods -> AM/PM.
// Midnight/Noon -> General Periods.
if ((toAppend == nullptr || toAppend->isBogus()) &&
(periodType == DayPeriodRules::DAYPERIOD_MIDNIGHT ||
periodType == DayPeriodRules::DAYPERIOD_NOON)) {
periodType = ruleSet->getDayPeriodForHour(hour);
index = (int32_t)periodType;
if (count <= 3) {
toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
} else if (count == 4 || count > 5) {
toAppend = &fSymbols->fWideDayPeriods[index];
} else { // count == 5
toAppend = &fSymbols->fNarrowDayPeriods[index];
}
}
// General Periods -> AM/PM.
if (periodType == DayPeriodRules::DAYPERIOD_AM ||
periodType == DayPeriodRules::DAYPERIOD_PM ||
toAppend->isBogus()) {
// We are passing a different fieldToOutput because we want to add
// 'B' to field position iterator. This makes this fallback stable when
// there is a data change on locales.
subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
return;
}
else {
appendTo += *toAppend;
}
break;
}
// all of the other pattern symbols can be formatted as simple numbers with
// appropriate zero padding
default:
zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
break;
}
#if !UCONFIG_NO_BREAK_ITERATION
// if first field, check to see whether we need to and are able to titlecase it
if (fieldNum == 0 && fCapitalizationBrkIter != nullptr && appendTo.length() > beginOffset &&
u_islower(appendTo.char32At(beginOffset))) {
UBool titlecase = false;
switch (capitalizationContext) {
case UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE:
titlecase = true;
break;
case UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU:
titlecase = fSymbols->fCapitalization[capContextUsageType][0];
break;
case UDISPCTX_CAPITALIZATION_FOR_STANDALONE:
titlecase = fSymbols->fCapitalization[capContextUsageType][1];
break;
default:
// titlecase = false;
break;
}
if (titlecase) {
BreakIterator* const mutableCapitalizationBrkIter = fCapitalizationBrkIter->clone();
UnicodeString firstField(appendTo, beginOffset);
firstField.toTitle(mutableCapitalizationBrkIter, fLocale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
appendTo.replaceBetween(beginOffset, appendTo.length(), firstField);
delete mutableCapitalizationBrkIter;
}
}
#endif
handler.addAttribute(DateFormatSymbols::getPatternCharIndex(fieldToOutput), beginOffset, appendTo.length());
}
//----------------------------------------------------------------------
void SimpleDateFormat::adoptNumberFormat(NumberFormat *formatToAdopt) {
// Null out the fast formatter, it references fNumberFormat which we're
// about to invalidate
delete fSimpleNumberFormatter;
fSimpleNumberFormatter = nullptr;
fixNumberFormatForDates(*formatToAdopt);
delete fNumberFormat;
fNumberFormat = formatToAdopt;
// We successfully set the default number format. Now delete the overrides
// (can't fail).
if (fSharedNumberFormatters) {
freeSharedNumberFormatters(fSharedNumberFormatters);
fSharedNumberFormatters = nullptr;
}
// Recompute fSimpleNumberFormatter if necessary
UErrorCode localStatus = U_ZERO_ERROR;
initSimpleNumberFormatter(localStatus);
}
void SimpleDateFormat::adoptNumberFormat(const UnicodeString& fields, NumberFormat *formatToAdopt, UErrorCode &status){
fixNumberFormatForDates(*formatToAdopt);
LocalPointer<NumberFormat> fmt(formatToAdopt);
if (U_FAILURE(status)) {
return;
}
// We must ensure fSharedNumberFormatters is allocated.
if (fSharedNumberFormatters == nullptr) {
fSharedNumberFormatters = allocSharedNumberFormatters();
if (fSharedNumberFormatters == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
const SharedNumberFormat *newFormat = createSharedNumberFormat(fmt.orphan());
if (newFormat == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
for (int i=0; i<fields.length(); i++) {
char16_t field = fields.charAt(i);
// if the pattern character is unrecognized, signal an error and bail out
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(field);
if (patternCharIndex == UDAT_FIELD_COUNT) {
status = U_INVALID_FORMAT_ERROR;
newFormat->deleteIfZeroRefCount();
return;
}
// Set the number formatter in the table
SharedObject::copyPtr(
newFormat, fSharedNumberFormatters[patternCharIndex]);
}
newFormat->deleteIfZeroRefCount();
}
const NumberFormat *
SimpleDateFormat::getNumberFormatForField(char16_t field) const {
UDateFormatField index = DateFormatSymbols::getPatternCharIndex(field);
if (index == UDAT_FIELD_COUNT) {
return nullptr;
}
return getNumberFormatByIndex(index);
}
//----------------------------------------------------------------------
void
SimpleDateFormat::zeroPaddingNumber(
const NumberFormat *currentNumberFormat,
UnicodeString &appendTo,
int32_t value, int32_t minDigits, int32_t maxDigits) const
{
if (currentNumberFormat == fNumberFormat && fSimpleNumberFormatter) {
// Can use fast path
UErrorCode localStatus = U_ZERO_ERROR;
number::SimpleNumber number = number::SimpleNumber::forInt64(value, localStatus);
number.setMinimumIntegerDigits(minDigits, localStatus);
number.truncateStart(maxDigits, localStatus);
number::FormattedNumber result = fSimpleNumberFormatter->format(std::move(number), localStatus);
if (U_FAILURE(localStatus)) {
return;
}
appendTo.append(result.toTempString(localStatus));
return;
}
// Check for RBNF (no clone necessary)
auto* rbnf = dynamic_cast<const RuleBasedNumberFormat*>(currentNumberFormat);
if (rbnf != nullptr) {
FieldPosition pos(FieldPosition::DONT_CARE);
rbnf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
return;
}
// Fall back to slow path (clone and mutate the NumberFormat)
if (currentNumberFormat != nullptr) {
FieldPosition pos(FieldPosition::DONT_CARE);
LocalPointer<NumberFormat> nf(currentNumberFormat->clone());
nf->setMinimumIntegerDigits(minDigits);
nf->setMaximumIntegerDigits(maxDigits);
nf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
}
}
//----------------------------------------------------------------------
/**
* Return true if the given format character, occurring count
* times, represents a numeric field.
*/
UBool SimpleDateFormat::isNumeric(char16_t formatChar, int32_t count) {
return DateFormatSymbols::isNumericPatternChar(formatChar, count);
}
UBool
SimpleDateFormat::isAtNumericField(const UnicodeString &pattern, int32_t patternOffset) {
if (patternOffset >= pattern.length()) {
// not at any field
return false;
}
char16_t ch = pattern.charAt(patternOffset);
UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
if (f == UDAT_FIELD_COUNT) {
// not at any field
return false;
}
int32_t i = patternOffset;
while (pattern.charAt(++i) == ch) {}
return DateFormatSymbols::isNumericField(f, i - patternOffset);
}
UBool
SimpleDateFormat::isAfterNonNumericField(const UnicodeString &pattern, int32_t patternOffset) {
if (patternOffset <= 0) {
// not after any field
return false;
}
char16_t ch = pattern.charAt(--patternOffset);
UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
if (f == UDAT_FIELD_COUNT) {
// not after any field
return false;
}
int32_t i = patternOffset;
while (pattern.charAt(--i) == ch) {}
return !DateFormatSymbols::isNumericField(f, patternOffset - i);
}
void
SimpleDateFormat::parse(const UnicodeString& text, Calendar& cal, ParsePosition& parsePos) const
{
UErrorCode status = U_ZERO_ERROR;
int32_t pos = parsePos.getIndex();
if(parsePos.getIndex() < 0) {
parsePos.setErrorIndex(0);
return;
}
int32_t start = pos;
// Hold the day period until everything else is parsed, because we need
// the hour to interpret time correctly.
int32_t dayPeriodInt = -1;
UBool ambiguousYear[] = { false };
int32_t saveHebrewMonth = -1;
int32_t count = 0;
UTimeZoneFormatTimeType tzTimeType = UTZFMT_TIME_TYPE_UNKNOWN;
// For parsing abutting numeric fields. 'abutPat' is the
// offset into 'pattern' of the first of 2 or more abutting
// numeric fields. 'abutStart' is the offset into 'text'
// where parsing the fields begins. 'abutPass' starts off as 0
// and increments each time we try to parse the fields.
int32_t abutPat = -1; // If >=0, we are in a run of abutting numeric fields
int32_t abutStart = 0;
int32_t abutPass = 0;
UBool inQuote = false;
MessageFormat * numericLeapMonthFormatter = nullptr;
Calendar* calClone = nullptr;
Calendar *workCal = &cal;
if (&cal != fCalendar && uprv_strcmp(cal.getType(), fCalendar->getType()) != 0) {
// Different calendar type
// We use the time/zone from the input calendar, but
// do not use the input calendar for field calculation.
calClone = fCalendar->clone();
if (calClone != nullptr) {
calClone->setTime(cal.getTime(status),status);
if (U_FAILURE(status)) {
goto ExitParse;
}
calClone->setTimeZone(cal.getTimeZone());
workCal = calClone;
} else {
status = U_MEMORY_ALLOCATION_ERROR;
goto ExitParse;
}
}
if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
numericLeapMonthFormatter = new MessageFormat(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric], fLocale, status);
if (numericLeapMonthFormatter == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
goto ExitParse;
} else if (U_FAILURE(status)) {
goto ExitParse; // this will delete numericLeapMonthFormatter
}
}
for (int32_t i=0; i<fPattern.length(); ++i) {
char16_t ch = fPattern.charAt(i);
// Handle alphabetic field characters.
if (!inQuote && isSyntaxChar(ch)) {
int32_t fieldPat = i;
// Count the length of this field specifier
count = 1;
while ((i+1)<fPattern.length() &&
fPattern.charAt(i+1) == ch) {
++count;
++i;
}
if (isNumeric(ch, count)) {
if (abutPat < 0) {
// Determine if there is an abutting numeric field.
// Record the start of a set of abutting numeric fields.
if (isAtNumericField(fPattern, i + 1)) {
abutPat = fieldPat;
abutStart = pos;
abutPass = 0;
}
}
} else {
abutPat = -1; // End of any abutting fields
}
// Handle fields within a run of abutting numeric fields. Take
// the pattern "HHmmss" as an example. We will try to parse
// 2/2/2 characters of the input text, then if that fails,
// 1/2/2. We only adjust the width of the leftmost field; the
// others remain fixed. This allows "123456" => 12:34:56, but
// "12345" => 1:23:45. Likewise, for the pattern "yyyyMMdd" we
// try 4/2/2, 3/2/2, 2/2/2, and finally 1/2/2.
if (abutPat >= 0) {
// If we are at the start of a run of abutting fields, then
// shorten this field in each pass. If we can't shorten
// this field any more, then the parse of this set of
// abutting numeric fields has failed.
if (fieldPat == abutPat) {
count -= abutPass++;
if (count == 0) {
status = U_PARSE_ERROR;
goto ExitParse;
}
}
pos = subParse(text, pos, ch, count,
true, false, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType);
// If the parse fails anywhere in the run, back up to the
// start of the run and retry.
if (pos < 0) {
i = abutPat - 1;
pos = abutStart;
continue;
}
}
// Handle non-numeric fields and non-abutting numeric
// fields.
else if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
int32_t s = subParse(text, pos, ch, count,
false, true, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType, &dayPeriodInt);
if (s == -pos-1) {
// era not present, in special cases allow this to continue
// from the position where the era was expected
s = pos;
if (i+1 < fPattern.length()) {
// move to next pattern character
char16_t c = fPattern.charAt(i+1);
// check for whitespace
if (PatternProps::isWhiteSpace(c)) {
i++;
// Advance over run in pattern
while ((i+1)<fPattern.length() &&
PatternProps::isWhiteSpace(fPattern.charAt(i+1))) {
++i;
}
}
}
}
else if (s <= 0) {
status = U_PARSE_ERROR;
goto ExitParse;
}
pos = s;
}
}
// Handle literal pattern characters. These are any
// quoted characters and non-alphabetic unquoted
// characters.
else {
abutPat = -1; // End of any abutting fields
if (! matchLiterals(fPattern, i, text, pos, getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status), getBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, status), isLenient())) {
status = U_PARSE_ERROR;
goto ExitParse;
}
}
}
// Special hack for trailing "." after non-numeric field.
if (text.charAt(pos) == 0x2e && getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
// only do if the last field is not numeric
if (isAfterNonNumericField(fPattern, fPattern.length())) {
pos++; // skip the extra "."
}
}
// If dayPeriod is set, use it in conjunction with hour-of-day to determine am/pm.
if (dayPeriodInt >= 0) {
DayPeriodRules::DayPeriod dayPeriod = (DayPeriodRules::DayPeriod)dayPeriodInt;
const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
if (!cal.isSet(UCAL_HOUR) && !cal.isSet(UCAL_HOUR_OF_DAY)) {
// If hour is not set, set time to the midpoint of current day period, overwriting
// minutes if it's set.
double midPoint = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
// If we can't get midPoint we do nothing.
if (U_SUCCESS(status)) {
// Truncate midPoint toward zero to get the hour.
// Any leftover means it was a half-hour.
int32_t midPointHour = (int32_t) midPoint;
int32_t midPointMinute = (midPoint - midPointHour) > 0 ? 30 : 0;
// No need to set am/pm because hour-of-day is set last therefore takes precedence.
cal.set(UCAL_HOUR_OF_DAY, midPointHour);
cal.set(UCAL_MINUTE, midPointMinute);
}
} else {
int hourOfDay;
if (cal.isSet(UCAL_HOUR_OF_DAY)) { // Hour is parsed in 24-hour format.
hourOfDay = cal.get(UCAL_HOUR_OF_DAY, status);
} else { // Hour is parsed in 12-hour format.
hourOfDay = cal.get(UCAL_HOUR, status);
// cal.get() turns 12 to 0 for 12-hour time; change 0 to 12
// so 0 unambiguously means a 24-hour time from above.
if (hourOfDay == 0) { hourOfDay = 12; }
}
U_ASSERT(0 <= hourOfDay && hourOfDay <= 23);
// If hour-of-day is 0 or 13 thru 23 then input time in unambiguously in 24-hour format.
if (hourOfDay == 0 || (13 <= hourOfDay && hourOfDay <= 23)) {
// Make hour-of-day take precedence over (hour + am/pm) by setting it again.
cal.set(UCAL_HOUR_OF_DAY, hourOfDay);
} else {
// We have a 12-hour time and need to choose between am and pm.
// Behave as if dayPeriod spanned 6 hours each way from its center point.
// This will parse correctly for consistent time + period (e.g. 10 at night) as
// well as provide a reasonable recovery for inconsistent time + period (e.g.
// 9 in the afternoon).
// Assume current time is in the AM.
// - Change 12 back to 0 for easier handling of 12am.
// - Append minutes as fractional hours because e.g. 8:15 and 8:45 could be parsed
// into different half-days if center of dayPeriod is at 14:30.
// - cal.get(MINUTE) will return 0 if MINUTE is unset, which works.
if (hourOfDay == 12) { hourOfDay = 0; }
double currentHour = hourOfDay + (cal.get(UCAL_MINUTE, status)) / 60.0;
double midPointHour = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
if (U_SUCCESS(status)) {
double hoursAheadMidPoint = currentHour - midPointHour;
// Assume current time is in the AM.
if (-6 <= hoursAheadMidPoint && hoursAheadMidPoint < 6) {
// Assumption holds; set time as such.
cal.set(UCAL_AM_PM, 0);
} else {
cal.set(UCAL_AM_PM, 1);
}
}
}
}
}
// At this point the fields of Calendar have been set. Calendar
// will fill in default values for missing fields when the time
// is computed.
parsePos.setIndex(pos);
// This part is a problem: When we call parsedDate.after, we compute the time.
// Take the date April 3 2004 at 2:30 am. When this is first set up, the year
// will be wrong if we're parsing a 2-digit year pattern. It will be 1904.
// April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day. 2:30 am
// is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
// on that day. It is therefore parsed out to fields as 3:30 am. Then we
// add 100 years, and get April 3 2004 at 3:30 am. Note that April 3 2004 is
// a Saturday, so it can have a 2:30 am -- and it should. [LIU]
/*
UDate parsedDate = calendar.getTime();
if( ambiguousYear[0] && !parsedDate.after(fDefaultCenturyStart) ) {
calendar.add(Calendar.YEAR, 100);
parsedDate = calendar.getTime();
}
*/
// Because of the above condition, save off the fields in case we need to readjust.
// The procedure we use here is not particularly efficient, but there is no other
// way to do this given the API restrictions present in Calendar. We minimize
// inefficiency by only performing this computation when it might apply, that is,
// when the two-digit year is equal to the start year, and thus might fall at the
// front or the back of the default century. This only works because we adjust
// the year correctly to start with in other cases -- see subParse().
if (ambiguousYear[0] || tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) // If this is true then the two-digit year == the default start year
{
// We need a copy of the fields, and we need to avoid triggering a call to
// complete(), which will recalculate the fields. Since we can't access
// the fields[] array in Calendar, we clone the entire object. This will
// stop working if Calendar.clone() is ever rewritten to call complete().
Calendar *copy;
if (ambiguousYear[0]) {
copy = cal.clone();
// Check for failed cloning.
if (copy == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
goto ExitParse;
}
UDate parsedDate = copy->getTime(status);
// {sfb} check internalGetDefaultCenturyStart
if (fHaveDefaultCentury && (parsedDate < fDefaultCenturyStart)) {
// We can't use add here because that does a complete() first.
cal.set(UCAL_YEAR, fDefaultCenturyStartYear + 100);
}
delete copy;
}
if (tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) {
copy = cal.clone();
// Check for failed cloning.
if (copy == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
goto ExitParse;
}
const TimeZone & tz = cal.getTimeZone();
BasicTimeZone *btz = nullptr;
if (dynamic_cast<const OlsonTimeZone *>(&tz) != nullptr
|| dynamic_cast<const SimpleTimeZone *>(&tz) != nullptr
|| dynamic_cast<const RuleBasedTimeZone *>(&tz) != nullptr
|| dynamic_cast<const VTimeZone *>(&tz) != nullptr) {
btz = (BasicTimeZone*)&tz;
}
// Get local millis
copy->set(UCAL_ZONE_OFFSET, 0);
copy->set(UCAL_DST_OFFSET, 0);
UDate localMillis = copy->getTime(status);
// Make sure parsed time zone type (Standard or Daylight)
// matches the rule used by the parsed time zone.
int32_t raw, dst;
if (btz != nullptr) {
if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
btz->getOffsetFromLocal(localMillis,
UCAL_TZ_LOCAL_STANDARD_FORMER, UCAL_TZ_LOCAL_STANDARD_LATTER, raw, dst, status);
} else {
btz->getOffsetFromLocal(localMillis,
UCAL_TZ_LOCAL_DAYLIGHT_FORMER, UCAL_TZ_LOCAL_DAYLIGHT_LATTER, raw, dst, status);
}
} else {
// No good way to resolve ambiguous time at transition,
// but following code work in most case.
tz.getOffset(localMillis, true, raw, dst, status);
}
// Now, compare the results with parsed type, either standard or daylight saving time
int32_t resolvedSavings = dst;
if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
if (dst != 0) {
// Override DST_OFFSET = 0 in the result calendar
resolvedSavings = 0;
}
} else { // tztype == TZTYPE_DST
if (dst == 0) {
if (btz != nullptr) {
// This implementation resolves daylight saving time offset
// closest rule after the given time.
UDate baseTime = localMillis + raw;
UDate time = baseTime;
UDate limit = baseTime + MAX_DAYLIGHT_DETECTION_RANGE;
TimeZoneTransition trs;
UBool trsAvail;
// Search for DST rule after the given time
while (time < limit) {
trsAvail = btz->getNextTransition(time, false, trs);
if (!trsAvail) {
break;
}
resolvedSavings = trs.getTo()->getDSTSavings();
if (resolvedSavings != 0) {
break;
}
time = trs.getTime();
}
if (resolvedSavings == 0) {
// If no DST rule after the given time was found, search for
// DST rule before.
time = baseTime;
limit = baseTime - MAX_DAYLIGHT_DETECTION_RANGE;
while (time > limit) {
trsAvail = btz->getPreviousTransition(time, true, trs);
if (!trsAvail) {
break;
}
resolvedSavings = trs.getFrom()->getDSTSavings();
if (resolvedSavings != 0) {
break;
}
time = trs.getTime() - 1;
}
if (resolvedSavings == 0) {
resolvedSavings = btz->getDSTSavings();
}
}
} else {
resolvedSavings = tz.getDSTSavings();
}
if (resolvedSavings == 0) {
// final fallback
resolvedSavings = U_MILLIS_PER_HOUR;
}
}
}
cal.set(UCAL_ZONE_OFFSET, raw);
cal.set(UCAL_DST_OFFSET, resolvedSavings);
delete copy;
}
}
ExitParse:
// Set the parsed result if local calendar is used
// instead of the input calendar
if (U_SUCCESS(status) && workCal != &cal) {
cal.setTimeZone(workCal->getTimeZone());
cal.setTime(workCal->getTime(status), status);
}
if (numericLeapMonthFormatter != nullptr) {
delete numericLeapMonthFormatter;
}
if (calClone != nullptr) {
delete calClone;
}
// If any Calendar calls failed, we pretend that we
// couldn't parse the string, when in reality this isn't quite accurate--
// we did parse it; the Calendar calls just failed.
if (U_FAILURE(status)) {
parsePos.setErrorIndex(pos);
parsePos.setIndex(start);
}
}
//----------------------------------------------------------------------
static int32_t
matchStringWithOptionalDot(const UnicodeString &text,
int32_t index,
const UnicodeString &data);
int32_t SimpleDateFormat::matchQuarterString(const UnicodeString& text,
int32_t start,
UCalendarDateFields field,
const UnicodeString* data,
int32_t dataCount,
Calendar& cal) const
{
int32_t i = 0;
int32_t count = dataCount;
// There may be multiple strings in the data[] array which begin with
// the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
// We keep track of the longest match, and return that. Note that this
// unfortunately requires us to test all array elements.
int32_t bestMatchLength = 0, bestMatch = -1;
UnicodeString bestMatchName;
for (; i < count; ++i) {
int32_t matchLength = 0;
if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
bestMatchLength = matchLength;
bestMatch = i;
}
}
if (bestMatch >= 0) {
cal.set(field, bestMatch * 3);
return start + bestMatchLength;
}
return -start;
}
int32_t SimpleDateFormat::matchDayPeriodStrings(const UnicodeString& text, int32_t start,
const UnicodeString* data, int32_t dataCount,
int32_t &dayPeriod) const
{
int32_t bestMatchLength = 0, bestMatch = -1;
for (int32_t i = 0; i < dataCount; ++i) {
int32_t matchLength = 0;
if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
bestMatchLength = matchLength;
bestMatch = i;
}
}
if (bestMatch >= 0) {
dayPeriod = bestMatch;
return start + bestMatchLength;
}
return -start;
}
//----------------------------------------------------------------------
#if APPLE_ICU_CHANGES
// rdar://
#define IS_BIDI_MARK(c) (c==0x200E || c==0x200F || c==0x061C)
#endif // APPLE_ICU_CHANGES
UBool SimpleDateFormat::matchLiterals(const UnicodeString &pattern,
int32_t &patternOffset,
const UnicodeString &text,
int32_t &textOffset,
UBool whitespaceLenient,
UBool partialMatchLenient,
UBool oldLeniency)
{
UBool inQuote = false;
UnicodeString literal;
int32_t i = patternOffset;
// scan pattern looking for contiguous literal characters
for ( ; i < pattern.length(); i += 1) {
char16_t ch = pattern.charAt(i);
if (!inQuote && isSyntaxChar(ch)) {
break;
}
if (ch == QUOTE) {
// Match a quote literal ('') inside OR outside of quotes
if ((i + 1) < pattern.length() && pattern.charAt(i + 1) == QUOTE) {
i += 1;
} else {
inQuote = !inQuote;
continue;
}
}
#if APPLE_ICU_CHANGES
// rdar://
if (!IS_BIDI_MARK(ch)) {
literal += ch;
}
#else
literal += ch;
#endif // APPLE_ICU_CHANGES
}
#if APPLE_ICU_CHANGES
// rdar://
// at this point, literal contains the pattern literal text (without bidi marks)
#else
// at this point, literal contains the literal text
#endif // APPLE_ICU_CHANGES
// and i is the index of the next non-literal pattern character.
int32_t p;
int32_t t = textOffset;
if (whitespaceLenient) {
#if APPLE_ICU_CHANGES
// rdar://
// trim leading, trailing whitespace from the pattern literal
#else
// trim leading, trailing whitespace from
// the literal text
#endif // APPLE_ICU_CHANGES
literal.trim();
#if APPLE_ICU_CHANGES
// rdar://
// ignore any leading whitespace (or bidi marks) in the text
while (t < text.length()) {
UChar ch = text.charAt(t);
if (!u_isWhitespace(ch) && !IS_BIDI_MARK(ch)) {
break;
}
t += 1;
}
#else
// ignore any leading whitespace in the text
while (t < text.length() && u_isWhitespace(text.charAt(t))) {
t += 1;
}
#endif // APPLE_ICU_CHANGES
}
#if APPLE_ICU_CHANGES
// rdar://
// Get ignorables, move up here
const UnicodeSet *ignorables = NULL;
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(pattern.charAt(i));
if (patternCharIndex != UDAT_FIELD_COUNT) {
ignorables = SimpleDateFormatStaticSets::getIgnorables(patternCharIndex);
}
#endif // APPLE_ICU_CHANGES
for (p = 0; p < literal.length() && t < text.length();) {
UBool needWhitespace = false;
#if APPLE_ICU_CHANGES
// rdar://
// Skip any whitespace at current position in pattern,
// but remember whether we found whitespace in the pattern
// (we already deleted any bidi marks in the pattern).
#endif // APPLE_ICU_CHANGES
while (p < literal.length() && PatternProps::isWhiteSpace(literal.charAt(p))) {
needWhitespace = true;
p += 1;
}
#if APPLE_ICU_CHANGES
// rdar://
// If the pattern has whitespace at this point, skip it in text as well
// (if the text does not have any, that may be an error for strict parsing)
#endif // APPLE_ICU_CHANGES
if (needWhitespace) {
#if APPLE_ICU_CHANGES
// rdar://
UBool whitespaceInText = false;
// Skip any whitespace (or bidi marks) at current position in text,
// but remember whether we found whitespace in the text at this point.
while (t < text.length()) {
UChar tch = text.charAt(t);
if (u_isUWhiteSpace(tch) || PatternProps::isWhiteSpace(tch)) {
whitespaceInText = true;
} else if (!IS_BIDI_MARK(tch)) {
break;
}
t += 1;
}
#else
int32_t tStart = t;
while (t < text.length()) {
char16_t tch = text.charAt(t);
if (!u_isUWhiteSpace(tch) && !PatternProps::isWhiteSpace(tch)) {
break;
}
t += 1;
}
#endif // APPLE_ICU_CHANGES
// TODO: should we require internal spaces
// in lenient mode? (There won't be any
// leading or trailing spaces)
#if APPLE_ICU_CHANGES
// rdar://
if (!whitespaceLenient && !whitespaceInText) {
#else
if (!whitespaceLenient && t == tStart) {
#endif // APPLE_ICU_CHANGES
// didn't find matching whitespace:
// an error in strict mode
return false;
}
// In strict mode, this run of whitespace
// may have been at the end.
if (p >= literal.length()) {
break;
}
#if APPLE_ICU_CHANGES
// rdar://
} else {
// Still need to skip any bidi marks in the text
while (t < text.length() && IS_BIDI_MARK(text.charAt(t))) {
++t;
}
#endif // APPLE_ICU_CHANGES
}
if (t >= text.length() || literal.charAt(p) != text.charAt(t)) {
// Ran out of text, or found a non-matching character:
// OK in lenient mode, an error in strict mode.
if (whitespaceLenient) {
if (t == textOffset && text.charAt(t) == 0x2e &&
isAfterNonNumericField(pattern, patternOffset)) {
// Lenient mode and the literal input text begins with a "." and
// we are after a non-numeric field: We skip the "."
++t;
continue; // Do not update p.
}
// if it is actual whitespace and we're whitespace lenient it's OK
char16_t wsc = text.charAt(t);
if(PatternProps::isWhiteSpace(wsc)) {
// Lenient mode and it's just whitespace we skip it
++t;
continue; // Do not update p.
}
}
// hack around oldleniency being a bit of a catch-all bucket and we're just adding support specifically for partial matches
#if APPLE_ICU_CHANGES
// rdar://
// This fix is for http://bugs.icu-project.org/trac/ticket/10855 and adds "&& oldLeniency"
//if(partialMatchLenient && oldLeniency) {
// However this causes problems for Apple, see rdar://20692829 regressions in Chinese date parsing
// We don't want to go back to just "if(partialMatchLenient)" as in ICU 53, that is too lenient for strict mode.
// So if the pattern character is in the separator set, we allow the text character to be in that set or be an alpha char.
if( partialMatchLenient && ( oldLeniency ||
( ignorables != NULL && ignorables->contains(literal.charAt(p)) && (ignorables->contains(text.charAt(t)) || u_isalpha(text.charAt(t))) ) )
) {
#else
if(partialMatchLenient && oldLeniency) {
#endif // APPLE_ICU_CHANGES
break;
}
return false;
}
++p;
++t;
}
// At this point if we're in strict mode we have a complete match.
// If we're in lenient mode we may have a partial match, or no
// match at all.
if (p <= 0) {
// no match. Pretend it matched a run of whitespace
// and ignorables in the text.
#if APPLE_ICU_CHANGES
// rdar://
#else
const UnicodeSet *ignorables = nullptr;
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(pattern.charAt(i));
if (patternCharIndex != UDAT_FIELD_COUNT) {
ignorables = SimpleDateFormatStaticSets::getIgnorables(patternCharIndex);
}
#endif // APPLE_ICU_CHANGES
for (t = textOffset; t < text.length(); t += 1) {
char16_t ch = text.charAt(t);
#if APPLE_ICU_CHANGES
// rdar://
if (!IS_BIDI_MARK(ch) && (ignorables == nullptr || !ignorables->contains(ch))) {
#else
if (ignorables == nullptr || !ignorables->contains(ch)) {
#endif // APPLE_ICU_CHANGES
break;
}
}
}
// if we get here, we've got a complete match.
patternOffset = i - 1;
textOffset = t;
return true;
}
//----------------------------------------------------------------------
// check both wide and abbrev months.
// Does not currently handle monthPattern.
// UCalendarDateFields field = UCAL_MONTH
int32_t SimpleDateFormat::matchAlphaMonthStrings(const UnicodeString& text,
int32_t start,
const UnicodeString* wideData,
const UnicodeString* shortData,
int32_t dataCount,
Calendar& cal) const
{
int32_t i;
int32_t bestMatchLength = 0, bestMatch = -1;
for (i = 0; i < dataCount; ++i) {
int32_t matchLen = 0;
if ((matchLen = matchStringWithOptionalDot(text, start, wideData[i])) > bestMatchLength) {
bestMatch = i;
bestMatchLength = matchLen;
}
}
for (i = 0; i < dataCount; ++i) {
int32_t matchLen = 0;
if ((matchLen = matchStringWithOptionalDot(text, start, shortData[i])) > bestMatchLength) {
bestMatch = i;
bestMatchLength = matchLen;
}
}
if (bestMatch >= 0) {
// Adjustment for Hebrew Calendar month Adar II
if (!strcmp(cal.getType(),"hebrew") && bestMatch==13) {
cal.set(UCAL_MONTH,6);
} else {
cal.set(UCAL_MONTH, bestMatch);
}
return start + bestMatchLength;
}
return -start;
}
//----------------------------------------------------------------------
int32_t SimpleDateFormat::matchString(const UnicodeString& text,
int32_t start,
UCalendarDateFields field,
const UnicodeString* data,
int32_t dataCount,
const UnicodeString* monthPattern,
Calendar& cal) const
{
int32_t i = 0;
int32_t count = dataCount;
if (field == UCAL_DAY_OF_WEEK) i = 1;
// There may be multiple strings in the data[] array which begin with
// the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
// We keep track of the longest match, and return that. Note that this
// unfortunately requires us to test all array elements.
// But this does not really work for cases such as Chuvash in which
// May is "ҫу" and August is "ҫурла"/"ҫур.", hence matchAlphaMonthStrings.
int32_t bestMatchLength = 0, bestMatch = -1;
UnicodeString bestMatchName;
int32_t isLeapMonth = 0;
for (; i < count; ++i) {
int32_t matchLen = 0;
if ((matchLen = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
bestMatch = i;
bestMatchLength = matchLen;
}
if (monthPattern != nullptr) {
UErrorCode status = U_ZERO_ERROR;
UnicodeString leapMonthName;
SimpleFormatter(*monthPattern, 1, 1, status).format(data[i], leapMonthName, status);
if (U_SUCCESS(status)) {
if ((matchLen = matchStringWithOptionalDot(text, start, leapMonthName)) > bestMatchLength) {
bestMatch = i;
bestMatchLength = matchLen;
isLeapMonth = 1;
}
}
}
}
if (bestMatch >= 0) {
if (field < UCAL_FIELD_COUNT) {
// Adjustment for Hebrew Calendar month Adar II
if (!strcmp(cal.getType(),"hebrew") && field==UCAL_MONTH && bestMatch==13) {
cal.set(field,6);
} else {
if (field == UCAL_YEAR) {
bestMatch++; // only get here for cyclic year names, which match 1-based years 1-60
}
cal.set(field, bestMatch);
}
if (monthPattern != nullptr) {
cal.set(UCAL_IS_LEAP_MONTH, isLeapMonth);
}
}
return start + bestMatchLength;
}
return -start;
}
static int32_t
matchStringWithOptionalDot(const UnicodeString &text,
int32_t index,
const UnicodeString &data) {
UErrorCode sts = U_ZERO_ERROR;
int32_t matchLenText = 0;
int32_t matchLenData = 0;
u_caseInsensitivePrefixMatch(text.getBuffer() + index, text.length() - index,
data.getBuffer(), data.length(),
0 /* default case option */,
&matchLenText, &matchLenData,
&sts);
U_ASSERT (U_SUCCESS(sts));
if (matchLenData == data.length() /* normal match */
|| (data.charAt(data.length() - 1) == 0x2e
&& matchLenData == data.length() - 1 /* match without trailing dot */)) {
return matchLenText;
}
return 0;
}
//----------------------------------------------------------------------
void
SimpleDateFormat::set2DigitYearStart(UDate d, UErrorCode& status)
{
parseAmbiguousDatesAsAfter(d, status);
}
/**
* Private member function that converts the parsed date strings into
* timeFields. Returns -start (for ParsePosition) if failed.
*/
int32_t SimpleDateFormat::subParse(const UnicodeString& text, int32_t& start, char16_t ch, int32_t count,
UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal,
int32_t patLoc, MessageFormat * numericLeapMonthFormatter, UTimeZoneFormatTimeType *tzTimeType,
int32_t *dayPeriod) const
{
Formattable number;
int32_t value = 0;
int32_t i;
int32_t ps = 0;
UErrorCode status = U_ZERO_ERROR;
ParsePosition pos(0);
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
const NumberFormat *currentNumberFormat;
UnicodeString temp;
#if APPLE_ICU_CHANGES
// rdar://
int32_t tzParseOptions = (isLenient())? UTZFMT_PARSE_OPTION_ALL_STYLES: UTZFMT_PARSE_OPTION_NONE;
#endif // APPLE_ICU_CHANGES
UBool gotNumber = false;
#if defined (U_DEBUG_CAL)
//fprintf(stderr, "%s:%d - [%c] st=%d \n", __FILE__, __LINE__, (char) ch, start);
#endif
if (patternCharIndex == UDAT_FIELD_COUNT) {
return -start;
}
currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
if (currentNumberFormat == nullptr) {
return -start;
}
UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex]; // UCAL_FIELD_COUNT if irrelevant
UnicodeString hebr("hebr", 4, US_INV);
if (numericLeapMonthFormatter != nullptr) {
numericLeapMonthFormatter->setFormats((const Format **)¤tNumberFormat, 1);
}
UBool isChineseCalendar = (uprv_strcmp(cal.getType(),"chinese") == 0 || uprv_strcmp(cal.getType(),"dangi") == 0);
// If there are any spaces here, skip over them. If we hit the end
// of the string, then fail.
for (;;) {
if (start >= text.length()) {
return -start;
}
UChar32 c = text.char32At(start);
if (!u_isUWhiteSpace(c) /*||*/ && !PatternProps::isWhiteSpace(c)) {
break;
}
start += U16_LENGTH(c);
}
pos.setIndex(start);
// We handle a few special cases here where we need to parse
// a number value. We handle further, more generic cases below. We need
// to handle some of them here because some fields require extra processing on
// the parsed value.
if (patternCharIndex == UDAT_HOUR_OF_DAY1_FIELD || // k
patternCharIndex == UDAT_HOUR_OF_DAY0_FIELD || // H
patternCharIndex == UDAT_HOUR1_FIELD || // h
patternCharIndex == UDAT_HOUR0_FIELD || // K
(patternCharIndex == UDAT_DOW_LOCAL_FIELD && count <= 2) || // e
(patternCharIndex == UDAT_STANDALONE_DAY_FIELD && count <= 2) || // c
(patternCharIndex == UDAT_MONTH_FIELD && count <= 2) || // M
(patternCharIndex == UDAT_STANDALONE_MONTH_FIELD && count <= 2) || // L
(patternCharIndex == UDAT_QUARTER_FIELD && count <= 2) || // Q
(patternCharIndex == UDAT_STANDALONE_QUARTER_FIELD && count <= 2) || // q
patternCharIndex == UDAT_YEAR_FIELD || // y
patternCharIndex == UDAT_YEAR_WOY_FIELD || // Y
patternCharIndex == UDAT_YEAR_NAME_FIELD || // U (falls back to numeric)
(patternCharIndex == UDAT_ERA_FIELD && isChineseCalendar) || // G
patternCharIndex == UDAT_FRACTIONAL_SECOND_FIELD) // S
{
int32_t parseStart = pos.getIndex();
// It would be good to unify this with the obeyCount logic below,
// but that's going to be difficult.
const UnicodeString* src;
UBool parsedNumericLeapMonth = false;
if (numericLeapMonthFormatter != nullptr && (patternCharIndex == UDAT_MONTH_FIELD || patternCharIndex == UDAT_STANDALONE_MONTH_FIELD)) {
int32_t argCount;
Formattable * args = numericLeapMonthFormatter->parse(text, pos, argCount);
if (args != nullptr && argCount == 1 && pos.getIndex() > parseStart && args[0].isNumeric()) {
parsedNumericLeapMonth = true;
number.setLong(args[0].getLong());
cal.set(UCAL_IS_LEAP_MONTH, 1);
delete[] args;
} else {
pos.setIndex(parseStart);
cal.set(UCAL_IS_LEAP_MONTH, 0);
}
}
if (!parsedNumericLeapMonth) {
if (obeyCount) {
if ((start+count) > text.length()) {
return -start;
}
text.extractBetween(0, start + count, temp);
src = &temp;
} else {
src = &text;
}
parseInt(*src, number, pos, allowNegative,currentNumberFormat);
}
int32_t txtLoc = pos.getIndex();
if (txtLoc > parseStart) {
value = number.getLong();
gotNumber = true;
// suffix processing
if (value < 0 ) {
txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, true);
if (txtLoc != pos.getIndex()) {
value *= -1;
}
}
else {
txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, false);
}
// Check the range of the value
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
int32_t bias = gFieldRangeBias[patternCharIndex];
if (bias >= 0 && (value > cal.getMaximum(field) + bias || value < cal.getMinimum(field) + bias)) {
return -start;
}
#if APPLE_ICU_CHANGES
// rdar://
} else {
int32_t bias = gFieldRangeBiasLenient[patternCharIndex];
if (bias >= 0 && (value > cal.getMaximum(field) + bias)) {
return -start;
}
#endif // APPLE_ICU_CHANGES
}
pos.setIndex(txtLoc);
}
}
// Make sure that we got a number if
// we want one, and didn't get one
// if we don't want one.
switch (patternCharIndex) {
case UDAT_HOUR_OF_DAY1_FIELD:
case UDAT_HOUR_OF_DAY0_FIELD:
case UDAT_HOUR1_FIELD:
case UDAT_HOUR0_FIELD:
// special range check for hours:
if (value < 0 || value > 24) {
return -start;
}
// fall through to gotNumber check
U_FALLTHROUGH;
case UDAT_YEAR_FIELD:
case UDAT_YEAR_WOY_FIELD:
case UDAT_FRACTIONAL_SECOND_FIELD:
// these must be a number
if (! gotNumber) {
return -start;
}
break;
default:
// we check the rest of the fields below.
break;
}
switch (patternCharIndex) {
case UDAT_ERA_FIELD:
if (isChineseCalendar) {
if (!gotNumber) {
return -start;
}
cal.set(UCAL_ERA, value);
return pos.getIndex();
}
if (count == 5) {
ps = matchString(text, start, UCAL_ERA, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount, nullptr, cal);
} else if (count == 4) {
ps = matchString(text, start, UCAL_ERA, fSymbols->fEraNames, fSymbols->fEraNamesCount, nullptr, cal);
} else {
ps = matchString(text, start, UCAL_ERA, fSymbols->fEras, fSymbols->fErasCount, nullptr, cal);
}
// check return position, if it equals -start, then matchString error
// special case the return code so we don't necessarily fail out until we
// verify no year information also
if (ps == -start)
ps--;
return ps;
case UDAT_YEAR_FIELD:
// If there are 3 or more YEAR pattern characters, this indicates
// that the year value is to be treated literally, without any
// two-digit year adjustments (e.g., from "01" to 2001). Otherwise
// we made adjustments to place the 2-digit year in the proper
// century, for parsed strings from "00" to "99". Any other string
// is treated literally: "2250", "-1", "1", "002".
if (fDateOverride.compare(hebr)==0 && value < 1000) {
value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
} else if (text.moveIndex32(start, 2) == pos.getIndex() && !isChineseCalendar
&& u_isdigit(text.char32At(start))
&& u_isdigit(text.char32At(text.moveIndex32(start, 1))))
{
// only adjust year for patterns less than 3.
if(count < 3) {
// Assume for example that the defaultCenturyStart is 6/18/1903.
// This means that two-digit years will be forced into the range
// 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
// correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
// to 1904, 1905, etc. If the year is 03, then it is 2003 if the
// other fields specify a date before 6/18, or 1903 if they specify a
// date afterwards. As a result, 03 is an ambiguous year. All other
// two-digit years are unambiguous.
if(fHaveDefaultCentury) { // check if this formatter even has a pivot year
int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
ambiguousYear[0] = (value == ambiguousTwoDigitYear);
value += (fDefaultCenturyStartYear/100)*100 +
(value < ambiguousTwoDigitYear ? 100 : 0);
}
}
}
cal.set(UCAL_YEAR, value);
// Delayed checking for adjustment of Hebrew month numbers in non-leap years.
if (saveHebrewMonth >= 0) {
HebrewCalendar *hc = (HebrewCalendar*)&cal;
if (!hc->isLeapYear(value) && saveHebrewMonth >= 6) {
cal.set(UCAL_MONTH,saveHebrewMonth);
} else {
cal.set(UCAL_MONTH,saveHebrewMonth-1);
}
saveHebrewMonth = -1;
}
return pos.getIndex();
case UDAT_YEAR_WOY_FIELD:
// Comment is the same as for UDAT_Year_FIELDs - look above
if (fDateOverride.compare(hebr)==0 && value < 1000) {
value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
} else if (text.moveIndex32(start, 2) == pos.getIndex()
&& u_isdigit(text.char32At(start))
&& u_isdigit(text.char32At(text.moveIndex32(start, 1)))
&& fHaveDefaultCentury )
{
int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
ambiguousYear[0] = (value == ambiguousTwoDigitYear);
value += (fDefaultCenturyStartYear/100)*100 +
(value < ambiguousTwoDigitYear ? 100 : 0);
}
cal.set(UCAL_YEAR_WOY, value);
return pos.getIndex();
case UDAT_YEAR_NAME_FIELD:
if (fSymbols->fShortYearNames != nullptr) {
int32_t newStart = matchString(text, start, UCAL_YEAR, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount, nullptr, cal);
if (newStart > 0) {
return newStart;
}
}
if (gotNumber && (getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC,status) || value > fSymbols->fShortYearNamesCount)) {
cal.set(UCAL_YEAR, value);
return pos.getIndex();
}
return -start;
case UDAT_MONTH_FIELD:
case UDAT_STANDALONE_MONTH_FIELD:
if (gotNumber) // i.e., M or MM.
{
// When parsing month numbers from the Hebrew Calendar, we might need to adjust the month depending on whether
// or not it was a leap year. We may or may not yet know what year it is, so might have to delay checking until
// the year is parsed.
if (!strcmp(cal.getType(),"hebrew")) {
HebrewCalendar *hc = (HebrewCalendar*)&cal;
if (cal.isSet(UCAL_YEAR)) {
UErrorCode monthStatus = U_ZERO_ERROR;
if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && value >= 6) {
cal.set(UCAL_MONTH, value);
} else {
cal.set(UCAL_MONTH, value - 1);
}
} else {
saveHebrewMonth = value;
}
} else {
// Don't want to parse the month if it is a string
// while pattern uses numeric style: M/MM, L/LL
// [We computed 'value' above.]
cal.set(UCAL_MONTH, value - 1);
}
return pos.getIndex();
} else {
// count >= 3 // i.e., MMM/MMMM, LLL/LLLL
// Want to be able to parse both short and long forms.
// Try count == 4 first:
UnicodeString * wideMonthPat = nullptr;
UnicodeString * shortMonthPat = nullptr;
if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
if (patternCharIndex==UDAT_MONTH_FIELD) {
wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide];
shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev];
} else {
wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide];
shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev];
}
}
int32_t newStart = 0;
if (patternCharIndex==UDAT_MONTH_FIELD) {
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fMonthsCount==fSymbols->fShortMonthsCount) {
// single function to check both wide and short, an experiment
newStart = matchAlphaMonthStrings(text, start, fSymbols->fMonths, fSymbols->fShortMonths, fSymbols->fMonthsCount, cal); // try MMMM,MMM
if (newStart > 0) {
return newStart;
}
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
newStart = matchString(text, start, UCAL_MONTH, fSymbols->fMonths, fSymbols->fMonthsCount, wideMonthPat, cal); // try MMMM
if (newStart > 0) {
return newStart;
}
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
newStart = matchString(text, start, UCAL_MONTH, fSymbols->fShortMonths, fSymbols->fShortMonthsCount, shortMonthPat, cal); // try MMM
}
} else {
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fStandaloneMonthsCount==fSymbols->fStandaloneShortMonthsCount) {
// single function to check both wide and short, an experiment
newStart = matchAlphaMonthStrings(text, start, fSymbols->fStandaloneMonths, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneMonthsCount, cal); // try MMMM,MMM
if (newStart > 0) {
return newStart;
}
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount, wideMonthPat, cal); // try LLLL
if (newStart > 0) {
return newStart;
}
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount, shortMonthPat, cal); // try LLL
}
}
if (newStart > 0 || !getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) // currently we do not try to parse MMMMM/LLLLL: #8860
return newStart;
// else we allowing parsing as number, below
}
break;
case UDAT_HOUR_OF_DAY1_FIELD:
// [We computed 'value' above.]
if (value == cal.getMaximum(UCAL_HOUR_OF_DAY) + 1)
value = 0;
// fall through to set field
U_FALLTHROUGH;
case UDAT_HOUR_OF_DAY0_FIELD:
cal.set(UCAL_HOUR_OF_DAY, value);
return pos.getIndex();
case UDAT_FRACTIONAL_SECOND_FIELD:
// Fractional seconds left-justify
i = countDigits(text, start, pos.getIndex());
if (i < 3) {
while (i < 3) {
value *= 10;
i++;
}
} else {
int32_t a = 1;
while (i > 3) {
a *= 10;
i--;
}
value /= a;
}
cal.set(UCAL_MILLISECOND, value);
return pos.getIndex();
case UDAT_DOW_LOCAL_FIELD:
if (gotNumber) // i.e., e or ee
{
// [We computed 'value' above.]
cal.set(UCAL_DOW_LOCAL, value);
return pos.getIndex();
}
// else for eee-eeeee fall through to handling of EEE-EEEEE
// fall through, do not break here
U_FALLTHROUGH;
case UDAT_DAY_OF_WEEK_FIELD:
{
// Want to be able to parse both short and long forms.
// Try count == 4 (EEEE) wide first:
int32_t newStart = 0;
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fWeekdays, fSymbols->fWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
// EEEE wide failed, now try EEE abbreviated
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fShortWeekdays, fSymbols->fShortWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
// EEE abbreviated failed, now try EEEEEE short
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fShorterWeekdays, fSymbols->fShorterWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
// EEEEEE short failed, now try EEEEE narrow
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fNarrowWeekdays, fSymbols->fNarrowWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status) || patternCharIndex == UDAT_DAY_OF_WEEK_FIELD)
return newStart;
// else we allowing parsing as number, below
}
break;
case UDAT_STANDALONE_DAY_FIELD:
{
if (gotNumber) // c or cc
{
// [We computed 'value' above.]
cal.set(UCAL_DOW_LOCAL, value);
return pos.getIndex();
}
// Want to be able to parse both short and long forms.
// Try count == 4 (cccc) first:
int32_t newStart = 0;
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fStandaloneWeekdays, fSymbols->fStandaloneWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fStandaloneShortWeekdays, fSymbols->fStandaloneShortWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
fSymbols->fStandaloneShorterWeekdays, fSymbols->fStandaloneShorterWeekdaysCount, nullptr, cal)) > 0)
return newStart;
}
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
return newStart;
// else we allowing parsing as number, below
}
break;
case UDAT_AM_PM_FIELD:
{
// optionally try both wide/abbrev and narrow forms
int32_t newStart = 0;
// try wide/abbrev
if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count < 5 ) {
if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fAmPms, fSymbols->fAmPmsCount, nullptr, cal)) > 0) {
return newStart;
}
}
// try narrow
if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count >= 5 ) {
if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fNarrowAmPms, fSymbols->fNarrowAmPmsCount, nullptr, cal)) > 0) {
return newStart;
}
}
// no matches for given options
return -start;
}
case UDAT_HOUR1_FIELD:
// [We computed 'value' above.]
if (value == cal.getLeastMaximum(UCAL_HOUR)+1)
value = 0;
// fall through to set field
U_FALLTHROUGH;
case UDAT_HOUR0_FIELD:
cal.set(UCAL_HOUR, value);
return pos.getIndex();
case UDAT_QUARTER_FIELD:
if (gotNumber) // i.e., Q or QQ.
{
// Don't want to parse the month if it is a string
// while pattern uses numeric style: Q or QQ.
// [We computed 'value' above.]
cal.set(UCAL_MONTH, (value - 1) * 3);
return pos.getIndex();
} else {
// count >= 3 // i.e., QQQ or QQQQ
// Want to be able to parse short, long, and narrow forms.
// Try count == 4 first:
int32_t newStart = 0;
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fQuarters, fSymbols->fQuartersCount, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fShortQuarters, fSymbols->fShortQuartersCount, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fNarrowQuarters, fSymbols->fNarrowQuartersCount, cal)) > 0)
return newStart;
}
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
return newStart;
// else we allowing parsing as number, below
if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
return -start;
}
break;
case UDAT_STANDALONE_QUARTER_FIELD:
if (gotNumber) // i.e., q or qq.
{
// Don't want to parse the month if it is a string
// while pattern uses numeric style: q or q.
// [We computed 'value' above.]
cal.set(UCAL_MONTH, (value - 1) * 3);
return pos.getIndex();
} else {
// count >= 3 // i.e., qqq or qqqq
// Want to be able to parse both short and long forms.
// Try count == 4 first:
int32_t newStart = 0;
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fStandaloneQuarters, fSymbols->fStandaloneQuartersCount, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fStandaloneShortQuarters, fSymbols->fStandaloneShortQuartersCount, cal)) > 0)
return newStart;
}
if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
fSymbols->fStandaloneNarrowQuarters, fSymbols->fStandaloneNarrowQuartersCount, cal)) > 0)
return newStart;
}
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
return newStart;
// else we allowing parsing as number, below
if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
return -start;
}
break;
case UDAT_TIMEZONE_FIELD: // 'z'
{
UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_SPECIFIC_SHORT : UTZFMT_STYLE_SPECIFIC_LONG;
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
#if APPLE_ICU_CHANGES
// rdar://
TimeZone *tz = tzfmt->parse(style, text, pos, tzParseOptions, tzTimeType);
#else
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
#endif // APPLE_ICU_CHANGES
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
break;
case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
{
UTimeZoneFormatStyle style = (count < 4) ?
UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL : ((count == 5) ? UTZFMT_STYLE_ISO_EXTENDED_FULL: UTZFMT_STYLE_LOCALIZED_GMT);
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
{
UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_GENERIC_SHORT : UTZFMT_STYLE_GENERIC_LONG;
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
#if APPLE_ICU_CHANGES
// rdar://
TimeZone *tz = tzfmt->parse(style, text, pos, tzParseOptions, tzTimeType);
#else
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
#endif // APPLE_ICU_CHANGES
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
{
UTimeZoneFormatStyle style;
switch (count) {
case 1:
style = UTZFMT_STYLE_ZONE_ID_SHORT;
break;
case 2:
style = UTZFMT_STYLE_ZONE_ID;
break;
case 3:
style = UTZFMT_STYLE_EXEMPLAR_LOCATION;
break;
default:
style = UTZFMT_STYLE_GENERIC_LOCATION;
break;
}
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
{
UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_LOCALIZED_GMT_SHORT : UTZFMT_STYLE_LOCALIZED_GMT;
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
case UDAT_TIMEZONE_ISO_FIELD: // 'X'
{
UTimeZoneFormatStyle style;
switch (count) {
case 1:
style = UTZFMT_STYLE_ISO_BASIC_SHORT;
break;
case 2:
style = UTZFMT_STYLE_ISO_BASIC_FIXED;
break;
case 3:
style = UTZFMT_STYLE_ISO_EXTENDED_FIXED;
break;
case 4:
style = UTZFMT_STYLE_ISO_BASIC_FULL;
break;
default:
style = UTZFMT_STYLE_ISO_EXTENDED_FULL;
break;
}
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
{
UTimeZoneFormatStyle style;
switch (count) {
case 1:
style = UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT;
break;
case 2:
style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED;
break;
case 3:
style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED;
break;
case 4:
style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL;
break;
default:
style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL;
break;
}
const TimeZoneFormat *tzfmt = tzFormat(status);
if (U_SUCCESS(status)) {
TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
if (tz != nullptr) {
cal.adoptTimeZone(tz);
return pos.getIndex();
}
}
return -start;
}
// currently no pattern character is defined for UDAT_TIME_SEPARATOR_FIELD
// so we should not get here. Leave support in for future definition.
case UDAT_TIME_SEPARATOR_FIELD:
{
static const char16_t def_sep = DateFormatSymbols::DEFAULT_TIME_SEPARATOR;
static const char16_t alt_sep = DateFormatSymbols::ALTERNATE_TIME_SEPARATOR;
// Try matching a time separator.
int32_t count_sep = 1;
UnicodeString data[3];
fSymbols->getTimeSeparatorString(data[0]);
// Add the default, if different from the locale.
if (data[0].compare(&def_sep, 1) != 0) {
data[count_sep++].setTo(def_sep);
}
// If lenient, add also the alternate, if different from the locale.
if (isLenient() && data[0].compare(&alt_sep, 1) != 0) {
data[count_sep++].setTo(alt_sep);
}
return matchString(text, start, UCAL_FIELD_COUNT /* => nothing to set */, data, count_sep, nullptr, cal);
}
case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
{
U_ASSERT(dayPeriod != nullptr);
int32_t ampmStart = subParse(text, start, 0x61, count,
obeyCount, allowNegative, ambiguousYear, saveHebrewMonth, cal,
patLoc, numericLeapMonthFormatter, tzTimeType);
if (ampmStart > 0) {
return ampmStart;
} else {
int32_t newStart = 0;
// Only match the first two strings from the day period strings array.
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
2, *dayPeriod)) > 0) {
return newStart;
}
}
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
2, *dayPeriod)) > 0) {
return newStart;
}
}
// count == 4, but allow other counts
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status)) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
2, *dayPeriod)) > 0) {
return newStart;
}
}
return -start;
}
}
case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
{
U_ASSERT(dayPeriod != nullptr);
int32_t newStart = 0;
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
fSymbols->fAbbreviatedDayPeriodsCount, *dayPeriod)) > 0) {
return newStart;
}
}
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
fSymbols->fNarrowDayPeriodsCount, *dayPeriod)) > 0) {
return newStart;
}
}
if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
fSymbols->fWideDayPeriodsCount, *dayPeriod)) > 0) {
return newStart;
}
}
return -start;
}
default:
// Handle "generic" fields
// this is now handled below, outside the switch block
break;
}
// Handle "generic" fields:
// switch default case now handled here (outside switch block) to allow
// parsing of some string fields as digits for lenient case
int32_t parseStart = pos.getIndex();
const UnicodeString* src;
if (obeyCount) {
if ((start+count) > text.length()) {
return -start;
}
text.extractBetween(0, start + count, temp);
src = &temp;
} else {
src = &text;
}
parseInt(*src, number, pos, allowNegative,currentNumberFormat);
if (obeyCount && !isLenient() && pos.getIndex() < start + count) {
return -start;
}
if (pos.getIndex() != parseStart) {
int32_t val = number.getLong();
// Don't need suffix processing here (as in number processing at the beginning of the function);
// the new fields being handled as numeric values (month, weekdays, quarters) should not have suffixes.
// Check the range of the value
if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) {
int32_t bias = gFieldRangeBias[patternCharIndex];
if (bias >= 0 && (val > cal.getMaximum(field) + bias || val < cal.getMinimum(field) + bias)) {
return -start;
}
#if APPLE_ICU_CHANGES
// rdar://
} else {
int32_t bias = gFieldRangeBiasLenient[patternCharIndex];
if (bias >= 0 && (value > cal.getMaximum(field) + bias)) {
return -start;
}
#endif // APPLE_ICU_CHANGES
}
// For the following, need to repeat some of the "if (gotNumber)" code above:
// UDAT_[STANDALONE_]MONTH_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_STANDALONE_DAY_FIELD,
// UDAT_[STANDALONE_]QUARTER_FIELD
switch (patternCharIndex) {
case UDAT_MONTH_FIELD:
// See notes under UDAT_MONTH_FIELD case above
if (!strcmp(cal.getType(),"hebrew")) {
HebrewCalendar *hc = (HebrewCalendar*)&cal;
if (cal.isSet(UCAL_YEAR)) {
UErrorCode monthStatus = U_ZERO_ERROR;
if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && val >= 6) {
cal.set(UCAL_MONTH, val);
} else {
cal.set(UCAL_MONTH, val - 1);
}
} else {
saveHebrewMonth = val;
}
} else {
cal.set(UCAL_MONTH, val - 1);
}
break;
case UDAT_STANDALONE_MONTH_FIELD:
cal.set(UCAL_MONTH, val - 1);
break;
case UDAT_DOW_LOCAL_FIELD:
case UDAT_STANDALONE_DAY_FIELD:
cal.set(UCAL_DOW_LOCAL, val);
break;
case UDAT_QUARTER_FIELD:
case UDAT_STANDALONE_QUARTER_FIELD:
cal.set(UCAL_MONTH, (val - 1) * 3);
break;
case UDAT_RELATED_YEAR_FIELD:
cal.setRelatedYear(val);
break;
default:
cal.set(field, val);
break;
}
return pos.getIndex();
}
return -start;
}
/**
* Parse an integer using fNumberFormat. This method is semantically
* const, but actually may modify fNumberFormat.
*/
void SimpleDateFormat::parseInt(const UnicodeString& text,
Formattable& number,
ParsePosition& pos,
UBool allowNegative,
const NumberFormat *fmt) const {
parseInt(text, number, -1, pos, allowNegative,fmt);
}
/**
* Parse an integer using fNumberFormat up to maxDigits.
*/
void SimpleDateFormat::parseInt(const UnicodeString& text,
Formattable& number,
int32_t maxDigits,
ParsePosition& pos,
UBool allowNegative,
const NumberFormat *fmt) const {
UnicodeString oldPrefix;
auto* fmtAsDF = dynamic_cast<const DecimalFormat*>(fmt);
LocalPointer<DecimalFormat> df;
if (!allowNegative && fmtAsDF != nullptr) {
df.adoptInstead(fmtAsDF->clone());
if (df.isNull()) {
// Memory allocation error
return;
}
df->setNegativePrefix(UnicodeString(true, SUPPRESS_NEGATIVE_PREFIX, -1));
fmt = df.getAlias();
}
int32_t oldPos = pos.getIndex();
fmt->parse(text, number, pos);
if (maxDigits > 0) {
// adjust the result to fit into
// the maxDigits and move the position back
int32_t nDigits = pos.getIndex() - oldPos;
if (nDigits > maxDigits) {
int32_t val = number.getLong();
nDigits -= maxDigits;
while (nDigits > 0) {
val /= 10;
nDigits--;
}
pos.setIndex(oldPos + maxDigits);
number.setLong(val);
}
}
}
int32_t SimpleDateFormat::countDigits(const UnicodeString& text, int32_t start, int32_t end) const {
int32_t numDigits = 0;
int32_t idx = start;
while (idx < end) {
UChar32 cp = text.char32At(idx);
if (u_isdigit(cp)) {
numDigits++;
}
idx += U16_LENGTH(cp);
}
return numDigits;
}
//----------------------------------------------------------------------
void SimpleDateFormat::translatePattern(const UnicodeString& originalPattern,
UnicodeString& translatedPattern,
const UnicodeString& from,
const UnicodeString& to,
UErrorCode& status)
{
// run through the pattern and convert any pattern symbols from the version
// in "from" to the corresponding character in "to". This code takes
// quoted strings into account (it doesn't try to translate them), and it signals
// an error if a particular "pattern character" doesn't appear in "from".
// Depending on the values of "from" and "to" this can convert from generic
// to localized patterns or localized to generic.
if (U_FAILURE(status)) {
return;
}
translatedPattern.remove();
UBool inQuote = false;
for (int32_t i = 0; i < originalPattern.length(); ++i) {
char16_t c = originalPattern[i];
if (inQuote) {
if (c == QUOTE) {
inQuote = false;
}
} else {
if (c == QUOTE) {
inQuote = true;
} else if (isSyntaxChar(c)) {
int32_t ci = from.indexOf(c);
if (ci == -1) {
status = U_INVALID_FORMAT_ERROR;
return;
}
c = to[ci];
}
}
translatedPattern += c;
}
if (inQuote) {
status = U_INVALID_FORMAT_ERROR;
return;
}
}
//----------------------------------------------------------------------
UnicodeString&
SimpleDateFormat::toPattern(UnicodeString& result) const
{
result = fPattern;
return result;
}
//----------------------------------------------------------------------
UnicodeString&
SimpleDateFormat::toLocalizedPattern(UnicodeString& result,
UErrorCode& status) const
{
translatePattern(fPattern, result,
UnicodeString(DateFormatSymbols::getPatternUChars()),
fSymbols->fLocalPatternChars, status);
return result;
}
//----------------------------------------------------------------------
void
SimpleDateFormat::applyPattern(const UnicodeString& pattern)
{
fPattern = pattern;
parsePattern();
// Hack to update use of Gannen year numbering for ja@calendar=japanese -
// use only if format is non-numeric (includes 年) and no other fDateOverride.
if (fCalendar != nullptr && uprv_strcmp(fCalendar->getType(),"japanese") == 0 &&
uprv_strcmp(fLocale.getLanguage(),"ja") == 0) {
if (fDateOverride==UnicodeString(u"y=jpanyear") && !fHasHanYearChar) {
// Gannen numbering is set but new pattern should not use it, unset;
// use procedure from adoptNumberFormat to clear overrides
if (fSharedNumberFormatters) {
freeSharedNumberFormatters(fSharedNumberFormatters);
fSharedNumberFormatters = nullptr;
}
fDateOverride.setToBogus(); // record status
} else if (fDateOverride.isBogus() && fHasHanYearChar) {
// No current override (=> no Gannen numbering) but new pattern needs it;
// use procedures from initNUmberFormatters / adoptNumberFormat
umtx_lock(&LOCK);
if (fSharedNumberFormatters == nullptr) {
fSharedNumberFormatters = allocSharedNumberFormatters();
}
umtx_unlock(&LOCK);
if (fSharedNumberFormatters != nullptr) {
Locale ovrLoc(fLocale.getLanguage(),fLocale.getCountry(),fLocale.getVariant(),"numbers=jpanyear");
UErrorCode status = U_ZERO_ERROR;
const SharedNumberFormat *snf = createSharedNumberFormat(ovrLoc, status);
if (U_SUCCESS(status)) {
// Now that we have an appropriate number formatter, fill in the
// appropriate slot in the number formatters table.
UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(u'y');
SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
snf->deleteIfZeroRefCount();
fDateOverride.setTo(u"y=jpanyear", -1); // record status
}
}
}
}
}
//----------------------------------------------------------------------
void
SimpleDateFormat::applyLocalizedPattern(const UnicodeString& pattern,
UErrorCode &status)
{
translatePattern(pattern, fPattern,
fSymbols->fLocalPatternChars,
UnicodeString(DateFormatSymbols::getPatternUChars()), status);
}
//----------------------------------------------------------------------
const DateFormatSymbols*
SimpleDateFormat::getDateFormatSymbols() const
{
return fSymbols;
}
//----------------------------------------------------------------------
void
SimpleDateFormat::adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols)
{
delete fSymbols;
fSymbols = newFormatSymbols;
}
//----------------------------------------------------------------------
void
SimpleDateFormat::setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols)
{
delete fSymbols;
fSymbols = new DateFormatSymbols(newFormatSymbols);
}
//----------------------------------------------------------------------
const TimeZoneFormat*
SimpleDateFormat::getTimeZoneFormat() const {
// TimeZoneFormat initialization might fail when out of memory.
// If we always initialize TimeZoneFormat instance, we can return
// such status there. For now, this implementation lazily instantiates
// a TimeZoneFormat for performance optimization reasons, but cannot
// propagate such error (probably just out of memory case) to the caller.
UErrorCode status = U_ZERO_ERROR;
return (const TimeZoneFormat*)tzFormat(status);
}
//----------------------------------------------------------------------
void
SimpleDateFormat::adoptTimeZoneFormat(TimeZoneFormat* timeZoneFormatToAdopt)
{
delete fTimeZoneFormat;
fTimeZoneFormat = timeZoneFormatToAdopt;
}
//----------------------------------------------------------------------
void
SimpleDateFormat::setTimeZoneFormat(const TimeZoneFormat& newTimeZoneFormat)
{
delete fTimeZoneFormat;
fTimeZoneFormat = new TimeZoneFormat(newTimeZoneFormat);
}
//----------------------------------------------------------------------
void SimpleDateFormat::adoptCalendar(Calendar* calendarToAdopt)
{
UErrorCode status = U_ZERO_ERROR;
Locale calLocale(fLocale);
#if APPLE_ICU_CHANGES
// rdar://
DateFormatSymbols *newSymbols = fSymbols;
if (!newSymbols || fCalendar->getType() != calendarToAdopt->getType()) {
calLocale.setKeywordValue("calendar", calendarToAdopt->getType(), status);
newSymbols = DateFormatSymbols::createForLocale(calLocale, status);
if (U_FAILURE(status)) {
delete calendarToAdopt;
return;
}
}
#else
calLocale.setKeywordValue("calendar", calendarToAdopt->getType(), status);
DateFormatSymbols *newSymbols =
DateFormatSymbols::createForLocale(calLocale, status);
if (U_FAILURE(status)) {
delete calendarToAdopt;
return;
}
#endif // APPLE_ICU_CHANGES
DateFormat::adoptCalendar(calendarToAdopt);
#if APPLE_ICU_CHANGES
// rdar://
if (fSymbols != newSymbols) {
delete fSymbols;
fSymbols = newSymbols;
}
#else
delete fSymbols;
fSymbols = newSymbols;
#endif // APPLE_ICU_CHANGES
initializeDefaultCentury(); // we need a new century (possibly)
}
//----------------------------------------------------------------------
// override the DateFormat implementation in order to
// lazily initialize fCapitalizationBrkIter
void
SimpleDateFormat::setContext(UDisplayContext value, UErrorCode& status)
{
DateFormat::setContext(value, status);
#if !UCONFIG_NO_BREAK_ITERATION
if (U_SUCCESS(status)) {
if ( fCapitalizationBrkIter == nullptr && (value==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
value==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU || value==UDISPCTX_CAPITALIZATION_FOR_STANDALONE) ) {
status = U_ZERO_ERROR;
fCapitalizationBrkIter = BreakIterator::createSentenceInstance(fLocale, status);
if (U_FAILURE(status)) {
delete fCapitalizationBrkIter;
fCapitalizationBrkIter = nullptr;
}
}
}
#endif
}
//----------------------------------------------------------------------
UBool
SimpleDateFormat::isFieldUnitIgnored(UCalendarDateFields field) const {
return isFieldUnitIgnored(fPattern, field);
}
UBool
SimpleDateFormat::isFieldUnitIgnored(const UnicodeString& pattern,
UCalendarDateFields field) {
int32_t fieldLevel = fgCalendarFieldToLevel[field];
int32_t level;
char16_t ch;
UBool inQuote = false;
char16_t prevCh = 0;
int32_t count = 0;
for (int32_t i = 0; i < pattern.length(); ++i) {
ch = pattern[i];
if (ch != prevCh && count > 0) {
level = getLevelFromChar(prevCh);
// the larger the level, the smaller the field unit.
if (fieldLevel <= level) {
return false;
}
count = 0;
}
if (ch == QUOTE) {
if ((i+1) < pattern.length() && pattern[i+1] == QUOTE) {
++i;
} else {
inQuote = ! inQuote;
}
}
else if (!inQuote && isSyntaxChar(ch)) {
prevCh = ch;
++count;
}
}
if (count > 0) {
// last item
level = getLevelFromChar(prevCh);
if (fieldLevel <= level) {
return false;
}
}
return true;
}
//----------------------------------------------------------------------
const Locale&
SimpleDateFormat::getSmpFmtLocale() const {
return fLocale;
}
//----------------------------------------------------------------------
int32_t
SimpleDateFormat::checkIntSuffix(const UnicodeString& text, int32_t start,
int32_t patLoc, UBool isNegative) const {
// local variables
UnicodeString suf;
int32_t patternMatch;
int32_t textPreMatch;
int32_t textPostMatch;
// check that we are still in range
if ( (start > text.length()) ||
(start < 0) ||
(patLoc < 0) ||
(patLoc > fPattern.length())) {
// out of range, don't advance location in text
return start;
}
// get the suffix
DecimalFormat* decfmt = dynamic_cast<DecimalFormat*>(fNumberFormat);
if (decfmt != nullptr) {
if (isNegative) {
suf = decfmt->getNegativeSuffix(suf);
}
else {
suf = decfmt->getPositiveSuffix(suf);
}
}
// check for suffix
if (suf.length() <= 0) {
return start;
}
// check suffix will be encountered in the pattern
patternMatch = compareSimpleAffix(suf,fPattern,patLoc);
// check if a suffix will be encountered in the text
textPreMatch = compareSimpleAffix(suf,text,start);
// check if a suffix was encountered in the text
textPostMatch = compareSimpleAffix(suf,text,start-suf.length());
// check for suffix match
if ((textPreMatch >= 0) && (patternMatch >= 0) && (textPreMatch == patternMatch)) {
return start;
}
else if ((textPostMatch >= 0) && (patternMatch >= 0) && (textPostMatch == patternMatch)) {
return start - suf.length();
}
// should not get here
return start;
}
//----------------------------------------------------------------------
int32_t
SimpleDateFormat::compareSimpleAffix(const UnicodeString& affix,
const UnicodeString& input,
int32_t pos) const {
int32_t start = pos;
for (int32_t i=0; i<affix.length(); ) {
UChar32 c = affix.char32At(i);
int32_t len = U16_LENGTH(c);
if (PatternProps::isWhiteSpace(c)) {
// We may have a pattern like: \u200F \u0020
// and input text like: \u200F \u0020
// Note that U+200F and U+0020 are Pattern_White_Space but only
// U+0020 is UWhiteSpace. So we have to first do a direct
// match of the run of Pattern_White_Space in the pattern,
// then match any extra characters.
UBool literalMatch = false;
while (pos < input.length() &&
input.char32At(pos) == c) {
literalMatch = true;
i += len;
pos += len;
if (i == affix.length()) {
break;
}
c = affix.char32At(i);
len = U16_LENGTH(c);
if (!PatternProps::isWhiteSpace(c)) {
break;
}
}
// Advance over run in pattern
i = skipPatternWhiteSpace(affix, i);
// Advance over run in input text
// Must see at least one white space char in input,
// unless we've already matched some characters literally.
int32_t s = pos;
pos = skipUWhiteSpace(input, pos);
if (pos == s && !literalMatch) {
return -1;
}
// If we skip UWhiteSpace in the input text, we need to skip it in the pattern.
// Otherwise, the previous lines may have skipped over text (such as U+00A0) that
// is also in the affix.
i = skipUWhiteSpace(affix, i);
} else {
if (pos < input.length() &&
input.char32At(pos) == c) {
i += len;
pos += len;
} else {
return -1;
}
}
}
return pos - start;
}
//----------------------------------------------------------------------
int32_t
SimpleDateFormat::skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const {
const char16_t* s = text.getBuffer();
return (int32_t)(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s);
}
//----------------------------------------------------------------------
int32_t
SimpleDateFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) const {
while (pos < text.length()) {
UChar32 c = text.char32At(pos);
if (!u_isUWhiteSpace(c)) {
break;
}
pos += U16_LENGTH(c);
}
return pos;
}
//----------------------------------------------------------------------
// Lazy TimeZoneFormat instantiation, semantically const.
TimeZoneFormat *
SimpleDateFormat::tzFormat(UErrorCode &status) const {
Mutex m(&LOCK);
if (fTimeZoneFormat == nullptr && U_SUCCESS(status)) {
const_cast<SimpleDateFormat *>(this)->fTimeZoneFormat =
TimeZoneFormat::createInstance(fLocale, status);
}
return fTimeZoneFormat;
}
void SimpleDateFormat::parsePattern() {
fHasMinute = false;
fHasSecond = false;
fHasHanYearChar = false;
int len = fPattern.length();
UBool inQuote = false;
for (int32_t i = 0; i < len; ++i) {
char16_t ch = fPattern[i];
if (ch == QUOTE) {
inQuote = !inQuote;
}
if (ch == 0x5E74) { // don't care whether this is inside quotes
fHasHanYearChar = true;
}
if (!inQuote) {
if (ch == 0x6D) { // 0x6D == 'm'
fHasMinute = true;
}
if (ch == 0x73) { // 0x73 == 's'
fHasSecond = true;
}
}
#if APPLE_ICU_CHANGES
// rdar://106782612 compatibility: format with plain spaces for specific app(s).
// Note that parsePattern() is called by both initialize and applyPattern so we can
// do all of the space adjustment here.
if (ch == 0x202F && fUsePlainSpaces) { // NNBSP
// currently we only map NNBSP to plain space.
fPattern.setCharAt(i, 0x0020); // plain space
}
#endif // APPLE_ICU_CHANGES
}
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
//eof
|