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
|
/*
*******************************************************************************
* Copyright (C) 1997-2011, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* File DECIMFMT.CPP
*
* Modification History:
*
* Date Name Description
* 02/19/97 aliu Converted from java.
* 03/20/97 clhuang Implemented with new APIs.
* 03/31/97 aliu Moved isLONG_MIN to DigitList, and fixed it.
* 04/3/97 aliu Rewrote parsing and formatting completely, and
* cleaned up and debugged. Actually works now.
* Implemented NAN and INF handling, for both parsing
* and formatting. Extensive testing & debugging.
* 04/10/97 aliu Modified to compile on AIX.
* 04/16/97 aliu Rewrote to use DigitList, which has been resurrected.
* Changed DigitCount to int per code review.
* 07/09/97 helena Made ParsePosition into a class.
* 08/26/97 aliu Extensive changes to applyPattern; completely
* rewritten from the Java.
* 09/09/97 aliu Ported over support for exponential formats.
* 07/20/98 stephen JDK 1.2 sync up.
* Various instances of '0' replaced with 'NULL'
* Check for grouping size in subFormat()
* Brought subParse() in line with Java 1.2
* Added method appendAffix()
* 08/24/1998 srl Removed Mutex calls. This is not a thread safe class!
* 02/22/99 stephen Removed character literals for EBCDIC safety
* 06/24/99 helena Integrated Alan's NF enhancements and Java2 bug fixes
* 06/28/99 stephen Fixed bugs in toPattern().
* 06/29/99 stephen Fixed operator= to copy fFormatWidth, fPad,
* fPadPosition
********************************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "fphdlimp.h"
#include "unicode/decimfmt.h"
#include "unicode/choicfmt.h"
#include "unicode/ucurr.h"
#include "unicode/ustring.h"
#include "unicode/dcfmtsym.h"
#include "unicode/ures.h"
#include "unicode/uchar.h"
#include "unicode/uniset.h"
#include "unicode/curramt.h"
#include "unicode/currpinf.h"
#include "unicode/plurrule.h"
#include "uresimp.h"
#include "ucurrimp.h"
#include "charstr.h"
#include "cmemory.h"
#include "patternprops.h"
#include "digitlst.h"
#include "cstring.h"
#include "umutex.h"
#include "uassert.h"
#include "putilimp.h"
#include <math.h>
#include "hash.h"
#include "decfmtst.h"
U_NAMESPACE_BEGIN
/* For currency parsing purose,
* Need to remember all prefix patterns and suffix patterns of
* every currency format pattern,
* including the pattern of default currecny style
* and plural currency style. And the patterns are set through applyPattern.
*/
struct AffixPatternsForCurrency : public UMemory {
// negative prefix pattern
UnicodeString negPrefixPatternForCurrency;
// negative suffix pattern
UnicodeString negSuffixPatternForCurrency;
// positive prefix pattern
UnicodeString posPrefixPatternForCurrency;
// positive suffix pattern
UnicodeString posSuffixPatternForCurrency;
int8_t patternType;
AffixPatternsForCurrency(const UnicodeString& negPrefix,
const UnicodeString& negSuffix,
const UnicodeString& posPrefix,
const UnicodeString& posSuffix,
int8_t type) {
negPrefixPatternForCurrency = negPrefix;
negSuffixPatternForCurrency = negSuffix;
posPrefixPatternForCurrency = posPrefix;
posSuffixPatternForCurrency = posSuffix;
patternType = type;
}
};
/* affix for currency formatting when the currency sign in the pattern
* equals to 3, such as the pattern contains 3 currency sign or
* the formatter style is currency plural format style.
*/
struct AffixesForCurrency : public UMemory {
// negative prefix
UnicodeString negPrefixForCurrency;
// negative suffix
UnicodeString negSuffixForCurrency;
// positive prefix
UnicodeString posPrefixForCurrency;
// positive suffix
UnicodeString posSuffixForCurrency;
int32_t formatWidth;
AffixesForCurrency(const UnicodeString& negPrefix,
const UnicodeString& negSuffix,
const UnicodeString& posPrefix,
const UnicodeString& posSuffix) {
negPrefixForCurrency = negPrefix;
negSuffixForCurrency = negSuffix;
posPrefixForCurrency = posPrefix;
posSuffixForCurrency = posSuffix;
}
};
U_CDECL_BEGIN
/**
* @internal ICU 4.2
*/
static UBool U_CALLCONV decimfmtAffixValueComparator(UHashTok val1, UHashTok val2);
/**
* @internal ICU 4.2
*/
static UBool U_CALLCONV decimfmtAffixPatternValueComparator(UHashTok val1, UHashTok val2);
static UBool
U_CALLCONV decimfmtAffixValueComparator(UHashTok val1, UHashTok val2) {
const AffixesForCurrency* affix_1 =
(AffixesForCurrency*)val1.pointer;
const AffixesForCurrency* affix_2 =
(AffixesForCurrency*)val2.pointer;
return affix_1->negPrefixForCurrency == affix_2->negPrefixForCurrency &&
affix_1->negSuffixForCurrency == affix_2->negSuffixForCurrency &&
affix_1->posPrefixForCurrency == affix_2->posPrefixForCurrency &&
affix_1->posSuffixForCurrency == affix_2->posSuffixForCurrency;
}
static UBool
U_CALLCONV decimfmtAffixPatternValueComparator(UHashTok val1, UHashTok val2) {
const AffixPatternsForCurrency* affix_1 =
(AffixPatternsForCurrency*)val1.pointer;
const AffixPatternsForCurrency* affix_2 =
(AffixPatternsForCurrency*)val2.pointer;
return affix_1->negPrefixPatternForCurrency ==
affix_2->negPrefixPatternForCurrency &&
affix_1->negSuffixPatternForCurrency ==
affix_2->negSuffixPatternForCurrency &&
affix_1->posPrefixPatternForCurrency ==
affix_2->posPrefixPatternForCurrency &&
affix_1->posSuffixPatternForCurrency ==
affix_2->posSuffixPatternForCurrency &&
affix_1->patternType == affix_2->patternType;
}
U_CDECL_END
//#define FMT_DEBUG
#ifdef FMT_DEBUG
#include <stdio.h>
static void debugout(UnicodeString s) {
char buf[2000];
s.extract((int32_t) 0, s.length(), buf);
printf("%s\n", buf);
}
#define debug(x) printf("%s\n", x);
#else
#define debugout(x)
#define debug(x)
#endif
// *****************************************************************************
// class DecimalFormat
// *****************************************************************************
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DecimalFormat)
// Constants for characters used in programmatic (unlocalized) patterns.
#define kPatternZeroDigit ((UChar)0x0030) /*'0'*/
#define kPatternSignificantDigit ((UChar)0x0040) /*'@'*/
#define kPatternGroupingSeparator ((UChar)0x002C) /*','*/
#define kPatternDecimalSeparator ((UChar)0x002E) /*'.'*/
#define kPatternPerMill ((UChar)0x2030)
#define kPatternPercent ((UChar)0x0025) /*'%'*/
#define kPatternDigit ((UChar)0x0023) /*'#'*/
#define kPatternSeparator ((UChar)0x003B) /*';'*/
#define kPatternExponent ((UChar)0x0045) /*'E'*/
#define kPatternPlus ((UChar)0x002B) /*'+'*/
#define kPatternMinus ((UChar)0x002D) /*'-'*/
#define kPatternPadEscape ((UChar)0x002A) /*'*'*/
#define kQuote ((UChar)0x0027) /*'\''*/
/**
* The CURRENCY_SIGN is the standard Unicode symbol for currency. It
* is used in patterns and substitued with either the currency symbol,
* or if it is doubled, with the international currency symbol. If the
* CURRENCY_SIGN is seen in a pattern, then the decimal separator is
* replaced with the monetary decimal separator.
*/
#define kCurrencySign ((UChar)0x00A4)
#define kDefaultPad ((UChar)0x0020) /* */
const int32_t DecimalFormat::kDoubleIntegerDigits = 309;
const int32_t DecimalFormat::kDoubleFractionDigits = 340;
const int32_t DecimalFormat::kMaxScientificIntegerDigits = 8;
/**
* These are the tags we expect to see in normal resource bundle files associated
* with a locale.
*/
const char DecimalFormat::fgNumberPatterns[]="NumberPatterns"; // Deprecated - not used
static const char fgNumberElements[]="NumberElements";
static const char fgLatn[]="latn";
static const char fgPatterns[]="patterns";
static const char fgDecimalFormat[]="decimalFormat";
static const char fgCurrencyFormat[]="currencyFormat";
static const UChar fgTripleCurrencySign[] = {0xA4, 0xA4, 0xA4, 0};
inline int32_t _min(int32_t a, int32_t b) { return (a<b) ? a : b; }
inline int32_t _max(int32_t a, int32_t b) { return (a<b) ? b : a; }
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance in the default locale.
DecimalFormat::DecimalFormat(UErrorCode& status) {
init();
UParseError parseError;
construct(status, parseError);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern in the default locale.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
UErrorCode& status) {
init();
UParseError parseError;
construct(status, parseError, &pattern);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the default locale. The
// created instance owns the symbols.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
DecimalFormatSymbols* symbolsToAdopt,
UErrorCode& status) {
init();
UParseError parseError;
if (symbolsToAdopt == NULL)
status = U_ILLEGAL_ARGUMENT_ERROR;
construct(status, parseError, &pattern, symbolsToAdopt);
}
DecimalFormat::DecimalFormat( const UnicodeString& pattern,
DecimalFormatSymbols* symbolsToAdopt,
UParseError& parseErr,
UErrorCode& status) {
init();
if (symbolsToAdopt == NULL)
status = U_ILLEGAL_ARGUMENT_ERROR;
construct(status,parseErr, &pattern, symbolsToAdopt);
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the default locale. The
// created instance owns the clone of the symbols.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
const DecimalFormatSymbols& symbols,
UErrorCode& status) {
init();
UParseError parseError;
construct(status, parseError, &pattern, new DecimalFormatSymbols(symbols));
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern, the number format symbols, and the number format style.
// The created instance owns the clone of the symbols.
DecimalFormat::DecimalFormat(const UnicodeString& pattern,
DecimalFormatSymbols* symbolsToAdopt,
UNumberFormatStyle style,
UErrorCode& status) {
init();
fStyle = style;
UParseError parseError;
construct(status, parseError, &pattern, symbolsToAdopt);
}
//-----------------------------------------------------------------------------
// Common DecimalFormat initialization.
// Put all fields of an uninitialized object into a known state.
// Common code, shared by all constructors.
void
DecimalFormat::init() {
fPosPrefixPattern = 0;
fPosSuffixPattern = 0;
fNegPrefixPattern = 0;
fNegSuffixPattern = 0;
fCurrencyChoice = 0;
fMultiplier = NULL;
fGroupingSize = 0;
fGroupingSize2 = 0;
fDecimalSeparatorAlwaysShown = FALSE;
fSymbols = NULL;
fUseSignificantDigits = FALSE;
fMinSignificantDigits = 1;
fMaxSignificantDigits = 6;
fUseExponentialNotation = FALSE;
fMinExponentDigits = 0;
fExponentSignAlwaysShown = FALSE;
fRoundingIncrement = 0;
fRoundingMode = kRoundHalfEven;
fPad = 0;
fFormatWidth = 0;
fPadPosition = kPadBeforePrefix;
fStyle = UNUM_DECIMAL;
fCurrencySignCount = 0;
fAffixPatternsForCurrency = NULL;
fAffixesForCurrency = NULL;
fPluralAffixesForCurrency = NULL;
fCurrencyPluralInfo = NULL;
}
//------------------------------------------------------------------------------
// Constructs a DecimalFormat instance with the specified number format
// pattern and the number format symbols in the desired locale. The
// created instance owns the symbols.
void
DecimalFormat::construct(UErrorCode& status,
UParseError& parseErr,
const UnicodeString* pattern,
DecimalFormatSymbols* symbolsToAdopt)
{
fSymbols = symbolsToAdopt; // Do this BEFORE aborting on status failure!!!
fRoundingIncrement = NULL;
fRoundingMode = kRoundHalfEven;
fPad = kPatternPadEscape;
fPadPosition = kPadBeforePrefix;
if (U_FAILURE(status))
return;
fPosPrefixPattern = fPosSuffixPattern = NULL;
fNegPrefixPattern = fNegSuffixPattern = NULL;
setMultiplier(1);
fGroupingSize = 3;
fGroupingSize2 = 0;
fDecimalSeparatorAlwaysShown = FALSE;
fUseExponentialNotation = FALSE;
fMinExponentDigits = 0;
if (fSymbols == NULL)
{
fSymbols = new DecimalFormatSymbols(Locale::getDefault(), status);
/* test for NULL */
if (fSymbols == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
UnicodeString str;
// Uses the default locale's number format pattern if there isn't
// one specified.
if (pattern == NULL)
{
int32_t len = 0;
UResourceBundle *resource = ures_open(NULL, Locale::getDefault().getName(), &status);
resource = ures_getByKeyWithFallback(resource, fgNumberElements, resource, &status);
// TODO : Get the pattern based on the active numbering system for the locale. Right now assumes "latn".
resource = ures_getByKeyWithFallback(resource, fgLatn, resource, &status);
resource = ures_getByKeyWithFallback(resource, fgPatterns, resource, &status);
const UChar *resStr = ures_getStringByKeyWithFallback(resource, fgDecimalFormat, &len, &status);
str.setTo(TRUE, resStr, len);
pattern = &str;
ures_close(resource);
}
if (U_FAILURE(status))
{
return;
}
if (pattern->indexOf((UChar)kCurrencySign) >= 0) {
// If it looks like we are going to use a currency pattern
// then do the time consuming lookup.
setCurrencyForSymbols();
} else {
setCurrencyInternally(NULL, status);
}
const UnicodeString* patternUsed;
UnicodeString currencyPluralPatternForOther;
// apply pattern
if (fStyle == UNUM_CURRENCY_PLURAL) {
fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
if (U_FAILURE(status)) {
return;
}
// the pattern used in format is not fixed until formatting,
// in which, the number is known and
// will be used to pick the right pattern based on plural count.
// Here, set the pattern as the pattern of plural count == "other".
// For most locale, the patterns are probably the same for all
// plural count. If not, the right pattern need to be re-applied
// during format.
fCurrencyPluralInfo->getCurrencyPluralPattern(UNICODE_STRING("other", 5), currencyPluralPatternForOther);
patternUsed = ¤cyPluralPatternForOther;
// TODO: not needed?
setCurrencyForSymbols();
} else {
patternUsed = pattern;
}
if (patternUsed->indexOf(kCurrencySign) != -1) {
// initialize for currency, not only for plural format,
// but also for mix parsing
if (fCurrencyPluralInfo == NULL) {
fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
if (U_FAILURE(status)) {
return;
}
}
// need it for mix parsing
setupCurrencyAffixPatterns(status);
// expanded affixes for plural names
if (patternUsed->indexOf(fgTripleCurrencySign, 3, 0) != -1) {
setupCurrencyAffixes(*patternUsed, TRUE, TRUE, status);
}
}
applyPatternWithoutExpandAffix(*patternUsed,FALSE, parseErr, status);
// expand affixes
if (fCurrencySignCount != fgCurrencySignCountInPluralFormat) {
expandAffixAdjustWidth(NULL);
}
// If it was a currency format, apply the appropriate rounding by
// resetting the currency. NOTE: this copies fCurrency on top of itself.
if (fCurrencySignCount > fgCurrencySignCountZero) {
setCurrencyInternally(getCurrency(), status);
}
}
void
DecimalFormat::setupCurrencyAffixPatterns(UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
UParseError parseErr;
fAffixPatternsForCurrency = initHashForAffixPattern(status);
if (U_FAILURE(status)) {
return;
}
// Save the default currency patterns of this locale.
// Here, chose onlyApplyPatternWithoutExpandAffix without
// expanding the affix patterns into affixes.
UnicodeString currencyPattern;
UErrorCode error = U_ZERO_ERROR;
UResourceBundle *resource = ures_open(NULL, fSymbols->getLocale().getName(), &error);
resource = ures_getByKeyWithFallback(resource, fgNumberElements, resource, &error);
// TODO : Get the pattern based on the active numbering system for the locale. Right now assumes "latn".
resource = ures_getByKeyWithFallback(resource, fgLatn, resource, &error);
resource = ures_getByKeyWithFallback(resource, fgPatterns, resource, &error);
int32_t patLen = 0;
const UChar *patResStr = ures_getStringByKeyWithFallback(resource, fgCurrencyFormat, &patLen, &error);
ures_close(resource);
if (U_SUCCESS(error)) {
applyPatternWithoutExpandAffix(UnicodeString(patResStr, patLen), false,
parseErr, status);
AffixPatternsForCurrency* affixPtn = new AffixPatternsForCurrency(
*fNegPrefixPattern,
*fNegSuffixPattern,
*fPosPrefixPattern,
*fPosSuffixPattern,
UCURR_SYMBOL_NAME);
fAffixPatternsForCurrency->put(UNICODE_STRING("default", 7), affixPtn, status);
}
// save the unique currency plural patterns of this locale.
Hashtable* pluralPtn = fCurrencyPluralInfo->fPluralCountToCurrencyUnitPattern;
const UHashElement* element = NULL;
int32_t pos = -1;
Hashtable pluralPatternSet;
while ((element = pluralPtn->nextElement(pos)) != NULL) {
const UHashTok valueTok = element->value;
const UnicodeString* value = (UnicodeString*)valueTok.pointer;
const UHashTok keyTok = element->key;
const UnicodeString* key = (UnicodeString*)keyTok.pointer;
if (pluralPatternSet.geti(*value) != 1) {
pluralPatternSet.puti(*value, 1, status);
applyPatternWithoutExpandAffix(*value, false, parseErr, status);
AffixPatternsForCurrency* affixPtn = new AffixPatternsForCurrency(
*fNegPrefixPattern,
*fNegSuffixPattern,
*fPosPrefixPattern,
*fPosSuffixPattern,
UCURR_LONG_NAME);
fAffixPatternsForCurrency->put(*key, affixPtn, status);
}
}
}
void
DecimalFormat::setupCurrencyAffixes(const UnicodeString& pattern,
UBool setupForCurrentPattern,
UBool setupForPluralPattern,
UErrorCode& status) {
if (U_FAILURE(status)) {
return;
}
UParseError parseErr;
if (setupForCurrentPattern) {
if (fAffixesForCurrency) {
deleteHashForAffix(fAffixesForCurrency);
}
fAffixesForCurrency = initHashForAffix(status);
if (U_SUCCESS(status)) {
applyPatternWithoutExpandAffix(pattern, false, parseErr, status);
const PluralRules* pluralRules = fCurrencyPluralInfo->getPluralRules();
StringEnumeration* keywords = pluralRules->getKeywords(status);
if (U_SUCCESS(status)) {
const UnicodeString* pluralCount;
while ((pluralCount = keywords->snext(status)) != NULL) {
if ( U_SUCCESS(status) ) {
expandAffixAdjustWidth(pluralCount);
AffixesForCurrency* affix = new AffixesForCurrency(
fNegativePrefix, fNegativeSuffix, fPositivePrefix, fPositiveSuffix);
fAffixesForCurrency->put(*pluralCount, affix, status);
}
}
}
delete keywords;
}
}
if (U_FAILURE(status)) {
return;
}
if (setupForPluralPattern) {
if (fPluralAffixesForCurrency) {
deleteHashForAffix(fPluralAffixesForCurrency);
}
fPluralAffixesForCurrency = initHashForAffix(status);
if (U_SUCCESS(status)) {
const PluralRules* pluralRules = fCurrencyPluralInfo->getPluralRules();
StringEnumeration* keywords = pluralRules->getKeywords(status);
if (U_SUCCESS(status)) {
const UnicodeString* pluralCount;
while ((pluralCount = keywords->snext(status)) != NULL) {
if ( U_SUCCESS(status) ) {
UnicodeString ptn;
fCurrencyPluralInfo->getCurrencyPluralPattern(*pluralCount, ptn);
applyPatternInternally(*pluralCount, ptn, false, parseErr, status);
AffixesForCurrency* affix = new AffixesForCurrency(
fNegativePrefix, fNegativeSuffix, fPositivePrefix, fPositiveSuffix);
fPluralAffixesForCurrency->put(*pluralCount, affix, status);
}
}
}
delete keywords;
}
}
}
//------------------------------------------------------------------------------
DecimalFormat::~DecimalFormat()
{
delete fPosPrefixPattern;
delete fPosSuffixPattern;
delete fNegPrefixPattern;
delete fNegSuffixPattern;
delete fCurrencyChoice;
delete fMultiplier;
delete fSymbols;
delete fRoundingIncrement;
deleteHashForAffixPattern();
deleteHashForAffix(fAffixesForCurrency);
deleteHashForAffix(fPluralAffixesForCurrency);
delete fCurrencyPluralInfo;
}
//------------------------------------------------------------------------------
// copy constructor
DecimalFormat::DecimalFormat(const DecimalFormat &source) :
NumberFormat(source) {
init();
*this = source;
}
//------------------------------------------------------------------------------
// assignment operator
static void _copy_us_ptr(UnicodeString** pdest, const UnicodeString* source) {
if (source == NULL) {
delete *pdest;
*pdest = NULL;
} else if (*pdest == NULL) {
*pdest = new UnicodeString(*source);
} else {
**pdest = *source;
}
}
DecimalFormat&
DecimalFormat::operator=(const DecimalFormat& rhs)
{
if(this != &rhs) {
NumberFormat::operator=(rhs);
fPositivePrefix = rhs.fPositivePrefix;
fPositiveSuffix = rhs.fPositiveSuffix;
fNegativePrefix = rhs.fNegativePrefix;
fNegativeSuffix = rhs.fNegativeSuffix;
_copy_us_ptr(&fPosPrefixPattern, rhs.fPosPrefixPattern);
_copy_us_ptr(&fPosSuffixPattern, rhs.fPosSuffixPattern);
_copy_us_ptr(&fNegPrefixPattern, rhs.fNegPrefixPattern);
_copy_us_ptr(&fNegSuffixPattern, rhs.fNegSuffixPattern);
if (rhs.fCurrencyChoice == 0) {
delete fCurrencyChoice;
fCurrencyChoice = 0;
} else {
fCurrencyChoice = (ChoiceFormat*) rhs.fCurrencyChoice->clone();
}
setRoundingIncrement(rhs.getRoundingIncrement());
fRoundingMode = rhs.fRoundingMode;
setMultiplier(rhs.getMultiplier());
fGroupingSize = rhs.fGroupingSize;
fGroupingSize2 = rhs.fGroupingSize2;
fDecimalSeparatorAlwaysShown = rhs.fDecimalSeparatorAlwaysShown;
if(fSymbols == NULL) {
fSymbols = new DecimalFormatSymbols(*rhs.fSymbols);
} else {
*fSymbols = *rhs.fSymbols;
}
fUseExponentialNotation = rhs.fUseExponentialNotation;
fExponentSignAlwaysShown = rhs.fExponentSignAlwaysShown;
/*Bertrand A. D. Update 98.03.17*/
fCurrencySignCount = rhs.fCurrencySignCount;
/*end of Update*/
fMinExponentDigits = rhs.fMinExponentDigits;
/* sfb 990629 */
fFormatWidth = rhs.fFormatWidth;
fPad = rhs.fPad;
fPadPosition = rhs.fPadPosition;
/* end sfb */
fMinSignificantDigits = rhs.fMinSignificantDigits;
fMaxSignificantDigits = rhs.fMaxSignificantDigits;
fUseSignificantDigits = rhs.fUseSignificantDigits;
fFormatPattern = rhs.fFormatPattern;
fStyle = rhs.fStyle;
fCurrencySignCount = rhs.fCurrencySignCount;
if (rhs.fCurrencyPluralInfo) {
delete fCurrencyPluralInfo;
fCurrencyPluralInfo = rhs.fCurrencyPluralInfo->clone();
}
if (rhs.fAffixPatternsForCurrency) {
UErrorCode status = U_ZERO_ERROR;
deleteHashForAffixPattern();
fAffixPatternsForCurrency = initHashForAffixPattern(status);
copyHashForAffixPattern(rhs.fAffixPatternsForCurrency,
fAffixPatternsForCurrency, status);
}
if (rhs.fAffixesForCurrency) {
UErrorCode status = U_ZERO_ERROR;
deleteHashForAffix(fAffixesForCurrency);
fAffixesForCurrency = initHashForAffixPattern(status);
copyHashForAffix(rhs.fAffixesForCurrency, fAffixesForCurrency, status);
}
if (rhs.fPluralAffixesForCurrency) {
UErrorCode status = U_ZERO_ERROR;
deleteHashForAffix(fPluralAffixesForCurrency);
fPluralAffixesForCurrency = initHashForAffixPattern(status);
copyHashForAffix(rhs.fPluralAffixesForCurrency, fPluralAffixesForCurrency, status);
}
}
return *this;
}
//------------------------------------------------------------------------------
UBool
DecimalFormat::operator==(const Format& that) const
{
if (this == &that)
return TRUE;
// NumberFormat::operator== guarantees this cast is safe
const DecimalFormat* other = (DecimalFormat*)&that;
#ifdef FMT_DEBUG
// This code makes it easy to determine why two format objects that should
// be equal aren't.
UBool first = TRUE;
if (!NumberFormat::operator==(that)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("NumberFormat::!=");
} else {
if (!((fPosPrefixPattern == other->fPosPrefixPattern && // both null
fPositivePrefix == other->fPositivePrefix)
|| (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
*fPosPrefixPattern == *other->fPosPrefixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Pos Prefix !=");
}
if (!((fPosSuffixPattern == other->fPosSuffixPattern && // both null
fPositiveSuffix == other->fPositiveSuffix)
|| (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
*fPosSuffixPattern == *other->fPosSuffixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Pos Suffix !=");
}
if (!((fNegPrefixPattern == other->fNegPrefixPattern && // both null
fNegativePrefix == other->fNegativePrefix)
|| (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
*fNegPrefixPattern == *other->fNegPrefixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Neg Prefix ");
if (fNegPrefixPattern == NULL) {
debug("NULL(");
debugout(fNegativePrefix);
debug(")");
} else {
debugout(*fNegPrefixPattern);
}
debug(" != ");
if (other->fNegPrefixPattern == NULL) {
debug("NULL(");
debugout(other->fNegativePrefix);
debug(")");
} else {
debugout(*other->fNegPrefixPattern);
}
}
if (!((fNegSuffixPattern == other->fNegSuffixPattern && // both null
fNegativeSuffix == other->fNegativeSuffix)
|| (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
*fNegSuffixPattern == *other->fNegSuffixPattern))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Neg Suffix ");
if (fNegSuffixPattern == NULL) {
debug("NULL(");
debugout(fNegativeSuffix);
debug(")");
} else {
debugout(*fNegSuffixPattern);
}
debug(" != ");
if (other->fNegSuffixPattern == NULL) {
debug("NULL(");
debugout(other->fNegativeSuffix);
debug(")");
} else {
debugout(*other->fNegSuffixPattern);
}
}
if (!((fRoundingIncrement == other->fRoundingIncrement) // both null
|| (fRoundingIncrement != NULL &&
other->fRoundingIncrement != NULL &&
*fRoundingIncrement == *other->fRoundingIncrement))) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Rounding Increment !=");
}
if (getMultiplier() != other->getMultiplier()) {
if (first) { printf("[ "); first = FALSE; }
printf("Multiplier %ld != %ld", getMultiplier(), other->getMultiplier());
}
if (fGroupingSize != other->fGroupingSize) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Grouping Size %ld != %ld", fGroupingSize, other->fGroupingSize);
}
if (fGroupingSize2 != other->fGroupingSize2) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Secondary Grouping Size %ld != %ld", fGroupingSize2, other->fGroupingSize2);
}
if (fDecimalSeparatorAlwaysShown != other->fDecimalSeparatorAlwaysShown) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
printf("Dec Sep Always %d != %d", fDecimalSeparatorAlwaysShown, other->fDecimalSeparatorAlwaysShown);
}
if (fUseExponentialNotation != other->fUseExponentialNotation) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Use Exp !=");
}
if (!(!fUseExponentialNotation ||
fMinExponentDigits != other->fMinExponentDigits)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Exp Digits !=");
}
if (*fSymbols != *(other->fSymbols)) {
if (first) { printf("[ "); first = FALSE; } else { printf(", "); }
debug("Symbols !=");
}
// TODO Add debug stuff for significant digits here
if (fUseSignificantDigits != other->fUseSignificantDigits) {
debug("fUseSignificantDigits !=");
}
if (fUseSignificantDigits &&
fMinSignificantDigits != other->fMinSignificantDigits) {
debug("fMinSignificantDigits !=");
}
if (fUseSignificantDigits &&
fMaxSignificantDigits != other->fMaxSignificantDigits) {
debug("fMaxSignificantDigits !=");
}
if (!first) { printf(" ]"); }
if (fCurrencySignCount != other->fCurrencySignCount) {
debug("fCurrencySignCount !=");
}
if (fCurrencyPluralInfo == other->fCurrencyPluralInfo) {
debug("fCurrencyPluralInfo == ");
if (fCurrencyPluralInfo == NULL) {
debug("fCurrencyPluralInfo == NULL");
}
}
if (fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo != NULL &&
*fCurrencyPluralInfo != *(other->fCurrencyPluralInfo)) {
debug("fCurrencyPluralInfo !=");
}
if (fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo == NULL ||
fCurrencyPluralInfo == NULL && other->fCurrencyPluralInfo != NULL) {
debug("fCurrencyPluralInfo one NULL, the other not");
}
if (fCurrencyPluralInfo == NULL && other->fCurrencyPluralInfo == NULL) {
debug("fCurrencyPluralInfo == ");
}
}
#endif
return (NumberFormat::operator==(that) &&
((fCurrencySignCount == fgCurrencySignCountInPluralFormat) ?
(fAffixPatternsForCurrency->equals(*other->fAffixPatternsForCurrency)) :
(((fPosPrefixPattern == other->fPosPrefixPattern && // both null
fPositivePrefix == other->fPositivePrefix)
|| (fPosPrefixPattern != 0 && other->fPosPrefixPattern != 0 &&
*fPosPrefixPattern == *other->fPosPrefixPattern)) &&
((fPosSuffixPattern == other->fPosSuffixPattern && // both null
fPositiveSuffix == other->fPositiveSuffix)
|| (fPosSuffixPattern != 0 && other->fPosSuffixPattern != 0 &&
*fPosSuffixPattern == *other->fPosSuffixPattern)) &&
((fNegPrefixPattern == other->fNegPrefixPattern && // both null
fNegativePrefix == other->fNegativePrefix)
|| (fNegPrefixPattern != 0 && other->fNegPrefixPattern != 0 &&
*fNegPrefixPattern == *other->fNegPrefixPattern)) &&
((fNegSuffixPattern == other->fNegSuffixPattern && // both null
fNegativeSuffix == other->fNegativeSuffix)
|| (fNegSuffixPattern != 0 && other->fNegSuffixPattern != 0 &&
*fNegSuffixPattern == *other->fNegSuffixPattern)))) &&
((fRoundingIncrement == other->fRoundingIncrement) // both null
|| (fRoundingIncrement != NULL &&
other->fRoundingIncrement != NULL &&
*fRoundingIncrement == *other->fRoundingIncrement)) &&
getMultiplier() == other->getMultiplier() &&
fGroupingSize == other->fGroupingSize &&
fGroupingSize2 == other->fGroupingSize2 &&
fDecimalSeparatorAlwaysShown == other->fDecimalSeparatorAlwaysShown &&
fUseExponentialNotation == other->fUseExponentialNotation &&
(!fUseExponentialNotation ||
fMinExponentDigits == other->fMinExponentDigits) &&
*fSymbols == *(other->fSymbols) &&
fUseSignificantDigits == other->fUseSignificantDigits &&
(!fUseSignificantDigits ||
(fMinSignificantDigits == other->fMinSignificantDigits &&
fMaxSignificantDigits == other->fMaxSignificantDigits)) &&
fCurrencySignCount == other->fCurrencySignCount &&
((fCurrencyPluralInfo == other->fCurrencyPluralInfo &&
fCurrencyPluralInfo == NULL) ||
(fCurrencyPluralInfo != NULL && other->fCurrencyPluralInfo != NULL &&
*fCurrencyPluralInfo == *(other->fCurrencyPluralInfo))));
}
//------------------------------------------------------------------------------
Format*
DecimalFormat::clone() const
{
return new DecimalFormat(*this);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format(int32_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
return format((int64_t)number, appendTo, fieldPosition);
}
UnicodeString&
DecimalFormat::format(int32_t number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const
{
return format((int64_t)number, appendTo, posIter, status);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format(int64_t number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
FieldPositionOnlyHandler handler(fieldPosition);
return _format(number, appendTo, handler);
}
UnicodeString&
DecimalFormat::format(int64_t number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const
{
FieldPositionIteratorHandler handler(posIter, status);
return _format(number, appendTo, handler);
}
UnicodeString&
DecimalFormat::_format(int64_t number,
UnicodeString& appendTo,
FieldPositionHandler& handler) const
{
UErrorCode status = U_ZERO_ERROR;
DigitList digits;
digits.set(number);
return _format(digits, appendTo, handler, status);
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format( double number,
UnicodeString& appendTo,
FieldPosition& fieldPosition) const
{
FieldPositionOnlyHandler handler(fieldPosition);
return _format(number, appendTo, handler);
}
UnicodeString&
DecimalFormat::format( double number,
UnicodeString& appendTo,
FieldPositionIterator* posIter,
UErrorCode& status) const
{
FieldPositionIteratorHandler handler(posIter, status);
return _format(number, appendTo, handler);
}
UnicodeString&
DecimalFormat::_format( double number,
UnicodeString& appendTo,
FieldPositionHandler& handler) const
{
// Special case for NaN, sets the begin and end index to be the
// the string length of localized name of NaN.
// TODO: let NaNs go through DigitList.
if (uprv_isNaN(number))
{
int begin = appendTo.length();
appendTo += getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
handler.addAttribute(kIntegerField, begin, appendTo.length());
addPadding(appendTo, handler, 0, 0);
return appendTo;
}
UErrorCode status = U_ZERO_ERROR;
DigitList digits;
digits.set(number);
_format(digits, appendTo, handler, status);
// No way to return status from here.
return appendTo;
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::format(const StringPiece &number,
UnicodeString &toAppendTo,
FieldPositionIterator *posIter,
UErrorCode &status) const
{
DigitList dnum;
dnum.set(number, status);
if (U_FAILURE(status)) {
return toAppendTo;
}
FieldPositionIteratorHandler handler(posIter, status);
_format(dnum, toAppendTo, handler, status);
return toAppendTo;
}
UnicodeString&
DecimalFormat::format(const DigitList &number,
UnicodeString &appendTo,
FieldPositionIterator *posIter,
UErrorCode &status) const {
FieldPositionIteratorHandler handler(posIter, status);
_format(number, appendTo, handler, status);
return appendTo;
}
UnicodeString&
DecimalFormat::format(const DigitList &number,
UnicodeString& appendTo,
FieldPosition& pos,
UErrorCode &status) const {
FieldPositionOnlyHandler handler(pos);
_format(number, appendTo, handler, status);
return appendTo;
}
UnicodeString&
DecimalFormat::_format(const DigitList &number,
UnicodeString& appendTo,
FieldPositionHandler& handler,
UErrorCode &status) const
{
// Special case for NaN, sets the begin and end index to be the
// the string length of localized name of NaN.
if (number.isNaN())
{
int begin = appendTo.length();
appendTo += getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
handler.addAttribute(kIntegerField, begin, appendTo.length());
addPadding(appendTo, handler, 0, 0);
return appendTo;
}
// Do this BEFORE checking to see if value is infinite or negative! Sets the
// begin and end index to be length of the string composed of
// localized name of Infinite and the positive/negative localized
// signs.
DigitList adjustedNum(number); // Copy, so we do not alter the original.
adjustedNum.setRoundingMode(fRoundingMode);
if (fMultiplier != NULL) {
adjustedNum.mult(*fMultiplier, status);
}
/*
* Note: sign is important for zero as well as non-zero numbers.
* Proper detection of -0.0 is needed to deal with the
* issues raised by bugs 4106658, 4106667, and 4147706. Liu 7/6/98.
*/
UBool isNegative = !adjustedNum.isPositive();
// Apply rounding after multiplier
adjustedNum.fContext.status &= ~DEC_Inexact;
if (fRoundingIncrement != NULL) {
adjustedNum.div(*fRoundingIncrement, status);
adjustedNum.toIntegralValue();
adjustedNum.mult(*fRoundingIncrement, status);
adjustedNum.trim();
}
if (fRoundingMode == kRoundUnnecessary && (adjustedNum.fContext.status & DEC_Inexact)) {
status = U_FORMAT_INEXACT_ERROR;
return appendTo;
}
// Special case for INFINITE,
if (adjustedNum.isInfinite()) {
int32_t prefixLen = appendAffix(appendTo, adjustedNum.getDouble(), handler, isNegative, TRUE);
int begin = appendTo.length();
appendTo += getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
handler.addAttribute(kIntegerField, begin, appendTo.length());
int32_t suffixLen = appendAffix(appendTo, adjustedNum.getDouble(), handler, isNegative, FALSE);
addPadding(appendTo, handler, prefixLen, suffixLen);
return appendTo;
}
if (fUseExponentialNotation || areSignificantDigitsUsed()) {
int32_t sigDigits = precision();
if (sigDigits > 0) {
adjustedNum.round(sigDigits);
}
} else {
// Fixed point format. Round to a set number of fraction digits.
int32_t numFractionDigits = precision();
adjustedNum.roundFixedPoint(numFractionDigits);
}
if (fRoundingMode == kRoundUnnecessary && (adjustedNum.fContext.status & DEC_Inexact)) {
status = U_FORMAT_INEXACT_ERROR;
return appendTo;
}
return subformat(appendTo, handler, adjustedNum, FALSE);
}
UnicodeString&
DecimalFormat::format( const Formattable& obj,
UnicodeString& appendTo,
FieldPosition& fieldPosition,
UErrorCode& status) const
{
return NumberFormat::format(obj, appendTo, fieldPosition, status);
}
/**
* Return true if a grouping separator belongs at the given
* position, based on whether grouping is in use and the values of
* the primary and secondary grouping interval.
* @param pos the number of integer digits to the right of
* the current position. Zero indicates the position after the
* rightmost integer digit.
* @return true if a grouping character belongs at the current
* position.
*/
UBool DecimalFormat::isGroupingPosition(int32_t pos) const {
UBool result = FALSE;
if (isGroupingUsed() && (pos > 0) && (fGroupingSize > 0)) {
if ((fGroupingSize2 > 0) && (pos > fGroupingSize)) {
result = ((pos - fGroupingSize) % fGroupingSize2) == 0;
} else {
result = pos % fGroupingSize == 0;
}
}
return result;
}
//------------------------------------------------------------------------------
/**
* Complete the formatting of a finite number. On entry, the DigitList must
* be filled in with the correct digits.
*/
UnicodeString&
DecimalFormat::subformat(UnicodeString& appendTo,
FieldPositionHandler& handler,
DigitList& digits,
UBool isInteger) const
{
// char zero = '0';
// DigitList returns digits as '0' thru '9', so we will need to
// always need to subtract the character 0 to get the numeric value to use for indexing.
UChar32 localizedDigits[10];
localizedDigits[0] = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
localizedDigits[1] = getConstSymbol(DecimalFormatSymbols::kOneDigitSymbol).char32At(0);
localizedDigits[2] = getConstSymbol(DecimalFormatSymbols::kTwoDigitSymbol).char32At(0);
localizedDigits[3] = getConstSymbol(DecimalFormatSymbols::kThreeDigitSymbol).char32At(0);
localizedDigits[4] = getConstSymbol(DecimalFormatSymbols::kFourDigitSymbol).char32At(0);
localizedDigits[5] = getConstSymbol(DecimalFormatSymbols::kFiveDigitSymbol).char32At(0);
localizedDigits[6] = getConstSymbol(DecimalFormatSymbols::kSixDigitSymbol).char32At(0);
localizedDigits[7] = getConstSymbol(DecimalFormatSymbols::kSevenDigitSymbol).char32At(0);
localizedDigits[8] = getConstSymbol(DecimalFormatSymbols::kEightDigitSymbol).char32At(0);
localizedDigits[9] = getConstSymbol(DecimalFormatSymbols::kNineDigitSymbol).char32At(0);
const UnicodeString *grouping ;
if(fCurrencySignCount > fgCurrencySignCountZero) {
grouping = &getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol);
}else{
grouping = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
}
const UnicodeString *decimal;
if(fCurrencySignCount > fgCurrencySignCountZero) {
decimal = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
} else {
decimal = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
UBool useSigDig = areSignificantDigitsUsed();
int32_t maxIntDig = getMaximumIntegerDigits();
int32_t minIntDig = getMinimumIntegerDigits();
// Appends the prefix.
double doubleValue = digits.getDouble();
int32_t prefixLen = appendAffix(appendTo, doubleValue, handler, !digits.isPositive(), TRUE);
if (fUseExponentialNotation)
{
int currentLength = appendTo.length();
int intBegin = currentLength;
int intEnd = -1;
int fracBegin = -1;
int32_t minFracDig = 0;
if (useSigDig) {
maxIntDig = minIntDig = 1;
minFracDig = getMinimumSignificantDigits() - 1;
} else {
minFracDig = getMinimumFractionDigits();
if (maxIntDig > kMaxScientificIntegerDigits) {
maxIntDig = 1;
if (maxIntDig < minIntDig) {
maxIntDig = minIntDig;
}
}
if (maxIntDig > minIntDig) {
minIntDig = 1;
}
}
// Minimum integer digits are handled in exponential format by
// adjusting the exponent. For example, 0.01234 with 3 minimum
// integer digits is "123.4E-4".
// Maximum integer digits are interpreted as indicating the
// repeating range. This is useful for engineering notation, in
// which the exponent is restricted to a multiple of 3. For
// example, 0.01234 with 3 maximum integer digits is "12.34e-3".
// If maximum integer digits are defined and are larger than
// minimum integer digits, then minimum integer digits are
// ignored.
digits.reduce(); // Removes trailing zero digits.
int32_t exponent = digits.getDecimalAt();
if (maxIntDig > 1 && maxIntDig != minIntDig) {
// A exponent increment is defined; adjust to it.
exponent = (exponent > 0) ? (exponent - 1) / maxIntDig
: (exponent / maxIntDig) - 1;
exponent *= maxIntDig;
} else {
// No exponent increment is defined; use minimum integer digits.
// If none is specified, as in "#E0", generate 1 integer digit.
exponent -= (minIntDig > 0 || minFracDig > 0)
? minIntDig : 1;
}
// We now output a minimum number of digits, and more if there
// are more digits, up to the maximum number of digits. We
// place the decimal point after the "integer" digits, which
// are the first (decimalAt - exponent) digits.
int32_t minimumDigits = minIntDig + minFracDig;
// The number of integer digits is handled specially if the number
// is zero, since then there may be no digits.
int32_t integerDigits = digits.isZero() ? minIntDig :
digits.getDecimalAt() - exponent;
int32_t totalDigits = digits.getCount();
if (minimumDigits > totalDigits)
totalDigits = minimumDigits;
if (integerDigits > totalDigits)
totalDigits = integerDigits;
// totalDigits records total number of digits needs to be processed
int32_t i;
for (i=0; i<totalDigits; ++i)
{
if (i == integerDigits)
{
intEnd = appendTo.length();
handler.addAttribute(kIntegerField, intBegin, intEnd);
appendTo += *decimal;
fracBegin = appendTo.length();
handler.addAttribute(kDecimalSeparatorField, fracBegin - 1, fracBegin);
}
// Restores the digit character or pads the buffer with zeros.
UChar32 c = (UChar32)((i < digits.getCount()) ?
localizedDigits[digits.getDigitValue(i)] :
localizedDigits[0]);
appendTo += c;
}
currentLength = appendTo.length();
if (intEnd < 0) {
handler.addAttribute(kIntegerField, intBegin, currentLength);
}
if (fracBegin > 0) {
handler.addAttribute(kFractionField, fracBegin, currentLength);
}
// The exponent is output using the pattern-specified minimum
// exponent digits. There is no maximum limit to the exponent
// digits, since truncating the exponent would appendTo in an
// unacceptable inaccuracy.
appendTo += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
handler.addAttribute(kExponentSymbolField, currentLength, appendTo.length());
currentLength = appendTo.length();
// For zero values, we force the exponent to zero. We
// must do this here, and not earlier, because the value
// is used to determine integer digit count above.
if (digits.isZero())
exponent = 0;
if (exponent < 0) {
appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
handler.addAttribute(kExponentSignField, currentLength, appendTo.length());
} else if (fExponentSignAlwaysShown) {
appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
handler.addAttribute(kExponentSignField, currentLength, appendTo.length());
}
currentLength = appendTo.length();
DigitList expDigits;
expDigits.set(exponent);
{
int expDig = fMinExponentDigits;
if (fUseExponentialNotation && expDig < 1) {
expDig = 1;
}
for (i=expDigits.getDecimalAt(); i<expDig; ++i)
appendTo += (localizedDigits[0]);
}
for (i=0; i<expDigits.getDecimalAt(); ++i)
{
UChar32 c = (UChar32)((i < expDigits.getCount()) ?
localizedDigits[expDigits.getDigitValue(i)] :
localizedDigits[0]);
appendTo += c;
}
handler.addAttribute(kExponentField, currentLength, appendTo.length());
}
else // Not using exponential notation
{
int currentLength = appendTo.length();
int intBegin = currentLength;
int32_t sigCount = 0;
int32_t minSigDig = getMinimumSignificantDigits();
int32_t maxSigDig = getMaximumSignificantDigits();
if (!useSigDig) {
minSigDig = 0;
maxSigDig = INT32_MAX;
}
// Output the integer portion. Here 'count' is the total
// number of integer digits we will display, including both
// leading zeros required to satisfy getMinimumIntegerDigits,
// and actual digits present in the number.
int32_t count = useSigDig ?
_max(1, digits.getDecimalAt()) : minIntDig;
if (digits.getDecimalAt() > 0 && count < digits.getDecimalAt()) {
count = digits.getDecimalAt();
}
// Handle the case where getMaximumIntegerDigits() is smaller
// than the real number of integer digits. If this is so, we
// output the least significant max integer digits. For example,
// the value 1997 printed with 2 max integer digits is just "97".
int32_t digitIndex = 0; // Index into digitList.fDigits[]
if (count > maxIntDig && maxIntDig >= 0) {
count = maxIntDig;
digitIndex = digits.getDecimalAt() - count;
}
int32_t sizeBeforeIntegerPart = appendTo.length();
int32_t i;
for (i=count-1; i>=0; --i)
{
if (i < digits.getDecimalAt() && digitIndex < digits.getCount() &&
sigCount < maxSigDig) {
// Output a real digit
appendTo += (UChar32)localizedDigits[digits.getDigitValue(digitIndex++)];
++sigCount;
}
else
{
// Output a zero (leading or trailing)
appendTo += localizedDigits[0];
if (sigCount > 0) {
++sigCount;
}
}
// Output grouping separator if necessary.
if (isGroupingPosition(i)) {
currentLength = appendTo.length();
appendTo.append(*grouping);
handler.addAttribute(kGroupingSeparatorField, currentLength, appendTo.length());
}
}
// TODO(dlf): this looks like it was a bug, we marked the int field as ending
// before the zero was generated.
// Record field information for caller.
// if (fieldPosition.getField() == NumberFormat::kIntegerField)
// fieldPosition.setEndIndex(appendTo.length());
// Determine whether or not there are any printable fractional
// digits. If we've used up the digits we know there aren't.
UBool fractionPresent = (!isInteger && digitIndex < digits.getCount()) ||
(useSigDig ? (sigCount < minSigDig) : (getMinimumFractionDigits() > 0));
// If there is no fraction present, and we haven't printed any
// integer digits, then print a zero. Otherwise we won't print
// _any_ digits, and we won't be able to parse this string.
if (!fractionPresent && appendTo.length() == sizeBeforeIntegerPart)
appendTo += localizedDigits[0];
currentLength = appendTo.length();
handler.addAttribute(kIntegerField, intBegin, currentLength);
// Output the decimal separator if we always do so.
if (fDecimalSeparatorAlwaysShown || fractionPresent) {
appendTo += *decimal;
handler.addAttribute(kDecimalSeparatorField, currentLength, appendTo.length());
currentLength = appendTo.length();
}
int fracBegin = currentLength;
count = useSigDig ? INT32_MAX : getMaximumFractionDigits();
if (useSigDig && (sigCount == maxSigDig ||
(sigCount >= minSigDig && digitIndex == digits.getCount()))) {
count = 0;
}
for (i=0; i < count; ++i) {
// Here is where we escape from the loop. We escape
// if we've output the maximum fraction digits
// (specified in the for expression above). We also
// stop when we've output the minimum digits and
// either: we have an integer, so there is no
// fractional stuff to display, or we're out of
// significant digits.
if (!useSigDig && i >= getMinimumFractionDigits() &&
(isInteger || digitIndex >= digits.getCount())) {
break;
}
// Output leading fractional zeros. These are zeros
// that come after the decimal but before any
// significant digits. These are only output if
// abs(number being formatted) < 1.0.
if (-1-i > (digits.getDecimalAt()-1)) {
appendTo += localizedDigits[0];
continue;
}
// Output a digit, if we have any precision left, or a
// zero if we don't. We don't want to output noise digits.
if (!isInteger && digitIndex < digits.getCount()) {
appendTo += (UChar32)localizedDigits[digits.getDigitValue(digitIndex++)];
} else {
appendTo += localizedDigits[0];
}
// If we reach the maximum number of significant
// digits, or if we output all the real digits and
// reach the minimum, then we are done.
++sigCount;
if (useSigDig &&
(sigCount == maxSigDig ||
(digitIndex == digits.getCount() && sigCount >= minSigDig))) {
break;
}
}
handler.addAttribute(kFractionField, fracBegin, appendTo.length());
}
int32_t suffixLen = appendAffix(appendTo, doubleValue, handler, !digits.isPositive(), FALSE);
addPadding(appendTo, handler, prefixLen, suffixLen);
return appendTo;
}
/**
* Inserts the character fPad as needed to expand result to fFormatWidth.
* @param result the string to be padded
*/
void DecimalFormat::addPadding(UnicodeString& appendTo,
FieldPositionHandler& handler,
int32_t prefixLen,
int32_t suffixLen) const
{
if (fFormatWidth > 0) {
int32_t len = fFormatWidth - appendTo.length();
if (len > 0) {
UnicodeString padding;
for (int32_t i=0; i<len; ++i) {
padding += fPad;
}
switch (fPadPosition) {
case kPadAfterPrefix:
appendTo.insert(prefixLen, padding);
break;
case kPadBeforePrefix:
appendTo.insert(0, padding);
break;
case kPadBeforeSuffix:
appendTo.insert(appendTo.length() - suffixLen, padding);
break;
case kPadAfterSuffix:
appendTo += padding;
break;
}
if (fPadPosition == kPadBeforePrefix || fPadPosition == kPadAfterPrefix) {
handler.shiftLast(len);
}
}
}
}
//------------------------------------------------------------------------------
void
DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
UErrorCode& status) const
{
NumberFormat::parse(text, result, status);
}
void
DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition) const {
parse(text, result, parsePosition, FALSE);
}
Formattable& DecimalFormat::parseCurrency(const UnicodeString& text,
Formattable& result,
ParsePosition& pos) const {
parse(text, result, pos, TRUE);
return result;
}
/**
* Parses the given text as either a number or a currency amount.
* @param text the string to parse
* @param result output parameter for the result
* @param parsePosition input-output position; on input, the
* position within text to match; must have 0 <= pos.getIndex() <
* text.length(); on output, the position after the last matched
* character. If the parse fails, the position in unchanged upon
* output.
* @param parseCurrency if true, a currency amount is parsed;
* otherwise a Number is parsed
*/
void DecimalFormat::parse(const UnicodeString& text,
Formattable& result,
ParsePosition& parsePosition,
UBool parseCurrency) const {
int32_t backup;
int32_t i = backup = parsePosition.getIndex();
// clear any old contents in the result. In particular, clears any DigitList
// that it may be holding.
result.setLong(0);
// Handle NaN as a special case:
// Skip padding characters, if around prefix
if (fFormatWidth > 0 && (fPadPosition == kPadBeforePrefix ||
fPadPosition == kPadAfterPrefix)) {
i = skipPadding(text, i);
}
if (isLenient()) {
// skip any leading whitespace
i = backup = skipUWhiteSpace(text, i);
}
// If the text is composed of the representation of NaN, returns NaN.length
const UnicodeString *nan = &getConstSymbol(DecimalFormatSymbols::kNaNSymbol);
int32_t nanLen = (text.compare(i, nan->length(), *nan)
? 0 : nan->length());
if (nanLen) {
i += nanLen;
if (fFormatWidth > 0 && (fPadPosition == kPadBeforeSuffix ||
fPadPosition == kPadAfterSuffix)) {
i = skipPadding(text, i);
}
parsePosition.setIndex(i);
result.setDouble(uprv_getNaN());
return;
}
// NaN parse failed; start over
i = backup;
parsePosition.setIndex(i);
// status is used to record whether a number is infinite.
UBool status[fgStatusLength];
UChar curbuf[4];
UChar* currency = parseCurrency ? curbuf : NULL;
DigitList *digits = new DigitList;
if (digits == NULL) {
return; // no way to report error from here.
}
if (fCurrencySignCount > fgCurrencySignCountZero) {
if (!parseForCurrency(text, parsePosition, *digits,
status, currency)) {
delete digits;
return;
}
} else {
if (!subparse(text,
fNegPrefixPattern, fNegSuffixPattern,
fPosPrefixPattern, fPosSuffixPattern,
FALSE, UCURR_SYMBOL_NAME,
parsePosition, *digits, status, currency)) {
parsePosition.setIndex(backup);
delete digits;
return;
}
}
// Handle infinity
if (status[fgStatusInfinite]) {
double inf = uprv_getInfinity();
result.setDouble(digits->isPositive() ? inf : -inf);
delete digits; // TODO: set the dl to infinity, and let it fall into the code below.
}
else {
if (fMultiplier != NULL) {
UErrorCode ec = U_ZERO_ERROR;
digits->div(*fMultiplier, ec);
}
// Negative zero special case:
// if parsing integerOnly, change to +0, which goes into an int32 in a Formattable.
// if not parsing integerOnly, leave as -0, which a double can represent.
if (digits->isZero() && !digits->isPositive() && isParseIntegerOnly()) {
digits->setPositive(TRUE);
}
result.adoptDigitList(digits);
}
if (parseCurrency) {
UErrorCode ec = U_ZERO_ERROR;
Formattable n(result);
result.adoptObject(new CurrencyAmount(n, curbuf, ec));
U_ASSERT(U_SUCCESS(ec)); // should always succeed
}
}
UBool
DecimalFormat::parseForCurrency(const UnicodeString& text,
ParsePosition& parsePosition,
DigitList& digits,
UBool* status,
UChar* currency) const {
int origPos = parsePosition.getIndex();
int maxPosIndex = origPos;
int maxErrorPos = -1;
// First, parse against current pattern.
// Since current pattern could be set by applyPattern(),
// it could be an arbitrary pattern, and it may not be the one
// defined in current locale.
UBool tmpStatus[fgStatusLength];
ParsePosition tmpPos(origPos);
DigitList tmpDigitList;
UBool found;
if (fStyle == UNUM_CURRENCY_PLURAL) {
found = subparse(text,
fNegPrefixPattern, fNegSuffixPattern,
fPosPrefixPattern, fPosSuffixPattern,
TRUE, UCURR_LONG_NAME,
tmpPos, tmpDigitList, tmpStatus, currency);
} else {
found = subparse(text,
fNegPrefixPattern, fNegSuffixPattern,
fPosPrefixPattern, fPosSuffixPattern,
TRUE, UCURR_SYMBOL_NAME,
tmpPos, tmpDigitList, tmpStatus, currency);
}
if (found) {
if (tmpPos.getIndex() > maxPosIndex) {
maxPosIndex = tmpPos.getIndex();
for (int32_t i = 0; i < fgStatusLength; ++i) {
status[i] = tmpStatus[i];
}
digits = tmpDigitList;
}
} else {
maxErrorPos = tmpPos.getErrorIndex();
}
// Then, parse against affix patterns.
// Those are currency patterns and currency plural patterns.
int32_t pos = -1;
const UHashElement* element = NULL;
while ( (element = fAffixPatternsForCurrency->nextElement(pos)) != NULL ) {
const UHashTok valueTok = element->value;
const AffixPatternsForCurrency* affixPtn = (AffixPatternsForCurrency*)valueTok.pointer;
UBool tmpStatus[fgStatusLength];
ParsePosition tmpPos(origPos);
DigitList tmpDigitList;
UBool result = subparse(text,
&affixPtn->negPrefixPatternForCurrency,
&affixPtn->negSuffixPatternForCurrency,
&affixPtn->posPrefixPatternForCurrency,
&affixPtn->posSuffixPatternForCurrency,
TRUE, affixPtn->patternType,
tmpPos, tmpDigitList, tmpStatus, currency);
if (result) {
found = true;
if (tmpPos.getIndex() > maxPosIndex) {
maxPosIndex = tmpPos.getIndex();
for (int32_t i = 0; i < fgStatusLength; ++i) {
status[i] = tmpStatus[i];
}
digits = tmpDigitList;
}
} else {
maxErrorPos = (tmpPos.getErrorIndex() > maxErrorPos) ?
tmpPos.getErrorIndex() : maxErrorPos;
}
}
// Finally, parse against simple affix to find the match.
// For example, in TestMonster suite,
// if the to-be-parsed text is "-\u00A40,00".
// complexAffixCompare will not find match,
// since there is no ISO code matches "\u00A4",
// and the parse stops at "\u00A4".
// We will just use simple affix comparison (look for exact match)
// to pass it.
UBool tmpStatus_2[fgStatusLength];
ParsePosition tmpPos_2(origPos);
DigitList tmpDigitList_2;
// set currencySignCount to 0 so that compareAffix function will
// fall to compareSimpleAffix path, not compareComplexAffix path.
// ?? TODO: is it right? need "false"?
UBool result = subparse(text,
&fNegativePrefix, &fNegativeSuffix,
&fPositivePrefix, &fPositiveSuffix,
FALSE, UCURR_SYMBOL_NAME,
tmpPos_2, tmpDigitList_2, tmpStatus_2,
currency);
if (result) {
if (tmpPos_2.getIndex() > maxPosIndex) {
maxPosIndex = tmpPos_2.getIndex();
for (int32_t i = 0; i < fgStatusLength; ++i) {
status[i] = tmpStatus_2[i];
}
digits = tmpDigitList_2;
}
found = true;
} else {
maxErrorPos = (tmpPos_2.getErrorIndex() > maxErrorPos) ?
tmpPos_2.getErrorIndex() : maxErrorPos;
}
if (!found) {
//parsePosition.setIndex(origPos);
parsePosition.setErrorIndex(maxErrorPos);
} else {
parsePosition.setIndex(maxPosIndex);
parsePosition.setErrorIndex(-1);
}
return found;
}
/**
* Parse the given text into a number. The text is parsed beginning at
* parsePosition, until an unparseable character is seen.
* @param text the string to parse.
* @param negPrefix negative prefix.
* @param negSuffix negative suffix.
* @param posPrefix positive prefix.
* @param posSuffix positive suffix.
* @param currencyParsing whether it is currency parsing or not.
* @param type the currency type to parse against, LONG_NAME only or not.
* @param parsePosition The position at which to being parsing. Upon
* return, the first unparsed character.
* @param digits the DigitList to set to the parsed value.
* @param status output param containing boolean status flags indicating
* whether the value was infinite and whether it was positive.
* @param currency return value for parsed currency, for generic
* currency parsing mode, or NULL for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
*/
UBool DecimalFormat::subparse(const UnicodeString& text,
const UnicodeString* negPrefix,
const UnicodeString* negSuffix,
const UnicodeString* posPrefix,
const UnicodeString* posSuffix,
UBool currencyParsing,
int8_t type,
ParsePosition& parsePosition,
DigitList& digits, UBool* status,
UChar* currency) const
{
// The parsing process builds up the number as char string, in the neutral format that
// will be acceptable to the decNumber library, then at the end passes that string
// off for conversion to a decNumber.
UErrorCode err = U_ZERO_ERROR;
CharString parsedNum;
digits.setToZero();
int32_t position = parsePosition.getIndex();
int32_t oldStart = position;
UBool strictParse = !isLenient();
// Match padding before prefix
if (fFormatWidth > 0 && fPadPosition == kPadBeforePrefix) {
position = skipPadding(text, position);
}
// Match positive and negative prefixes; prefer longest match.
int32_t posMatch = compareAffix(text, position, FALSE, TRUE, posPrefix, currencyParsing, type, currency);
int32_t negMatch = compareAffix(text, position, TRUE, TRUE, negPrefix, currencyParsing, type, currency);
if (posMatch >= 0 && negMatch >= 0) {
if (posMatch > negMatch) {
negMatch = -1;
} else if (negMatch > posMatch) {
posMatch = -1;
}
}
if (posMatch >= 0) {
position += posMatch;
parsedNum.append('+', err);
} else if (negMatch >= 0) {
position += negMatch;
parsedNum.append('-', err);
} else if (strictParse){
parsePosition.setErrorIndex(position);
return FALSE;
}
// Match padding before prefix
if (fFormatWidth > 0 && fPadPosition == kPadAfterPrefix) {
position = skipPadding(text, position);
}
if (! strictParse) {
position = skipUWhiteSpace(text, position);
}
// process digits or Inf, find decimal position
const UnicodeString *inf = &getConstSymbol(DecimalFormatSymbols::kInfinitySymbol);
int32_t infLen = (text.compare(position, inf->length(), *inf)
? 0 : inf->length());
position += infLen; // infLen is non-zero when it does equal to infinity
status[fgStatusInfinite] = infLen != 0;
if (infLen != 0) {
parsedNum.append("Infinity", err);
} else {
// We now have a string of digits, possibly with grouping symbols,
// and decimal points. We want to process these into a DigitList.
// We don't want to put a bunch of leading zeros into the DigitList
// though, so we keep track of the location of the decimal point,
// put only significant digits into the DigitList, and adjust the
// exponent as needed.
UChar32 zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
UBool strictFail = FALSE; // did we exit with a strict parse failure?
int32_t lastGroup = -1; // where did we last see a grouping separator?
int32_t digitStart = position;
int32_t gs2 = fGroupingSize2 == 0 ? fGroupingSize : fGroupingSize2;
const UnicodeString *decimalString;
if (fCurrencySignCount > fgCurrencySignCountZero) {
decimalString = &getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol);
} else {
decimalString = &getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
UChar32 decimalChar = decimalString->char32At(0);
const UnicodeString *groupingString = &getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
UChar32 groupingChar = groupingString->char32At(0);
UBool sawDecimal = FALSE;
UBool sawDigit = FALSE;
int32_t backup = -1;
int32_t digit;
int32_t textLength = text.length(); // One less pointer to follow
int32_t decimalStringLength = decimalString->length();
int32_t decimalCharLength = U16_LENGTH(decimalChar);
int32_t groupingStringLength = groupingString->length();
int32_t groupingCharLength = U16_LENGTH(groupingChar);
// equivalent grouping and decimal support
// TODO markdavis Cache these if it makes a difference in performance.
UnicodeSet decimalFallback;
UnicodeSet *decimalSet = NULL;
UnicodeSet *groupingSet = NULL;
if (decimalCharLength == decimalStringLength) {
decimalSet = (UnicodeSet *) DecimalFormatStaticSets::getSimilarDecimals(decimalChar, strictParse, &decimalFallback)->cloneAsThawed();
}
if (groupingCharLength == groupingStringLength) {
if (strictParse) {
groupingSet = (UnicodeSet *) DecimalFormatStaticSets::gStaticSets->fStrictDefaultGroupingSeparators->cloneAsThawed();
} else {
groupingSet = (UnicodeSet *) DecimalFormatStaticSets::gStaticSets->fDefaultGroupingSeparators->cloneAsThawed();
}
groupingSet->add(groupingChar);
if (decimalSet != NULL) {
groupingSet->removeAll(*decimalSet);
}
}
// we are guaranteed that
// decimalSet contains the decimal, and
// groupingSet contains the groupingSeparator
// (unless decimal and grouping are the same, which should never happen. But in that case, groupingSet will just be empty.)
// We have to track digitCount ourselves, because digits.fCount will
// pin when the maximum allowable digits is reached.
int32_t digitCount = 0;
int32_t integerDigitCount = 0;
for (; position < textLength; )
{
UChar32 ch = text.char32At(position);
/* We recognize all digit ranges, not only the Latin digit range
* '0'..'9'. We do so by using the Character.digit() method,
* which converts a valid Unicode digit to the range 0..9.
*
* The character 'ch' may be a digit. If so, place its value
* from 0 to 9 in 'digit'. First try using the locale digit,
* which may or MAY NOT be a standard Unicode digit range. If
* this fails, try using the standard Unicode digit ranges by
* calling Character.digit(). If this also fails, digit will
* have a value outside the range 0..9.
*/
digit = ch - zero;
if (digit < 0 || digit > 9)
{
digit = u_charDigitValue(ch);
}
// As a last resort, look through the localized digits if the zero digit
// is not a "standard" Unicode digit.
if ( (digit < 0 || digit > 9) && u_charDigitValue(zero) != 0) {
digit = 0;
if ( getConstSymbol((DecimalFormatSymbols::ENumberFormatSymbol)(DecimalFormatSymbols::kZeroDigitSymbol)).char32At(0) == ch ) {
break;
}
for (digit = 1 ; digit < 10 ; digit++ ) {
if ( getConstSymbol((DecimalFormatSymbols::ENumberFormatSymbol)(DecimalFormatSymbols::kOneDigitSymbol+digit-1)).char32At(0) == ch ) {
break;
}
}
}
if (digit >= 0 && digit <= 9)
{
if (strictParse && backup != -1) {
// comma followed by digit, so group before comma is a
// secondary group. If there was a group separator
// before that, the group must == the secondary group
// length, else it can be <= the the secondary group
// length.
if ((lastGroup != -1 && backup - lastGroup - 1 != gs2) ||
(lastGroup == -1 && position - digitStart - 1 > gs2)) {
strictFail = TRUE;
break;
}
lastGroup = backup;
}
// Cancel out backup setting (see grouping handler below)
backup = -1;
sawDigit = TRUE;
// Note: this will append leading zeros
parsedNum.append((char)(digit + '0'), err);
// count any digit that's not a leading zero
if (digit > 0 || digitCount > 0 || sawDecimal) {
digitCount += 1;
// count any integer digit that's not a leading zero
if (! sawDecimal) {
integerDigitCount += 1;
}
}
position += U16_LENGTH(ch);
}
else if (groupingStringLength > 0 && matchSymbol(text, position, groupingStringLength, *groupingString, groupingSet, ch) && isGroupingUsed())
{
if (sawDecimal) {
break;
}
if (strictParse) {
if ((!sawDigit || backup != -1)) {
// leading group, or two group separators in a row
strictFail = TRUE;
break;
}
}
// Ignore grouping characters, if we are using them, but require
// that they be followed by a digit. Otherwise we backup and
// reprocess them.
backup = position;
position += groupingStringLength;
if (groupingSet != NULL) {
// Once we see a grouping character, we only accept that grouping character from then on.
groupingSet->set(ch, ch);
}
}
else if (matchSymbol(text, position, decimalStringLength, *decimalString, decimalSet, ch))
{
if (strictParse) {
if (backup != -1 ||
(lastGroup != -1 && position - lastGroup != fGroupingSize + 1)) {
strictFail = TRUE;
break;
}
}
// If we're only parsing integers, or if we ALREADY saw the
// decimal, then don't parse this one.
if (isParseIntegerOnly() || sawDecimal) {
break;
}
parsedNum.append('.', err);
position += decimalStringLength;
sawDecimal = TRUE;
if (decimalSet != NULL) {
// Once we see a decimal character, we only accept that decimal character from then on.
decimalSet->set(ch, ch);
}
}
else {
const UnicodeString *tmp;
tmp = &getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
if (!text.caseCompare(position, tmp->length(), *tmp, U_FOLD_CASE_DEFAULT)) // error code is set below if !sawDigit
{
// Parse sign, if present
int32_t pos = position + tmp->length();
char exponentSign = '+';
if (pos < textLength)
{
tmp = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
if (!text.compare(pos, tmp->length(), *tmp))
{
pos += tmp->length();
}
else {
tmp = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
if (!text.compare(pos, tmp->length(), *tmp))
{
exponentSign = '-';
pos += tmp->length();
}
}
}
UBool sawExponentDigit = FALSE;
while (pos < textLength) {
ch = text[(int32_t)pos];
digit = ch - zero;
if (digit < 0 || digit > 9) {
digit = u_charDigitValue(ch);
}
if (0 <= digit && digit <= 9) {
if (!sawExponentDigit) {
parsedNum.append('E', err);
parsedNum.append(exponentSign, err);
sawExponentDigit = TRUE;
}
++pos;
parsedNum.append((char)(digit + '0'), err);
} else {
break;
}
}
if (sawExponentDigit) {
position = pos; // Advance past the exponent
}
break; // Whether we fail or succeed, we exit this loop
}
else {
break;
}
}
}
delete groupingSet;
delete decimalSet;
if (backup != -1)
{
position = backup;
}
if (strictParse && !sawDecimal) {
if (lastGroup != -1 && position - lastGroup != fGroupingSize + 1) {
strictFail = TRUE;
}
}
if (strictFail) {
// only set with strictParse and a grouping separator error
parsePosition.setIndex(oldStart);
parsePosition.setErrorIndex(position);
return FALSE;
}
// If there was no decimal point we have an integer
// If none of the text string was recognized. For example, parse
// "x" with pattern "#0.00" (return index and error index both 0)
// parse "$" with pattern "$#0.00". (return index 0 and error index
// 1).
if (!sawDigit && digitCount == 0) {
parsePosition.setIndex(oldStart);
parsePosition.setErrorIndex(oldStart);
return FALSE;
}
}
// Match padding before suffix
if (fFormatWidth > 0 && fPadPosition == kPadBeforeSuffix) {
position = skipPadding(text, position);
}
int32_t posSuffixMatch = -1, negSuffixMatch = -1;
// Match positive and negative suffixes; prefer longest match.
if (posMatch >= 0 || (!strictParse && negMatch < 0)) {
posSuffixMatch = compareAffix(text, position, FALSE, FALSE, posSuffix, currencyParsing, type, currency);
}
if (negMatch >= 0) {
negSuffixMatch = compareAffix(text, position, TRUE, FALSE, negSuffix, currencyParsing, type, currency);
}
if (posSuffixMatch >= 0 && negSuffixMatch >= 0) {
if (posSuffixMatch > negSuffixMatch) {
negSuffixMatch = -1;
} else if (negSuffixMatch > posSuffixMatch) {
posSuffixMatch = -1;
}
}
// Fail if neither or both
if (strictParse && ((posSuffixMatch >= 0) == (negSuffixMatch >= 0))) {
parsePosition.setErrorIndex(position);
return FALSE;
}
position += (posSuffixMatch >= 0 ? posSuffixMatch : (negSuffixMatch >= 0 ? negSuffixMatch : 0));
// Match padding before suffix
if (fFormatWidth > 0 && fPadPosition == kPadAfterSuffix) {
position = skipPadding(text, position);
}
parsePosition.setIndex(position);
parsedNum.data()[0] = (posSuffixMatch >= 0 || (!strictParse && negMatch < 0 && negSuffixMatch < 0)) ? '+' : '-';
if(parsePosition.getIndex() == oldStart)
{
parsePosition.setErrorIndex(position);
return FALSE;
}
digits.set(parsedNum.toStringPiece(), err);
if (U_FAILURE(err)) {
parsePosition.setErrorIndex(position);
return FALSE;
}
return TRUE;
}
/**
* Starting at position, advance past a run of pad characters, if any.
* Return the index of the first character after position that is not a pad
* character. Result is >= position.
*/
int32_t DecimalFormat::skipPadding(const UnicodeString& text, int32_t position) const {
int32_t padLen = U16_LENGTH(fPad);
while (position < text.length() &&
text.char32At(position) == fPad) {
position += padLen;
}
return position;
}
/**
* Return the length matched by the given affix, or -1 if none.
* Runs of white space in the affix, match runs of white space in
* the input. Pattern white space and input white space are
* determined differently; see code.
* @param text input text
* @param pos offset into input at which to begin matching
* @param isNegative
* @param isPrefix
* @param affixPat affix pattern used for currency affix comparison.
* @param currencyParsing whether it is currency parsing or not
* @param type the currency type to parse against, LONG_NAME only or not.
* @param currency return value for parsed currency, for generic
* currency parsing mode, or null for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareAffix(const UnicodeString& text,
int32_t pos,
UBool isNegative,
UBool isPrefix,
const UnicodeString* affixPat,
UBool currencyParsing,
int8_t type,
UChar* currency) const
{
const UnicodeString *patternToCompare;
if (fCurrencyChoice != NULL || currency != NULL ||
(fCurrencySignCount > fgCurrencySignCountZero && currencyParsing)) {
if (affixPat != NULL) {
return compareComplexAffix(*affixPat, text, pos, type, currency);
}
}
if (isNegative) {
if (isPrefix) {
patternToCompare = &fNegativePrefix;
}
else {
patternToCompare = &fNegativeSuffix;
}
}
else {
if (isPrefix) {
patternToCompare = &fPositivePrefix;
}
else {
patternToCompare = &fPositiveSuffix;
}
}
return compareSimpleAffix(*patternToCompare, text, pos, isLenient());
}
/**
* Return the length matched by the given affix, or -1 if none.
* Runs of white space in the affix, match runs of white space in
* the input. Pattern white space and input white space are
* determined differently; see code.
* @param affix pattern string, taken as a literal
* @param input input text
* @param pos offset into input at which to begin matching
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareSimpleAffix(const UnicodeString& affix,
const UnicodeString& input,
int32_t pos,
UBool lenient) {
UErrorCode status = U_ZERO_ERROR;
int32_t start = pos;
UChar32 affixChar = affix.char32At(0);
int32_t affixLength = affix.length();
int32_t inputLength = input.length();
int32_t affixCharLength = U16_LENGTH(affixChar);
UnicodeSet *affixSet;
DecimalFormatStaticSets::initSets(&status);
if (!lenient) {
affixSet = DecimalFormatStaticSets::gStaticSets->fStrictDashEquivalents;
// If the affix is exactly one character long and that character
// is in the dash set and the very next input character is also
// in the dash set, return a match.
if (affixCharLength == affixLength && affixSet->contains(affixChar)) {
if (affixSet->contains(input.char32At(pos))) {
return 1;
}
}
for (int32_t i = 0; i < affixLength; ) {
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 < inputLength &&
input.char32At(pos) == c) {
literalMatch = TRUE;
i += len;
pos += len;
if (i == affixLength) {
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 < inputLength &&
input.char32At(pos) == c) {
i += len;
pos += len;
} else {
return -1;
}
}
}
} else {
UBool match = FALSE;
affixSet = DecimalFormatStaticSets::gStaticSets->fDashEquivalents;
if (affixCharLength == affixLength && affixSet->contains(affixChar)) {
pos = skipUWhiteSpace(input, pos);
if (affixSet->contains(input.char32At(pos))) {
return pos - start + 1;
}
}
for (int32_t i = 0; i < affixLength; )
{
//i = skipRuleWhiteSpace(affix, i);
i = skipUWhiteSpace(affix, i);
pos = skipUWhiteSpace(input, pos);
if (i >= affixLength || pos >= inputLength) {
break;
}
UChar32 c = affix.char32At(i);
int32_t len = U16_LENGTH(c);
if (input.char32At(pos) != c) {
return -1;
}
match = TRUE;
i += len;
pos += len;
}
if (affixLength > 0 && ! match) {
return -1;
}
}
return pos - start;
}
/**
* Skip over a run of zero or more Pattern_White_Space characters at
* pos in text.
*/
int32_t DecimalFormat::skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) {
const UChar* s = text.getBuffer();
return (int32_t)(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s);
}
/**
* Skip over a run of zero or more isUWhiteSpace() characters at pos
* in text.
*/
int32_t DecimalFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) {
while (pos < text.length()) {
UChar32 c = text.char32At(pos);
if (!u_isUWhiteSpace(c)) {
break;
}
pos += U16_LENGTH(c);
}
return pos;
}
/**
* Return the length matched by the given affix, or -1 if none.
* @param affixPat pattern string
* @param input input text
* @param pos offset into input at which to begin matching
* @param type the currency type to parse against, LONG_NAME only or not.
* @param currency return value for parsed currency, for generic
* currency parsing mode, or null for normal parsing. In generic
* currency parsing mode, any currency is parsed, not just the
* currency that this formatter is set to.
* @return length of input that matches, or -1 if match failure
*/
int32_t DecimalFormat::compareComplexAffix(const UnicodeString& affixPat,
const UnicodeString& text,
int32_t pos,
int8_t type,
UChar* currency) const
{
int32_t start = pos;
U_ASSERT(currency != NULL ||
(fCurrencyChoice != NULL && *getCurrency() != 0) ||
fCurrencySignCount > fgCurrencySignCountZero);
for (int32_t i=0;
i<affixPat.length() && pos >= 0; ) {
UChar32 c = affixPat.char32At(i);
i += U16_LENGTH(c);
if (c == kQuote) {
U_ASSERT(i <= affixPat.length());
c = affixPat.char32At(i);
i += U16_LENGTH(c);
const UnicodeString* affix = NULL;
switch (c) {
case kCurrencySign: {
// since the currency names in choice format is saved
// the same way as other currency names,
// do not need to do currency choice parsing here.
// the general currency parsing parse against all names,
// including names in choice format.
UBool intl = i<affixPat.length() &&
affixPat.char32At(i) == kCurrencySign;
if (intl) {
++i;
}
UBool plural = i<affixPat.length() &&
affixPat.char32At(i) == kCurrencySign;
if (plural) {
++i;
intl = FALSE;
}
// Parse generic currency -- anything for which we
// have a display name, or any 3-letter ISO code.
// Try to parse display name for our locale; first
// determine our locale.
const char* loc = fCurrencyPluralInfo->getLocale().getName();
ParsePosition ppos(pos);
UChar curr[4];
UErrorCode ec = U_ZERO_ERROR;
// Delegate parse of display name => ISO code to Currency
uprv_parseCurrency(loc, text, ppos, type, curr, ec);
// If parse succeeds, populate currency[0]
if (U_SUCCESS(ec) && ppos.getIndex() != pos) {
if (currency) {
u_strcpy(currency, curr);
} else {
// The formatter is currency-style but the client has not requested
// the value of the parsed currency. In this case, if that value does
// not match the formatter's current value, then the parse fails.
UChar effectiveCurr[4];
getEffectiveCurrency(effectiveCurr, ec);
if ( U_FAILURE(ec) || u_strncmp(curr,effectiveCurr,4) != 0 ) {
pos = -1;
continue;
}
}
pos = ppos.getIndex();
} else if (!isLenient()){
pos = -1;
}
continue;
}
case kPatternPercent:
affix = &getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
break;
case kPatternPerMill:
affix = &getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
break;
case kPatternPlus:
affix = &getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
break;
case kPatternMinus:
affix = &getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
break;
default:
// fall through to affix!=0 test, which will fail
break;
}
if (affix != NULL) {
pos = match(text, pos, *affix);
continue;
}
}
pos = match(text, pos, c);
if (PatternProps::isWhiteSpace(c)) {
i = skipPatternWhiteSpace(affixPat, i);
}
}
return pos - start;
}
/**
* Match a single character at text[pos] and return the index of the
* next character upon success. Return -1 on failure. If
* ch is a Pattern_White_Space then match a run of white space in text.
*/
int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, UChar32 ch) {
if (PatternProps::isWhiteSpace(ch)) {
// Advance over run of white space in input text
// Must see at least one white space char in input
int32_t s = pos;
pos = skipPatternWhiteSpace(text, pos);
if (pos == s) {
return -1;
}
return pos;
}
return (pos >= 0 && text.char32At(pos) == ch) ?
(pos + U16_LENGTH(ch)) : -1;
}
/**
* Match a string at text[pos] and return the index of the next
* character upon success. Return -1 on failure. Match a run of
* white space in str with a run of white space in text.
*/
int32_t DecimalFormat::match(const UnicodeString& text, int32_t pos, const UnicodeString& str) {
for (int32_t i=0; i<str.length() && pos >= 0; ) {
UChar32 ch = str.char32At(i);
i += U16_LENGTH(ch);
if (PatternProps::isWhiteSpace(ch)) {
i = skipPatternWhiteSpace(str, i);
}
pos = match(text, pos, ch);
}
return pos;
}
UBool DecimalFormat::matchSymbol(const UnicodeString &text, int32_t position, int32_t length, const UnicodeString &symbol,
UnicodeSet *sset, UChar32 schar)
{
if (sset != NULL) {
return sset->contains(schar);
}
return text.compare(position, length, symbol) == 0;
}
//------------------------------------------------------------------------------
// Gets the pointer to the localized decimal format symbols
const DecimalFormatSymbols*
DecimalFormat::getDecimalFormatSymbols() const
{
return fSymbols;
}
//------------------------------------------------------------------------------
// De-owning the current localized symbols and adopt the new symbols.
void
DecimalFormat::adoptDecimalFormatSymbols(DecimalFormatSymbols* symbolsToAdopt)
{
if (symbolsToAdopt == NULL) {
return; // do not allow caller to set fSymbols to NULL
}
UBool sameSymbols = FALSE;
if (fSymbols != NULL) {
sameSymbols = (UBool)(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) ==
symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) &&
getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) ==
symbolsToAdopt->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
delete fSymbols;
}
fSymbols = symbolsToAdopt;
if (!sameSymbols) {
// If the currency symbols are the same, there is no need to recalculate.
setCurrencyForSymbols();
}
expandAffixes(NULL);
}
//------------------------------------------------------------------------------
// Setting the symbols is equlivalent to adopting a newly created localized
// symbols.
void
DecimalFormat::setDecimalFormatSymbols(const DecimalFormatSymbols& symbols)
{
adoptDecimalFormatSymbols(new DecimalFormatSymbols(symbols));
}
const CurrencyPluralInfo*
DecimalFormat::getCurrencyPluralInfo(void) const
{
return fCurrencyPluralInfo;
}
void
DecimalFormat::adoptCurrencyPluralInfo(CurrencyPluralInfo* toAdopt)
{
if (toAdopt != NULL) {
delete fCurrencyPluralInfo;
fCurrencyPluralInfo = toAdopt;
// re-set currency affix patterns and currency affixes.
if (fCurrencySignCount > fgCurrencySignCountZero) {
UErrorCode status = U_ZERO_ERROR;
if (fAffixPatternsForCurrency) {
deleteHashForAffixPattern();
}
setupCurrencyAffixPatterns(status);
if (fCurrencySignCount == fgCurrencySignCountInPluralFormat) {
// only setup the affixes of the plural pattern.
setupCurrencyAffixes(fFormatPattern, FALSE, TRUE, status);
}
}
}
}
void
DecimalFormat::setCurrencyPluralInfo(const CurrencyPluralInfo& info)
{
adoptCurrencyPluralInfo(info.clone());
}
/**
* Update the currency object to match the symbols. This method
* is used only when the caller has passed in a symbols object
* that may not be the default object for its locale.
*/
void
DecimalFormat::setCurrencyForSymbols() {
/*Bug 4212072
Update the affix strings accroding to symbols in order to keep
the affix strings up to date.
[Richard/GCL]
*/
// With the introduction of the Currency object, the currency
// symbols in the DFS object are ignored. For backward
// compatibility, we check any explicitly set DFS object. If it
// is a default symbols object for its locale, we change the
// currency object to one for that locale. If it is custom,
// we set the currency to null.
UErrorCode ec = U_ZERO_ERROR;
const UChar* c = NULL;
const char* loc = fSymbols->getLocale().getName();
UChar intlCurrencySymbol[4];
ucurr_forLocale(loc, intlCurrencySymbol, 4, &ec);
UnicodeString currencySymbol;
uprv_getStaticCurrencyName(intlCurrencySymbol, loc, currencySymbol, ec);
if (U_SUCCESS(ec)
&& getConstSymbol(DecimalFormatSymbols::kCurrencySymbol) == currencySymbol
&& getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol) == UnicodeString(intlCurrencySymbol))
{
// Trap an error in mapping locale to currency. If we can't
// map, then don't fail and set the currency to "".
c = intlCurrencySymbol;
}
ec = U_ZERO_ERROR; // reset local error code!
setCurrencyInternally(c, ec);
}
//------------------------------------------------------------------------------
// Gets the positive prefix of the number pattern.
UnicodeString&
DecimalFormat::getPositivePrefix(UnicodeString& result) const
{
result = fPositivePrefix;
return result;
}
//------------------------------------------------------------------------------
// Sets the positive prefix of the number pattern.
void
DecimalFormat::setPositivePrefix(const UnicodeString& newValue)
{
fPositivePrefix = newValue;
delete fPosPrefixPattern;
fPosPrefixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the negative prefix of the number pattern.
UnicodeString&
DecimalFormat::getNegativePrefix(UnicodeString& result) const
{
result = fNegativePrefix;
return result;
}
//------------------------------------------------------------------------------
// Gets the negative prefix of the number pattern.
void
DecimalFormat::setNegativePrefix(const UnicodeString& newValue)
{
fNegativePrefix = newValue;
delete fNegPrefixPattern;
fNegPrefixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the positive suffix of the number pattern.
UnicodeString&
DecimalFormat::getPositiveSuffix(UnicodeString& result) const
{
result = fPositiveSuffix;
return result;
}
//------------------------------------------------------------------------------
// Sets the positive suffix of the number pattern.
void
DecimalFormat::setPositiveSuffix(const UnicodeString& newValue)
{
fPositiveSuffix = newValue;
delete fPosSuffixPattern;
fPosSuffixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the negative suffix of the number pattern.
UnicodeString&
DecimalFormat::getNegativeSuffix(UnicodeString& result) const
{
result = fNegativeSuffix;
return result;
}
//------------------------------------------------------------------------------
// Sets the negative suffix of the number pattern.
void
DecimalFormat::setNegativeSuffix(const UnicodeString& newValue)
{
fNegativeSuffix = newValue;
delete fNegSuffixPattern;
fNegSuffixPattern = 0;
}
//------------------------------------------------------------------------------
// Gets the multiplier of the number pattern.
// Multipliers are stored as decimal numbers (DigitLists) because that
// is the most convenient for muliplying or dividing the numbers to be formatted.
// A NULL multiplier implies one, and the scaling operations are skipped.
int32_t
DecimalFormat::getMultiplier() const
{
if (fMultiplier == NULL) {
return 1;
} else {
return fMultiplier->getLong();
}
}
//------------------------------------------------------------------------------
// Sets the multiplier of the number pattern.
void
DecimalFormat::setMultiplier(int32_t newValue)
{
// if (newValue == 0) {
// throw new IllegalArgumentException("Bad multiplier: " + newValue);
// }
if (newValue == 0) {
newValue = 1; // one being the benign default value for a multiplier.
}
if (newValue == 1) {
delete fMultiplier;
fMultiplier = NULL;
} else {
if (fMultiplier == NULL) {
fMultiplier = new DigitList;
}
if (fMultiplier != NULL) {
fMultiplier->set(newValue);
}
}
}
/**
* Get the rounding increment.
* @return A positive rounding increment, or 0.0 if rounding
* is not in effect.
* @see #setRoundingIncrement
* @see #getRoundingMode
* @see #setRoundingMode
*/
double DecimalFormat::getRoundingIncrement() const {
if (fRoundingIncrement == NULL) {
return 0.0;
} else {
return fRoundingIncrement->getDouble();
}
}
/**
* Set the rounding increment. This method also controls whether
* rounding is enabled.
* @param newValue A positive rounding increment, or 0.0 to disable rounding.
* Negative increments are equivalent to 0.0.
* @see #getRoundingIncrement
* @see #getRoundingMode
* @see #setRoundingMode
*/
void DecimalFormat::setRoundingIncrement(double newValue) {
if (newValue > 0.0) {
if (fRoundingIncrement == NULL) {
fRoundingIncrement = new DigitList();
}
if (fRoundingIncrement != NULL) {
fRoundingIncrement->set(newValue);
return;
}
}
// These statements are executed if newValue is less than 0.0
// or fRoundingIncrement could not be created.
delete fRoundingIncrement;
fRoundingIncrement = NULL;
}
/**
* Get the rounding mode.
* @return A rounding mode
* @see #setRoundingIncrement
* @see #getRoundingIncrement
* @see #setRoundingMode
*/
DecimalFormat::ERoundingMode DecimalFormat::getRoundingMode() const {
return fRoundingMode;
}
/**
* Set the rounding mode. This has no effect unless the rounding
* increment is greater than zero.
* @param roundingMode A rounding mode
* @see #setRoundingIncrement
* @see #getRoundingIncrement
* @see #getRoundingMode
*/
void DecimalFormat::setRoundingMode(ERoundingMode roundingMode) {
fRoundingMode = roundingMode;
}
/**
* Get the width to which the output of <code>format()</code> is padded.
* @return the format width, or zero if no padding is in effect
* @see #setFormatWidth
* @see #getPadCharacter
* @see #setPadCharacter
* @see #getPadPosition
* @see #setPadPosition
*/
int32_t DecimalFormat::getFormatWidth() const {
return fFormatWidth;
}
/**
* Set the width to which the output of <code>format()</code> is padded.
* This method also controls whether padding is enabled.
* @param width the width to which to pad the result of
* <code>format()</code>, or zero to disable padding. A negative
* width is equivalent to 0.
* @see #getFormatWidth
* @see #getPadCharacter
* @see #setPadCharacter
* @see #getPadPosition
* @see #setPadPosition
*/
void DecimalFormat::setFormatWidth(int32_t width) {
fFormatWidth = (width > 0) ? width : 0;
}
UnicodeString DecimalFormat::getPadCharacterString() const {
return UnicodeString(fPad);
}
void DecimalFormat::setPadCharacter(const UnicodeString &padChar) {
if (padChar.length() > 0) {
fPad = padChar.char32At(0);
}
else {
fPad = kDefaultPad;
}
}
/**
* Get the position at which padding will take place. This is the location
* at which padding will be inserted if the result of <code>format()</code>
* is shorter than the format width.
* @return the pad position, one of <code>kPadBeforePrefix</code>,
* <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
* <code>kPadAfterSuffix</code>.
* @see #setFormatWidth
* @see #getFormatWidth
* @see #setPadCharacter
* @see #getPadCharacter
* @see #setPadPosition
* @see #kPadBeforePrefix
* @see #kPadAfterPrefix
* @see #kPadBeforeSuffix
* @see #kPadAfterSuffix
*/
DecimalFormat::EPadPosition DecimalFormat::getPadPosition() const {
return fPadPosition;
}
/**
* <strong><font face=helvetica color=red>NEW</font></strong>
* Set the position at which padding will take place. This is the location
* at which padding will be inserted if the result of <code>format()</code>
* is shorter than the format width. This has no effect unless padding is
* enabled.
* @param padPos the pad position, one of <code>kPadBeforePrefix</code>,
* <code>kPadAfterPrefix</code>, <code>kPadBeforeSuffix</code>, or
* <code>kPadAfterSuffix</code>.
* @see #setFormatWidth
* @see #getFormatWidth
* @see #setPadCharacter
* @see #getPadCharacter
* @see #getPadPosition
* @see #kPadBeforePrefix
* @see #kPadAfterPrefix
* @see #kPadBeforeSuffix
* @see #kPadAfterSuffix
*/
void DecimalFormat::setPadPosition(EPadPosition padPos) {
fPadPosition = padPos;
}
/**
* Return whether or not scientific notation is used.
* @return TRUE if this object formats and parses scientific notation
* @see #setScientificNotation
* @see #getMinimumExponentDigits
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
UBool DecimalFormat::isScientificNotation() {
return fUseExponentialNotation;
}
/**
* Set whether or not scientific notation is used.
* @param useScientific TRUE if this object formats and parses scientific
* notation
* @see #isScientificNotation
* @see #getMinimumExponentDigits
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
void DecimalFormat::setScientificNotation(UBool useScientific) {
fUseExponentialNotation = useScientific;
}
/**
* Return the minimum exponent digits that will be shown.
* @return the minimum exponent digits that will be shown
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
int8_t DecimalFormat::getMinimumExponentDigits() const {
return fMinExponentDigits;
}
/**
* Set the minimum exponent digits that will be shown. This has no
* effect unless scientific notation is in use.
* @param minExpDig a value >= 1 indicating the fewest exponent digits
* that will be shown. Values less than 1 will be treated as 1.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #getMinimumExponentDigits
* @see #isExponentSignAlwaysShown
* @see #setExponentSignAlwaysShown
*/
void DecimalFormat::setMinimumExponentDigits(int8_t minExpDig) {
fMinExponentDigits = (int8_t)((minExpDig > 0) ? minExpDig : 1);
}
/**
* Return whether the exponent sign is always shown.
* @return TRUE if the exponent is always prefixed with either the
* localized minus sign or the localized plus sign, false if only negative
* exponents are prefixed with the localized minus sign.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #getMinimumExponentDigits
* @see #setExponentSignAlwaysShown
*/
UBool DecimalFormat::isExponentSignAlwaysShown() {
return fExponentSignAlwaysShown;
}
/**
* Set whether the exponent sign is always shown. This has no effect
* unless scientific notation is in use.
* @param expSignAlways TRUE if the exponent is always prefixed with either
* the localized minus sign or the localized plus sign, false if only
* negative exponents are prefixed with the localized minus sign.
* @see #setScientificNotation
* @see #isScientificNotation
* @see #setMinimumExponentDigits
* @see #getMinimumExponentDigits
* @see #isExponentSignAlwaysShown
*/
void DecimalFormat::setExponentSignAlwaysShown(UBool expSignAlways) {
fExponentSignAlwaysShown = expSignAlways;
}
//------------------------------------------------------------------------------
// Gets the grouping size of the number pattern. For example, thousand or 10
// thousand groupings.
int32_t
DecimalFormat::getGroupingSize() const
{
return fGroupingSize;
}
//------------------------------------------------------------------------------
// Gets the grouping size of the number pattern.
void
DecimalFormat::setGroupingSize(int32_t newValue)
{
fGroupingSize = newValue;
}
//------------------------------------------------------------------------------
int32_t
DecimalFormat::getSecondaryGroupingSize() const
{
return fGroupingSize2;
}
//------------------------------------------------------------------------------
void
DecimalFormat::setSecondaryGroupingSize(int32_t newValue)
{
fGroupingSize2 = newValue;
}
//------------------------------------------------------------------------------
// Checks if to show the decimal separator.
UBool
DecimalFormat::isDecimalSeparatorAlwaysShown() const
{
return fDecimalSeparatorAlwaysShown;
}
//------------------------------------------------------------------------------
// Sets to always show the decimal separator.
void
DecimalFormat::setDecimalSeparatorAlwaysShown(UBool newValue)
{
fDecimalSeparatorAlwaysShown = newValue;
}
//------------------------------------------------------------------------------
// Emits the pattern of this DecimalFormat instance.
UnicodeString&
DecimalFormat::toPattern(UnicodeString& result) const
{
return toPattern(result, FALSE);
}
//------------------------------------------------------------------------------
// Emits the localized pattern this DecimalFormat instance.
UnicodeString&
DecimalFormat::toLocalizedPattern(UnicodeString& result) const
{
return toPattern(result, TRUE);
}
//------------------------------------------------------------------------------
/**
* Expand the affix pattern strings into the expanded affix strings. If any
* affix pattern string is null, do not expand it. This method should be
* called any time the symbols or the affix patterns change in order to keep
* the expanded affix strings up to date.
* This method also will be called before formatting if format currency
* plural names, since the plural name is not a static one, it is
* based on the currency plural count, the affix will be known only
* after the currency plural count is know.
* In which case, the parameter
* 'pluralCount' will be a non-null currency plural count.
* In all other cases, the 'pluralCount' is null, which means it is not needed.
*/
void DecimalFormat::expandAffixes(const UnicodeString* pluralCount) {
FieldPositionHandler none;
if (fPosPrefixPattern != 0) {
expandAffix(*fPosPrefixPattern, fPositivePrefix, 0, none, FALSE, pluralCount);
}
if (fPosSuffixPattern != 0) {
expandAffix(*fPosSuffixPattern, fPositiveSuffix, 0, none, FALSE, pluralCount);
}
if (fNegPrefixPattern != 0) {
expandAffix(*fNegPrefixPattern, fNegativePrefix, 0, none, FALSE, pluralCount);
}
if (fNegSuffixPattern != 0) {
expandAffix(*fNegSuffixPattern, fNegativeSuffix, 0, none, FALSE, pluralCount);
}
#ifdef FMT_DEBUG
UnicodeString s;
s.append("[")
.append(*fPosPrefixPattern).append("|").append(*fPosSuffixPattern)
.append(";") .append(*fNegPrefixPattern).append("|").append(*fNegSuffixPattern)
.append("]->[")
.append(fPositivePrefix).append("|").append(fPositiveSuffix)
.append(";") .append(fNegativePrefix).append("|").append(fNegativeSuffix)
.append("]\n");
debugout(s);
#endif
}
/**
* Expand an affix pattern into an affix string. All characters in the
* pattern are literal unless prefixed by kQuote. The following characters
* after kQuote are recognized: PATTERN_PERCENT, PATTERN_PER_MILLE,
* PATTERN_MINUS, and kCurrencySign. If kCurrencySign is doubled (kQuote +
* kCurrencySign + kCurrencySign), it is interpreted as an international
* currency sign. If CURRENCY_SIGN is tripled, it is interpreted as
* currency plural long names, such as "US Dollars".
* Any other character after a kQuote represents itself.
* kQuote must be followed by another character; kQuote may not occur by
* itself at the end of the pattern.
*
* This method is used in two distinct ways. First, it is used to expand
* the stored affix patterns into actual affixes. For this usage, doFormat
* must be false. Second, it is used to expand the stored affix patterns
* given a specific number (doFormat == true), for those rare cases in
* which a currency format references a ChoiceFormat (e.g., en_IN display
* name for INR). The number itself is taken from digitList.
*
* When used in the first way, this method has a side effect: It sets
* currencyChoice to a ChoiceFormat object, if the currency's display name
* in this locale is a ChoiceFormat pattern (very rare). It only does this
* if currencyChoice is null to start with.
*
* @param pattern the non-null, fPossibly empty pattern
* @param affix string to receive the expanded equivalent of pattern.
* Previous contents are deleted.
* @param doFormat if false, then the pattern will be expanded, and if a
* currency symbol is encountered that expands to a ChoiceFormat, the
* currencyChoice member variable will be initialized if it is null. If
* doFormat is true, then it is assumed that the currencyChoice has been
* created, and it will be used to format the value in digitList.
* @param pluralCount the plural count. It is only used for currency
* plural format. In which case, it is the plural
* count of the currency amount. For example,
* in en_US, it is the singular "one", or the plural
* "other". For all other cases, it is null, and
* is not being used.
*/
void DecimalFormat::expandAffix(const UnicodeString& pattern,
UnicodeString& affix,
double number,
FieldPositionHandler& handler,
UBool doFormat,
const UnicodeString* pluralCount) const {
affix.remove();
for (int i=0; i<pattern.length(); ) {
UChar32 c = pattern.char32At(i);
i += U16_LENGTH(c);
if (c == kQuote) {
c = pattern.char32At(i);
i += U16_LENGTH(c);
int beginIdx = affix.length();
switch (c) {
case kCurrencySign: {
// As of ICU 2.2 we use the currency object, and
// ignore the currency symbols in the DFS, unless
// we have a null currency object. This occurs if
// resurrecting a pre-2.2 object or if the user
// sets a custom DFS.
UBool intl = i<pattern.length() &&
pattern.char32At(i) == kCurrencySign;
UBool plural = FALSE;
if (intl) {
++i;
plural = i<pattern.length() &&
pattern.char32At(i) == kCurrencySign;
if (plural) {
intl = FALSE;
++i;
}
}
const UChar* currencyUChars = getCurrency();
if (currencyUChars[0] != 0) {
UErrorCode ec = U_ZERO_ERROR;
if (plural && pluralCount != NULL) {
// plural name is only needed when pluralCount != null,
// which means when formatting currency plural names.
// For other cases, pluralCount == null,
// and plural names are not needed.
int32_t len;
CharString pluralCountChar;
pluralCountChar.appendInvariantChars(*pluralCount, ec);
UBool isChoiceFormat;
const UChar* s = ucurr_getPluralName(currencyUChars,
fSymbols != NULL ? fSymbols->getLocale().getName() :
Locale::getDefault().getName(), &isChoiceFormat,
pluralCountChar.data(), &len, &ec);
affix += UnicodeString(s, len);
handler.addAttribute(kCurrencyField, beginIdx, affix.length());
} else if(intl) {
affix.append(currencyUChars, -1);
handler.addAttribute(kCurrencyField, beginIdx, affix.length());
} else {
int32_t len;
UBool isChoiceFormat;
// If fSymbols is NULL, use default locale
const UChar* s = ucurr_getName(currencyUChars,
fSymbols != NULL ? fSymbols->getLocale().getName() : Locale::getDefault().getName(),
UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec);
if (isChoiceFormat) {
// Two modes here: If doFormat is false, we set up
// currencyChoice. If doFormat is true, we use the
// previously created currencyChoice to format the
// value in digitList.
if (!doFormat) {
// If the currency is handled by a ChoiceFormat,
// then we're not going to use the expanded
// patterns. Instantiate the ChoiceFormat and
// return.
if (fCurrencyChoice == NULL) {
// TODO Replace double-check with proper thread-safe code
ChoiceFormat* fmt = new ChoiceFormat(UnicodeString(s), ec);
if (U_SUCCESS(ec)) {
umtx_lock(NULL);
if (fCurrencyChoice == NULL) {
// Cast away const
((DecimalFormat*)this)->fCurrencyChoice = fmt;
fmt = NULL;
}
umtx_unlock(NULL);
delete fmt;
}
}
// We could almost return null or "" here, since the
// expanded affixes are almost not used at all
// in this situation. However, one method --
// toPattern() -- still does use the expanded
// affixes, in order to set up a padding
// pattern. We use the CURRENCY_SIGN as a
// placeholder.
affix.append(kCurrencySign);
} else {
if (fCurrencyChoice != NULL) {
FieldPosition pos(0); // ignored
if (number < 0) {
number = -number;
}
fCurrencyChoice->format(number, affix, pos);
} else {
// We only arrive here if the currency choice
// format in the locale data is INVALID.
affix.append(currencyUChars, -1);
handler.addAttribute(kCurrencyField, beginIdx, affix.length());
}
}
continue;
}
affix += UnicodeString(s, len);
handler.addAttribute(kCurrencyField, beginIdx, affix.length());
}
} else {
if(intl) {
affix += getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
} else {
affix += getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
}
handler.addAttribute(kCurrencyField, beginIdx, affix.length());
}
break;
}
case kPatternPercent:
affix += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
handler.addAttribute(kPercentField, beginIdx, affix.length());
break;
case kPatternPerMill:
affix += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
handler.addAttribute(kPermillField, beginIdx, affix.length());
break;
case kPatternPlus:
affix += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
handler.addAttribute(kSignField, beginIdx, affix.length());
break;
case kPatternMinus:
affix += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
handler.addAttribute(kSignField, beginIdx, affix.length());
break;
default:
affix.append(c);
break;
}
}
else {
affix.append(c);
}
}
}
/**
* Append an affix to the given StringBuffer.
* @param buf buffer to append to
* @param isNegative
* @param isPrefix
*/
int32_t DecimalFormat::appendAffix(UnicodeString& buf, double number,
FieldPositionHandler& handler,
UBool isNegative, UBool isPrefix) const {
// plural format precedes choice format
if (fCurrencyChoice != 0 &&
fCurrencySignCount != fgCurrencySignCountInPluralFormat) {
const UnicodeString* affixPat;
if (isPrefix) {
affixPat = isNegative ? fNegPrefixPattern : fPosPrefixPattern;
} else {
affixPat = isNegative ? fNegSuffixPattern : fPosSuffixPattern;
}
if (affixPat) {
UnicodeString affixBuf;
expandAffix(*affixPat, affixBuf, number, handler, TRUE, NULL);
buf.append(affixBuf);
return affixBuf.length();
}
// else someone called a function that reset the pattern.
}
const UnicodeString* affix;
if (fCurrencySignCount == fgCurrencySignCountInPluralFormat) {
UnicodeString pluralCount = fCurrencyPluralInfo->getPluralRules()->select(number);
AffixesForCurrency* oneSet;
if (fStyle == UNUM_CURRENCY_PLURAL) {
oneSet = (AffixesForCurrency*)fPluralAffixesForCurrency->get(pluralCount);
} else {
oneSet = (AffixesForCurrency*)fAffixesForCurrency->get(pluralCount);
}
if (isPrefix) {
affix = isNegative ? &oneSet->negPrefixForCurrency :
&oneSet->posPrefixForCurrency;
} else {
affix = isNegative ? &oneSet->negSuffixForCurrency :
&oneSet->posSuffixForCurrency;
}
} else {
if (isPrefix) {
affix = isNegative ? &fNegativePrefix : &fPositivePrefix;
} else {
affix = isNegative ? &fNegativeSuffix : &fPositiveSuffix;
}
}
int32_t begin = (int) buf.length();
buf.append(*affix);
if (handler.isRecording()) {
int32_t offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kCurrencySymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kCurrencySymbol);
handler.addAttribute(kCurrencyField, begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
handler.addAttribute(kCurrencyField, begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
handler.addAttribute(kSignField, begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
handler.addAttribute(kPercentField, begin + offset, begin + offset + aff.length());
}
offset = (int) (*affix).indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
if (offset > -1) {
UnicodeString aff = getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
handler.addAttribute(kPermillField, begin + offset, begin + offset + aff.length());
}
}
return affix->length();
}
/**
* Appends an affix pattern to the given StringBuffer, quoting special
* characters as needed. Uses the internal affix pattern, if that exists,
* or the literal affix, if the internal affix pattern is null. The
* appended string will generate the same affix pattern (or literal affix)
* when passed to toPattern().
*
* @param appendTo the affix string is appended to this
* @param affixPattern a pattern such as fPosPrefixPattern; may be null
* @param expAffix a corresponding expanded affix, such as fPositivePrefix.
* Ignored unless affixPattern is null. If affixPattern is null, then
* expAffix is appended as a literal affix.
* @param localized true if the appended pattern should contain localized
* pattern characters; otherwise, non-localized pattern chars are appended
*/
void DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
const UnicodeString* affixPattern,
const UnicodeString& expAffix,
UBool localized) const {
if (affixPattern == 0) {
appendAffixPattern(appendTo, expAffix, localized);
} else {
int i;
for (int pos=0; pos<affixPattern->length(); pos=i) {
i = affixPattern->indexOf(kQuote, pos);
if (i < 0) {
UnicodeString s;
affixPattern->extractBetween(pos, affixPattern->length(), s);
appendAffixPattern(appendTo, s, localized);
break;
}
if (i > pos) {
UnicodeString s;
affixPattern->extractBetween(pos, i, s);
appendAffixPattern(appendTo, s, localized);
}
UChar32 c = affixPattern->char32At(++i);
++i;
if (c == kQuote) {
appendTo.append(c).append(c);
// Fall through and append another kQuote below
} else if (c == kCurrencySign &&
i<affixPattern->length() &&
affixPattern->char32At(i) == kCurrencySign) {
++i;
appendTo.append(c).append(c);
} else if (localized) {
switch (c) {
case kPatternPercent:
appendTo += getConstSymbol(DecimalFormatSymbols::kPercentSymbol);
break;
case kPatternPerMill:
appendTo += getConstSymbol(DecimalFormatSymbols::kPerMillSymbol);
break;
case kPatternPlus:
appendTo += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
break;
case kPatternMinus:
appendTo += getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol);
break;
default:
appendTo.append(c);
}
} else {
appendTo.append(c);
}
}
}
}
/**
* Append an affix to the given StringBuffer, using quotes if
* there are special characters. Single quotes themselves must be
* escaped in either case.
*/
void
DecimalFormat::appendAffixPattern(UnicodeString& appendTo,
const UnicodeString& affix,
UBool localized) const {
UBool needQuote;
if(localized) {
needQuote = affix.indexOf(getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPercentSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kDigitSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol)) >= 0
|| affix.indexOf(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) >= 0
|| affix.indexOf(kCurrencySign) >= 0;
}
else {
needQuote = affix.indexOf(kPatternZeroDigit) >= 0
|| affix.indexOf(kPatternGroupingSeparator) >= 0
|| affix.indexOf(kPatternDecimalSeparator) >= 0
|| affix.indexOf(kPatternPercent) >= 0
|| affix.indexOf(kPatternPerMill) >= 0
|| affix.indexOf(kPatternDigit) >= 0
|| affix.indexOf(kPatternSeparator) >= 0
|| affix.indexOf(kPatternExponent) >= 0
|| affix.indexOf(kPatternPlus) >= 0
|| affix.indexOf(kPatternMinus) >= 0
|| affix.indexOf(kCurrencySign) >= 0;
}
if (needQuote)
appendTo += (UChar)0x0027 /*'\''*/;
if (affix.indexOf((UChar)0x0027 /*'\''*/) < 0)
appendTo += affix;
else {
for (int32_t j = 0; j < affix.length(); ) {
UChar32 c = affix.char32At(j);
j += U16_LENGTH(c);
appendTo += c;
if (c == 0x0027 /*'\''*/)
appendTo += c;
}
}
if (needQuote)
appendTo += (UChar)0x0027 /*'\''*/;
}
//------------------------------------------------------------------------------
UnicodeString&
DecimalFormat::toPattern(UnicodeString& result, UBool localized) const
{
if (fStyle == UNUM_CURRENCY_PLURAL) {
// the prefix or suffix pattern might not be defined yet,
// so they can not be synthesized,
// instead, get them directly.
// but it might not be the actual pattern used in formatting.
// the actual pattern used in formatting depends on the
// formatted number's plural count.
result = fFormatPattern;
return result;
}
result.remove();
UChar32 zero, sigDigit = kPatternSignificantDigit;
UnicodeString digit, group;
int32_t i;
int32_t roundingDecimalPos = 0; // Pos of decimal in roundingDigits
UnicodeString roundingDigits;
int32_t padPos = (fFormatWidth > 0) ? fPadPosition : -1;
UnicodeString padSpec;
UBool useSigDig = areSignificantDigitsUsed();
if (localized) {
digit.append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
group.append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
zero = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
if (useSigDig) {
sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
}
}
else {
digit.append((UChar)kPatternDigit);
group.append((UChar)kPatternGroupingSeparator);
zero = (UChar32)kPatternZeroDigit;
}
if (fFormatWidth > 0) {
if (localized) {
padSpec.append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
}
else {
padSpec.append((UChar)kPatternPadEscape);
}
padSpec.append(fPad);
}
if (fRoundingIncrement != NULL) {
for(i=0; i<fRoundingIncrement->getCount(); ++i) {
roundingDigits.append(zero+(fRoundingIncrement->getDigitValue(i))); // Convert to Unicode digit
}
roundingDecimalPos = fRoundingIncrement->getDecimalAt();
}
for (int32_t part=0; part<2; ++part) {
if (padPos == kPadBeforePrefix) {
result.append(padSpec);
}
appendAffixPattern(result,
(part==0 ? fPosPrefixPattern : fNegPrefixPattern),
(part==0 ? fPositivePrefix : fNegativePrefix),
localized);
if (padPos == kPadAfterPrefix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
int32_t sub0Start = result.length();
int32_t g = isGroupingUsed() ? _max(0, fGroupingSize) : 0;
if (g > 0 && fGroupingSize2 > 0 && fGroupingSize2 != fGroupingSize) {
g += fGroupingSize2;
}
int32_t maxDig = 0, minDig = 0, maxSigDig = 0;
if (useSigDig) {
minDig = getMinimumSignificantDigits();
maxDig = maxSigDig = getMaximumSignificantDigits();
} else {
minDig = getMinimumIntegerDigits();
maxDig = getMaximumIntegerDigits();
}
if (fUseExponentialNotation) {
if (maxDig > kMaxScientificIntegerDigits) {
maxDig = 1;
}
} else if (useSigDig) {
maxDig = _max(maxDig, g+1);
} else {
maxDig = _max(_max(g, getMinimumIntegerDigits()),
roundingDecimalPos) + 1;
}
for (i = maxDig; i > 0; --i) {
if (!fUseExponentialNotation && i<maxDig &&
isGroupingPosition(i)) {
result.append(group);
}
if (useSigDig) {
// #@,@### (maxSigDig == 5, minSigDig == 2)
// 65 4321 (1-based pos, count from the right)
// Use # if pos > maxSigDig or 1 <= pos <= (maxSigDig - minSigDig)
// Use @ if (maxSigDig - minSigDig) < pos <= maxSigDig
if (maxSigDig >= i && i > (maxSigDig - minDig)) {
result.append(sigDigit);
} else {
result.append(digit);
}
} else {
if (! roundingDigits.isEmpty()) {
int32_t pos = roundingDecimalPos - i;
if (pos >= 0 && pos < roundingDigits.length()) {
result.append((UChar) (roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
continue;
}
}
if (i<=minDig) {
result.append(zero);
} else {
result.append(digit);
}
}
}
if (!useSigDig) {
if (getMaximumFractionDigits() > 0 || fDecimalSeparatorAlwaysShown) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
}
else {
result.append((UChar)kPatternDecimalSeparator);
}
}
int32_t pos = roundingDecimalPos;
for (i = 0; i < getMaximumFractionDigits(); ++i) {
if (! roundingDigits.isEmpty() && pos < roundingDigits.length()) {
if (pos < 0) {
result.append(zero);
}
else {
result.append((UChar)(roundingDigits.char32At(pos) - kPatternZeroDigit + zero));
}
++pos;
continue;
}
if (i<getMinimumFractionDigits()) {
result.append(zero);
}
else {
result.append(digit);
}
}
}
if (fUseExponentialNotation) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kExponentialSymbol);
}
else {
result.append((UChar)kPatternExponent);
}
if (fExponentSignAlwaysShown) {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol);
}
else {
result.append((UChar)kPatternPlus);
}
}
for (i=0; i<fMinExponentDigits; ++i) {
result.append(zero);
}
}
if (! padSpec.isEmpty() && !fUseExponentialNotation) {
int32_t add = fFormatWidth - result.length() + sub0Start
- ((part == 0)
? fPositivePrefix.length() + fPositiveSuffix.length()
: fNegativePrefix.length() + fNegativeSuffix.length());
while (add > 0) {
result.insert(sub0Start, digit);
++maxDig;
--add;
// Only add a grouping separator if we have at least
// 2 additional characters to be added, so we don't
// end up with ",###".
if (add>1 && isGroupingPosition(maxDig)) {
result.insert(sub0Start, group);
--add;
}
}
}
if (fPadPosition == kPadBeforeSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
if (part == 0) {
appendAffixPattern(result, fPosSuffixPattern, fPositiveSuffix, localized);
if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
UBool isDefault = FALSE;
if ((fNegSuffixPattern == fPosSuffixPattern && // both null
fNegativeSuffix == fPositiveSuffix)
|| (fNegSuffixPattern != 0 && fPosSuffixPattern != 0 &&
*fNegSuffixPattern == *fPosSuffixPattern))
{
if (fNegPrefixPattern != NULL && fPosPrefixPattern != NULL)
{
int32_t length = fPosPrefixPattern->length();
isDefault = fNegPrefixPattern->length() == (length+2) &&
(*fNegPrefixPattern)[(int32_t)0] == kQuote &&
(*fNegPrefixPattern)[(int32_t)1] == kPatternMinus &&
fNegPrefixPattern->compare(2, length, *fPosPrefixPattern, 0, length) == 0;
}
if (!isDefault &&
fNegPrefixPattern == NULL && fPosPrefixPattern == NULL)
{
int32_t length = fPositivePrefix.length();
isDefault = fNegativePrefix.length() == (length+1) &&
fNegativePrefix.compare(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol)) == 0 &&
fNegativePrefix.compare(1, length, fPositivePrefix, 0, length) == 0;
}
}
if (isDefault) {
break; // Don't output default negative subpattern
} else {
if (localized) {
result += getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol);
}
else {
result.append((UChar)kPatternSeparator);
}
}
} else {
appendAffixPattern(result, fNegSuffixPattern, fNegativeSuffix, localized);
if (fPadPosition == kPadAfterSuffix && ! padSpec.isEmpty()) {
result.append(padSpec);
}
}
}
return result;
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPattern(const UnicodeString& pattern, UErrorCode& status)
{
UParseError parseError;
applyPattern(pattern, FALSE, parseError, status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status)
{
applyPattern(pattern, FALSE, parseError, status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern, UErrorCode& status)
{
UParseError parseError;
applyPattern(pattern, TRUE,parseError,status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyLocalizedPattern(const UnicodeString& pattern,
UParseError& parseError,
UErrorCode& status)
{
applyPattern(pattern, TRUE,parseError,status);
}
//------------------------------------------------------------------------------
void
DecimalFormat::applyPatternWithoutExpandAffix(const UnicodeString& pattern,
UBool localized,
UParseError& parseError,
UErrorCode& status)
{
if (U_FAILURE(status))
{
return;
}
// Clear error struct
parseError.offset = -1;
parseError.preContext[0] = parseError.postContext[0] = (UChar)0;
// Set the significant pattern symbols
UChar32 zeroDigit = kPatternZeroDigit; // '0'
UChar32 sigDigit = kPatternSignificantDigit; // '@'
UnicodeString groupingSeparator ((UChar)kPatternGroupingSeparator);
UnicodeString decimalSeparator ((UChar)kPatternDecimalSeparator);
UnicodeString percent ((UChar)kPatternPercent);
UnicodeString perMill ((UChar)kPatternPerMill);
UnicodeString digit ((UChar)kPatternDigit); // '#'
UnicodeString separator ((UChar)kPatternSeparator);
UnicodeString exponent ((UChar)kPatternExponent);
UnicodeString plus ((UChar)kPatternPlus);
UnicodeString minus ((UChar)kPatternMinus);
UnicodeString padEscape ((UChar)kPatternPadEscape);
// Substitute with the localized symbols if necessary
if (localized) {
zeroDigit = getConstSymbol(DecimalFormatSymbols::kZeroDigitSymbol).char32At(0);
sigDigit = getConstSymbol(DecimalFormatSymbols::kSignificantDigitSymbol).char32At(0);
groupingSeparator. remove().append(getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol));
decimalSeparator. remove().append(getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol));
percent. remove().append(getConstSymbol(DecimalFormatSymbols::kPercentSymbol));
perMill. remove().append(getConstSymbol(DecimalFormatSymbols::kPerMillSymbol));
digit. remove().append(getConstSymbol(DecimalFormatSymbols::kDigitSymbol));
separator. remove().append(getConstSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol));
exponent. remove().append(getConstSymbol(DecimalFormatSymbols::kExponentialSymbol));
plus. remove().append(getConstSymbol(DecimalFormatSymbols::kPlusSignSymbol));
minus. remove().append(getConstSymbol(DecimalFormatSymbols::kMinusSignSymbol));
padEscape. remove().append(getConstSymbol(DecimalFormatSymbols::kPadEscapeSymbol));
}
UChar nineDigit = (UChar)(zeroDigit + 9);
int32_t digitLen = digit.length();
int32_t groupSepLen = groupingSeparator.length();
int32_t decimalSepLen = decimalSeparator.length();
int32_t pos = 0;
int32_t patLen = pattern.length();
// Part 0 is the positive pattern. Part 1, if present, is the negative
// pattern.
for (int32_t part=0; part<2 && pos<patLen; ++part) {
// The subpart ranges from 0 to 4: 0=pattern proper, 1=prefix,
// 2=suffix, 3=prefix in quote, 4=suffix in quote. Subpart 0 is
// between the prefix and suffix, and consists of pattern
// characters. In the prefix and suffix, percent, perMill, and
// currency symbols are recognized and translated.
int32_t subpart = 1, sub0Start = 0, sub0Limit = 0, sub2Limit = 0;
// It's important that we don't change any fields of this object
// prematurely. We set the following variables for the multiplier,
// grouping, etc., and then only change the actual object fields if
// everything parses correctly. This also lets us register
// the data from part 0 and ignore the part 1, except for the
// prefix and suffix.
UnicodeString prefix;
UnicodeString suffix;
int32_t decimalPos = -1;
int32_t multiplier = 1;
int32_t digitLeftCount = 0, zeroDigitCount = 0, digitRightCount = 0, sigDigitCount = 0;
int8_t groupingCount = -1;
int8_t groupingCount2 = -1;
int32_t padPos = -1;
UChar32 padChar = 0;
int32_t roundingPos = -1;
DigitList roundingInc;
int8_t expDigits = -1;
UBool expSignAlways = FALSE;
// The affix is either the prefix or the suffix.
UnicodeString* affix = &prefix;
int32_t start = pos;
UBool isPartDone = FALSE;
UChar32 ch;
for (; !isPartDone && pos < patLen; ) {
// Todo: account for surrogate pairs
ch = pattern.char32At(pos);
switch (subpart) {
case 0: // Pattern proper subpart (between prefix & suffix)
// Process the digits, decimal, and grouping characters. We
// record five pieces of information. We expect the digits
// to occur in the pattern ####00.00####, and we record the
// number of left digits, zero (central) digits, and right
// digits. The position of the last grouping character is
// recorded (should be somewhere within the first two blocks
// of characters), as is the position of the decimal point,
// if any (should be in the zero digits). If there is no
// decimal point, then there should be no right digits.
if (pattern.compare(pos, digitLen, digit) == 0) {
if (zeroDigitCount > 0 || sigDigitCount > 0) {
++digitRightCount;
} else {
++digitLeftCount;
}
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
pos += digitLen;
} else if ((ch >= zeroDigit && ch <= nineDigit) ||
ch == sigDigit) {
if (digitRightCount > 0) {
// Unexpected '0'
debug("Unexpected '0'")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
if (ch == sigDigit) {
++sigDigitCount;
} else {
++zeroDigitCount;
if (ch != zeroDigit && roundingPos < 0) {
roundingPos = digitLeftCount + zeroDigitCount;
}
if (roundingPos >= 0) {
roundingInc.append((char)(ch - zeroDigit + '0'));
}
}
if (groupingCount >= 0 && decimalPos < 0) {
++groupingCount;
}
pos += U16_LENGTH(ch);
} else if (pattern.compare(pos, groupSepLen, groupingSeparator) == 0) {
if (decimalPos >= 0) {
// Grouping separator after decimal
debug("Grouping separator after decimal")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
groupingCount2 = groupingCount;
groupingCount = 0;
pos += groupSepLen;
} else if (pattern.compare(pos, decimalSepLen, decimalSeparator) == 0) {
if (decimalPos >= 0) {
// Multiple decimal separators
debug("Multiple decimal separators")
status = U_MULTIPLE_DECIMAL_SEPARATORS;
syntaxError(pattern,pos,parseError);
return;
}
// Intentionally incorporate the digitRightCount,
// even though it is illegal for this to be > 0
// at this point. We check pattern syntax below.
decimalPos = digitLeftCount + zeroDigitCount + digitRightCount;
pos += decimalSepLen;
} else {
if (pattern.compare(pos, exponent.length(), exponent) == 0) {
if (expDigits >= 0) {
// Multiple exponential symbols
debug("Multiple exponential symbols")
status = U_MULTIPLE_EXPONENTIAL_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
if (groupingCount >= 0) {
// Grouping separator in exponential pattern
debug("Grouping separator in exponential pattern")
status = U_MALFORMED_EXPONENTIAL_PATTERN;
syntaxError(pattern,pos,parseError);
return;
}
pos += exponent.length();
// Check for positive prefix
if (pos < patLen
&& pattern.compare(pos, plus.length(), plus) == 0) {
expSignAlways = TRUE;
pos += plus.length();
}
// Use lookahead to parse out the exponential part of the
// pattern, then jump into suffix subpart.
expDigits = 0;
while (pos < patLen &&
pattern.char32At(pos) == zeroDigit) {
++expDigits;
pos += U16_LENGTH(zeroDigit);
}
// 1. Require at least one mantissa pattern digit
// 2. Disallow "#+ @" in mantissa
// 3. Require at least one exponent pattern digit
if (((digitLeftCount + zeroDigitCount) < 1 &&
(sigDigitCount + digitRightCount) < 1) ||
(sigDigitCount > 0 && digitLeftCount > 0) ||
expDigits < 1) {
// Malformed exponential pattern
debug("Malformed exponential pattern")
status = U_MALFORMED_EXPONENTIAL_PATTERN;
syntaxError(pattern,pos,parseError);
return;
}
}
// Transition to suffix subpart
subpart = 2; // suffix subpart
affix = &suffix;
sub0Limit = pos;
continue;
}
break;
case 1: // Prefix subpart
case 2: // Suffix subpart
// Process the prefix / suffix characters
// Process unquoted characters seen in prefix or suffix
// subpart.
// Several syntax characters implicitly begins the
// next subpart if we are in the prefix; otherwise
// they are illegal if unquoted.
if (!pattern.compare(pos, digitLen, digit) ||
!pattern.compare(pos, groupSepLen, groupingSeparator) ||
!pattern.compare(pos, decimalSepLen, decimalSeparator) ||
(ch >= zeroDigit && ch <= nineDigit) ||
ch == sigDigit) {
if (subpart == 1) { // prefix subpart
subpart = 0; // pattern proper subpart
sub0Start = pos; // Reprocess this character
continue;
} else {
status = U_UNQUOTED_SPECIAL;
syntaxError(pattern,pos,parseError);
return;
}
} else if (ch == kCurrencySign) {
affix->append(kQuote); // Encode currency
// Use lookahead to determine if the currency sign is
// doubled or not.
U_ASSERT(U16_LENGTH(kCurrencySign) == 1);
if ((pos+1) < pattern.length() && pattern[pos+1] == kCurrencySign) {
affix->append(kCurrencySign);
++pos; // Skip over the doubled character
if ((pos+1) < pattern.length() &&
pattern[pos+1] == kCurrencySign) {
affix->append(kCurrencySign);
++pos; // Skip over the doubled character
fCurrencySignCount = fgCurrencySignCountInPluralFormat;
} else {
fCurrencySignCount = fgCurrencySignCountInISOFormat;
}
} else {
fCurrencySignCount = fgCurrencySignCountInSymbolFormat;
}
// Fall through to append(ch)
} else if (ch == kQuote) {
// A quote outside quotes indicates either the opening
// quote or two quotes, which is a quote literal. That is,
// we have the first quote in 'do' or o''clock.
U_ASSERT(U16_LENGTH(kQuote) == 1);
++pos;
if (pos < pattern.length() && pattern[pos] == kQuote) {
affix->append(kQuote); // Encode quote
// Fall through to append(ch)
} else {
subpart += 2; // open quote
continue;
}
} else if (pattern.compare(pos, separator.length(), separator) == 0) {
// Don't allow separators in the prefix, and don't allow
// separators in the second pattern (part == 1).
if (subpart == 1 || part == 1) {
// Unexpected separator
debug("Unexpected separator")
status = U_UNEXPECTED_TOKEN;
syntaxError(pattern,pos,parseError);
return;
}
sub2Limit = pos;
isPartDone = TRUE; // Go to next part
pos += separator.length();
break;
} else if (pattern.compare(pos, percent.length(), percent) == 0) {
// Next handle characters which are appended directly.
if (multiplier != 1) {
// Too many percent/perMill characters
debug("Too many percent characters")
status = U_MULTIPLE_PERCENT_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
affix->append(kQuote); // Encode percent/perMill
affix->append(kPatternPercent); // Use unlocalized pattern char
multiplier = 100;
pos += percent.length();
break;
} else if (pattern.compare(pos, perMill.length(), perMill) == 0) {
// Next handle characters which are appended directly.
if (multiplier != 1) {
// Too many percent/perMill characters
debug("Too many perMill characters")
status = U_MULTIPLE_PERMILL_SYMBOLS;
syntaxError(pattern,pos,parseError);
return;
}
affix->append(kQuote); // Encode percent/perMill
affix->append(kPatternPerMill); // Use unlocalized pattern char
multiplier = 1000;
pos += perMill.length();
break;
} else if (pattern.compare(pos, padEscape.length(), padEscape) == 0) {
if (padPos >= 0 || // Multiple pad specifiers
(pos+1) == pattern.length()) { // Nothing after padEscape
debug("Multiple pad specifiers")
status = U_MULTIPLE_PAD_SPECIFIERS;
syntaxError(pattern,pos,parseError);
return;
}
padPos = pos;
pos += padEscape.length();
padChar = pattern.char32At(pos);
pos += U16_LENGTH(padChar);
break;
} else if (pattern.compare(pos, minus.length(), minus) == 0) {
affix->append(kQuote); // Encode minus
affix->append(kPatternMinus);
pos += minus.length();
break;
} else if (pattern.compare(pos, plus.length(), plus) == 0) {
affix->append(kQuote); // Encode plus
affix->append(kPatternPlus);
pos += plus.length();
break;
}
// Unquoted, non-special characters fall through to here, as
// well as other code which needs to append something to the
// affix.
affix->append(ch);
pos += U16_LENGTH(ch);
break;
case 3: // Prefix subpart, in quote
case 4: // Suffix subpart, in quote
// A quote within quotes indicates either the closing
// quote or two quotes, which is a quote literal. That is,
// we have the second quote in 'do' or 'don''t'.
if (ch == kQuote) {
++pos;
if (pos < pattern.length() && pattern[pos] == kQuote) {
affix->append(kQuote); // Encode quote
// Fall through to append(ch)
} else {
subpart -= 2; // close quote
continue;
}
}
affix->append(ch);
pos += U16_LENGTH(ch);
break;
}
}
if (sub0Limit == 0) {
sub0Limit = pattern.length();
}
if (sub2Limit == 0) {
sub2Limit = pattern.length();
}
/* Handle patterns with no '0' pattern character. These patterns
* are legal, but must be recodified to make sense. "##.###" ->
* "#0.###". ".###" -> ".0##".
*
* We allow patterns of the form "####" to produce a zeroDigitCount
* of zero (got that?); although this seems like it might make it
* possible for format() to produce empty strings, format() checks
* for this condition and outputs a zero digit in this situation.
* Having a zeroDigitCount of zero yields a minimum integer digits
* of zero, which allows proper round-trip patterns. We don't want
* "#" to become "#0" when toPattern() is called (even though that's
* what it really is, semantically).
*/
if (zeroDigitCount == 0 && sigDigitCount == 0 &&
digitLeftCount > 0 && decimalPos >= 0) {
// Handle "###.###" and "###." and ".###"
int n = decimalPos;
if (n == 0)
++n; // Handle ".###"
digitRightCount = digitLeftCount - n;
digitLeftCount = n - 1;
zeroDigitCount = 1;
}
// Do syntax checking on the digits, decimal points, and quotes.
if ((decimalPos < 0 && digitRightCount > 0 && sigDigitCount == 0) ||
(decimalPos >= 0 &&
(sigDigitCount > 0 ||
decimalPos < digitLeftCount ||
decimalPos > (digitLeftCount + zeroDigitCount))) ||
groupingCount == 0 || groupingCount2 == 0 ||
(sigDigitCount > 0 && zeroDigitCount > 0) ||
subpart > 2)
{ // subpart > 2 == unmatched quote
debug("Syntax error")
status = U_PATTERN_SYNTAX_ERROR;
syntaxError(pattern,pos,parseError);
return;
}
// Make sure pad is at legal position before or after affix.
if (padPos >= 0) {
if (padPos == start) {
padPos = kPadBeforePrefix;
} else if (padPos+2 == sub0Start) {
padPos = kPadAfterPrefix;
} else if (padPos == sub0Limit) {
padPos = kPadBeforeSuffix;
} else if (padPos+2 == sub2Limit) {
padPos = kPadAfterSuffix;
} else {
// Illegal pad position
debug("Illegal pad position")
status = U_ILLEGAL_PAD_POSITION;
syntaxError(pattern,pos,parseError);
return;
}
}
if (part == 0) {
delete fPosPrefixPattern;
delete fPosSuffixPattern;
delete fNegPrefixPattern;
delete fNegSuffixPattern;
fPosPrefixPattern = new UnicodeString(prefix);
/* test for NULL */
if (fPosPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
fPosSuffixPattern = new UnicodeString(suffix);
/* test for NULL */
if (fPosSuffixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
delete fPosPrefixPattern;
return;
}
fNegPrefixPattern = 0;
fNegSuffixPattern = 0;
fUseExponentialNotation = (expDigits >= 0);
if (fUseExponentialNotation) {
fMinExponentDigits = expDigits;
}
fExponentSignAlwaysShown = expSignAlways;
int32_t digitTotalCount = digitLeftCount + zeroDigitCount + digitRightCount;
// The effectiveDecimalPos is the position the decimal is at or
// would be at if there is no decimal. Note that if
// decimalPos<0, then digitTotalCount == digitLeftCount +
// zeroDigitCount.
int32_t effectiveDecimalPos = decimalPos >= 0 ? decimalPos : digitTotalCount;
UBool isSigDig = (sigDigitCount > 0);
setSignificantDigitsUsed(isSigDig);
if (isSigDig) {
setMinimumSignificantDigits(sigDigitCount);
setMaximumSignificantDigits(sigDigitCount + digitRightCount);
} else {
int32_t minInt = effectiveDecimalPos - digitLeftCount;
setMinimumIntegerDigits(minInt);
setMaximumIntegerDigits(fUseExponentialNotation
? digitLeftCount + getMinimumIntegerDigits()
: kDoubleIntegerDigits);
setMaximumFractionDigits(decimalPos >= 0
? (digitTotalCount - decimalPos) : 0);
setMinimumFractionDigits(decimalPos >= 0
? (digitLeftCount + zeroDigitCount - decimalPos) : 0);
}
setGroupingUsed(groupingCount > 0);
fGroupingSize = (groupingCount > 0) ? groupingCount : 0;
fGroupingSize2 = (groupingCount2 > 0 && groupingCount2 != groupingCount)
? groupingCount2 : 0;
setMultiplier(multiplier);
setDecimalSeparatorAlwaysShown(decimalPos == 0
|| decimalPos == digitTotalCount);
if (padPos >= 0) {
fPadPosition = (EPadPosition) padPos;
// To compute the format width, first set up sub0Limit -
// sub0Start. Add in prefix/suffix length later.
// fFormatWidth = prefix.length() + suffix.length() +
// sub0Limit - sub0Start;
fFormatWidth = sub0Limit - sub0Start;
fPad = padChar;
} else {
fFormatWidth = 0;
}
if (roundingPos >= 0) {
roundingInc.setDecimalAt(effectiveDecimalPos - roundingPos);
if (fRoundingIncrement != NULL) {
*fRoundingIncrement = roundingInc;
} else {
fRoundingIncrement = new DigitList(roundingInc);
/* test for NULL */
if (fRoundingIncrement == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
delete fPosPrefixPattern;
delete fPosSuffixPattern;
return;
}
}
fRoundingIncrement->getDouble(); // forces caching of double in the DigitList,
// makes getting it thread safe.
fRoundingMode = kRoundHalfEven;
} else {
setRoundingIncrement(0.0);
}
} else {
fNegPrefixPattern = new UnicodeString(prefix);
/* test for NULL */
if (fNegPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
fNegSuffixPattern = new UnicodeString(suffix);
/* test for NULL */
if (fNegSuffixPattern == 0) {
delete fNegPrefixPattern;
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
}
if (pattern.length() == 0) {
delete fNegPrefixPattern;
delete fNegSuffixPattern;
fNegPrefixPattern = NULL;
fNegSuffixPattern = NULL;
if (fPosPrefixPattern != NULL) {
fPosPrefixPattern->remove();
} else {
fPosPrefixPattern = new UnicodeString();
/* test for NULL */
if (fPosPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
if (fPosSuffixPattern != NULL) {
fPosSuffixPattern->remove();
} else {
fPosSuffixPattern = new UnicodeString();
/* test for NULL */
if (fPosSuffixPattern == 0) {
delete fPosPrefixPattern;
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
setMinimumIntegerDigits(0);
setMaximumIntegerDigits(kDoubleIntegerDigits);
setMinimumFractionDigits(0);
setMaximumFractionDigits(kDoubleFractionDigits);
fUseExponentialNotation = FALSE;
fCurrencySignCount = 0;
setGroupingUsed(FALSE);
fGroupingSize = 0;
fGroupingSize2 = 0;
setMultiplier(1);
setDecimalSeparatorAlwaysShown(FALSE);
fFormatWidth = 0;
setRoundingIncrement(0.0);
}
// If there was no negative pattern, or if the negative pattern is
// identical to the positive pattern, then prepend the minus sign to the
// positive pattern to form the negative pattern.
if (fNegPrefixPattern == NULL ||
(*fNegPrefixPattern == *fPosPrefixPattern
&& *fNegSuffixPattern == *fPosSuffixPattern)) {
_copy_us_ptr(&fNegSuffixPattern, fPosSuffixPattern);
if (fNegPrefixPattern == NULL) {
fNegPrefixPattern = new UnicodeString();
/* test for NULL */
if (fNegPrefixPattern == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
} else {
fNegPrefixPattern->remove();
}
fNegPrefixPattern->append(kQuote).append(kPatternMinus)
.append(*fPosPrefixPattern);
}
#ifdef FMT_DEBUG
UnicodeString s;
s.append("\"").append(pattern).append("\"->");
debugout(s);
#endif
// save the pattern
fFormatPattern = pattern;
}
void
DecimalFormat::expandAffixAdjustWidth(const UnicodeString* pluralCount) {
expandAffixes(pluralCount);
if (fFormatWidth > 0) {
// Finish computing format width (see above)
// TODO: how to handle fFormatWidth,
// need to save in f(Plural)AffixesForCurrecy?
fFormatWidth += fPositivePrefix.length() + fPositiveSuffix.length();
}
}
void
DecimalFormat::applyPattern(const UnicodeString& pattern,
UBool localized,
UParseError& parseError,
UErrorCode& status)
{
// do the following re-set first. since they change private data by
// apply pattern again.
if (pattern.indexOf(kCurrencySign) != -1) {
if (fCurrencyPluralInfo == NULL) {
// initialize currencyPluralInfo if needed
fCurrencyPluralInfo = new CurrencyPluralInfo(fSymbols->getLocale(), status);
}
if (fAffixPatternsForCurrency == NULL) {
setupCurrencyAffixPatterns(status);
}
if (pattern.indexOf(fgTripleCurrencySign, 3, 0) != -1) {
// only setup the affixes of the current pattern.
setupCurrencyAffixes(pattern, TRUE, FALSE, status);
}
}
applyPatternWithoutExpandAffix(pattern, localized, parseError, status);
expandAffixAdjustWidth(NULL);
}
void
DecimalFormat::applyPatternInternally(const UnicodeString& pluralCount,
const UnicodeString& pattern,
UBool localized,
UParseError& parseError,
UErrorCode& status) {
applyPatternWithoutExpandAffix(pattern, localized, parseError, status);
expandAffixAdjustWidth(&pluralCount);
}
/**
* Sets the maximum number of digits allowed in the integer portion of a
* number. This override limits the integer digit count to 309.
* @see NumberFormat#setMaximumIntegerDigits
*/
void DecimalFormat::setMaximumIntegerDigits(int32_t newValue) {
NumberFormat::setMaximumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
}
/**
* Sets the minimum number of digits allowed in the integer portion of a
* number. This override limits the integer digit count to 309.
* @see NumberFormat#setMinimumIntegerDigits
*/
void DecimalFormat::setMinimumIntegerDigits(int32_t newValue) {
NumberFormat::setMinimumIntegerDigits(_min(newValue, kDoubleIntegerDigits));
}
/**
* Sets the maximum number of digits allowed in the fraction portion of a
* number. This override limits the fraction digit count to 340.
* @see NumberFormat#setMaximumFractionDigits
*/
void DecimalFormat::setMaximumFractionDigits(int32_t newValue) {
NumberFormat::setMaximumFractionDigits(_min(newValue, kDoubleFractionDigits));
}
/**
* Sets the minimum number of digits allowed in the fraction portion of a
* number. This override limits the fraction digit count to 340.
* @see NumberFormat#setMinimumFractionDigits
*/
void DecimalFormat::setMinimumFractionDigits(int32_t newValue) {
NumberFormat::setMinimumFractionDigits(_min(newValue, kDoubleFractionDigits));
}
int32_t DecimalFormat::getMinimumSignificantDigits() const {
return fMinSignificantDigits;
}
int32_t DecimalFormat::getMaximumSignificantDigits() const {
return fMaxSignificantDigits;
}
void DecimalFormat::setMinimumSignificantDigits(int32_t min) {
if (min < 1) {
min = 1;
}
// pin max sig dig to >= min
int32_t max = _max(fMaxSignificantDigits, min);
fMinSignificantDigits = min;
fMaxSignificantDigits = max;
}
void DecimalFormat::setMaximumSignificantDigits(int32_t max) {
if (max < 1) {
max = 1;
}
// pin min sig dig to 1..max
U_ASSERT(fMinSignificantDigits >= 1);
int32_t min = _min(fMinSignificantDigits, max);
fMinSignificantDigits = min;
fMaxSignificantDigits = max;
}
UBool DecimalFormat::areSignificantDigitsUsed() const {
return fUseSignificantDigits;
}
void DecimalFormat::setSignificantDigitsUsed(UBool useSignificantDigits) {
fUseSignificantDigits = useSignificantDigits;
}
void DecimalFormat::setCurrencyInternally(const UChar* theCurrency,
UErrorCode& ec) {
// If we are a currency format, then modify our affixes to
// encode the currency symbol for the given currency in our
// locale, and adjust the decimal digits and rounding for the
// given currency.
// Note: The code is ordered so that this object is *not changed*
// until we are sure we are going to succeed.
// NULL or empty currency is *legal* and indicates no currency.
UBool isCurr = (theCurrency && *theCurrency);
double rounding = 0.0;
int32_t frac = 0;
if (fCurrencySignCount > fgCurrencySignCountZero && isCurr) {
rounding = ucurr_getRoundingIncrement(theCurrency, &ec);
frac = ucurr_getDefaultFractionDigits(theCurrency, &ec);
}
NumberFormat::setCurrency(theCurrency, ec);
if (U_FAILURE(ec)) return;
if (fCurrencySignCount > fgCurrencySignCountZero) {
// NULL or empty currency is *legal* and indicates no currency.
if (isCurr) {
setRoundingIncrement(rounding);
setMinimumFractionDigits(frac);
setMaximumFractionDigits(frac);
}
expandAffixes(NULL);
}
}
void DecimalFormat::setCurrency(const UChar* theCurrency, UErrorCode& ec) {
// set the currency before compute affixes to get the right currency names
NumberFormat::setCurrency(theCurrency, ec);
if (fFormatPattern.indexOf(fgTripleCurrencySign, 3, 0) != -1) {
UnicodeString savedPtn = fFormatPattern;
setupCurrencyAffixes(fFormatPattern, TRUE, TRUE, ec);
UParseError parseErr;
applyPattern(savedPtn, FALSE, parseErr, ec);
}
// set the currency after apply pattern to get the correct rounding/fraction
setCurrencyInternally(theCurrency, ec);
}
// Deprecated variant with no UErrorCode parameter
void DecimalFormat::setCurrency(const UChar* theCurrency) {
UErrorCode ec = U_ZERO_ERROR;
setCurrency(theCurrency, ec);
}
void DecimalFormat::getEffectiveCurrency(UChar* result, UErrorCode& ec) const {
if (fSymbols == NULL) {
ec = U_MEMORY_ALLOCATION_ERROR;
return;
}
ec = U_ZERO_ERROR;
const UChar* c = getCurrency();
if (*c == 0) {
const UnicodeString &intl =
fSymbols->getConstSymbol(DecimalFormatSymbols::kIntlCurrencySymbol);
c = intl.getBuffer(); // ok for intl to go out of scope
}
u_strncpy(result, c, 3);
result[3] = 0;
}
/**
* Return the number of fraction digits to display, or the total
* number of digits for significant digit formats and exponential
* formats.
*/
int32_t
DecimalFormat::precision() const {
if (areSignificantDigitsUsed()) {
return getMaximumSignificantDigits();
} else if (fUseExponentialNotation) {
return getMinimumIntegerDigits() + getMaximumFractionDigits();
} else {
return getMaximumFractionDigits();
}
}
// TODO: template algorithm
Hashtable*
DecimalFormat::initHashForAffix(UErrorCode& status) {
if ( U_FAILURE(status) ) {
return NULL;
}
Hashtable* hTable;
if ( (hTable = new Hashtable(TRUE, status)) == NULL ) {
status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
if ( U_FAILURE(status) ) {
delete hTable;
return NULL;
}
hTable->setValueComparator(decimfmtAffixValueComparator);
return hTable;
}
Hashtable*
DecimalFormat::initHashForAffixPattern(UErrorCode& status) {
if ( U_FAILURE(status) ) {
return NULL;
}
Hashtable* hTable;
if ( (hTable = new Hashtable(TRUE, status)) == NULL ) {
status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
if ( U_FAILURE(status) ) {
delete hTable;
return NULL;
}
hTable->setValueComparator(decimfmtAffixPatternValueComparator);
return hTable;
}
void
DecimalFormat::deleteHashForAffix(Hashtable*& table)
{
if ( table == NULL ) {
return;
}
int32_t pos = -1;
const UHashElement* element = NULL;
while ( (element = table->nextElement(pos)) != NULL ) {
const UHashTok valueTok = element->value;
const AffixesForCurrency* value = (AffixesForCurrency*)valueTok.pointer;
delete value;
}
delete table;
table = NULL;
}
void
DecimalFormat::deleteHashForAffixPattern()
{
if ( fAffixPatternsForCurrency == NULL ) {
return;
}
int32_t pos = -1;
const UHashElement* element = NULL;
while ( (element = fAffixPatternsForCurrency->nextElement(pos)) != NULL ) {
const UHashTok valueTok = element->value;
const AffixPatternsForCurrency* value = (AffixPatternsForCurrency*)valueTok.pointer;
delete value;
}
delete fAffixPatternsForCurrency;
fAffixPatternsForCurrency = NULL;
}
void
DecimalFormat::copyHashForAffixPattern(const Hashtable* source,
Hashtable* target,
UErrorCode& status) {
if ( U_FAILURE(status) ) {
return;
}
int32_t pos = -1;
const UHashElement* element = NULL;
if ( source ) {
while ( (element = source->nextElement(pos)) != NULL ) {
const UHashTok keyTok = element->key;
const UnicodeString* key = (UnicodeString*)keyTok.pointer;
const UHashTok valueTok = element->value;
const AffixPatternsForCurrency* value = (AffixPatternsForCurrency*)valueTok.pointer;
AffixPatternsForCurrency* copy = new AffixPatternsForCurrency(
value->negPrefixPatternForCurrency,
value->negSuffixPatternForCurrency,
value->posPrefixPatternForCurrency,
value->posSuffixPatternForCurrency,
value->patternType);
target->put(UnicodeString(*key), copy, status);
if ( U_FAILURE(status) ) {
return;
}
}
}
}
void
DecimalFormat::copyHashForAffix(const Hashtable* source,
Hashtable* target,
UErrorCode& status) {
if ( U_FAILURE(status) ) {
return;
}
int32_t pos = -1;
const UHashElement* element = NULL;
if ( source ) {
while ( (element = source->nextElement(pos)) != NULL ) {
const UHashTok keyTok = element->key;
const UnicodeString* key = (UnicodeString*)keyTok.pointer;
const UHashTok valueTok = element->value;
const AffixesForCurrency* value = (AffixesForCurrency*)valueTok.pointer;
AffixesForCurrency* copy = new AffixesForCurrency(
value->negPrefixForCurrency,
value->negSuffixForCurrency,
value->posPrefixForCurrency,
value->posSuffixForCurrency);
target->put(UnicodeString(*key), copy, status);
if ( U_FAILURE(status) ) {
return;
}
}
}
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_FORMATTING */
//eof
|