1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
|
/*
**********************************************************************
* Copyright (C) 2001-2011 IBM and others. All rights reserved.
**********************************************************************
* Date Name Description
* 07/02/2001 synwee Creation.
**********************************************************************
*/
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION && !UCONFIG_NO_BREAK_ITERATION
#include "unicode/usearch.h"
#include "unicode/ustring.h"
#include "unicode/uchar.h"
#include "normalizer2impl.h"
#include "ucol_imp.h"
#include "usrchimp.h"
#include "cmemory.h"
#include "ucln_in.h"
#include "uassert.h"
#include "ustr_imp.h"
U_NAMESPACE_USE
// don't use Boyer-Moore
// (and if we decide to turn this on again there are several new TODOs that will need to be addressed)
#define BOYER_MOORE 0
#define LENGTHOF(array) (int32_t)(sizeof(array)/sizeof((array)[0]))
// internal definition ---------------------------------------------------
#define LAST_BYTE_MASK_ 0xFF
#define SECOND_LAST_BYTE_SHIFT_ 8
#define SUPPLEMENTARY_MIN_VALUE_ 0x10000
static const uint16_t *fcdTrieIndex = NULL;
static UChar32 fcdHighStart = 0;
// internal methods -------------------------------------------------
/**
* Fast collation element iterator setOffset.
* This function does not check for bounds.
* @param coleiter collation element iterator
* @param offset to set
*/
static
inline void setColEIterOffset(UCollationElements *elems,
int32_t offset)
{
collIterate *ci = &(elems->iteratordata_);
ci->pos = ci->string + offset;
ci->CEpos = ci->toReturn = ci->extendCEs ? ci->extendCEs : ci->CEs;
if (ci->flags & UCOL_ITER_INNORMBUF) {
ci->flags = ci->origFlags;
}
ci->fcdPosition = NULL;
ci->offsetReturn = NULL;
ci->offsetStore = ci->offsetBuffer;
ci->offsetRepeatCount = ci->offsetRepeatValue = 0;
}
/**
* Getting the mask for collation strength
* @param strength collation strength
* @return collation element mask
*/
static
inline uint32_t getMask(UCollationStrength strength)
{
switch (strength)
{
case UCOL_PRIMARY:
return UCOL_PRIMARYORDERMASK;
case UCOL_SECONDARY:
return UCOL_SECONDARYORDERMASK | UCOL_PRIMARYORDERMASK;
default:
return UCOL_TERTIARYORDERMASK | UCOL_SECONDARYORDERMASK |
UCOL_PRIMARYORDERMASK;
}
}
/**
* This is to squeeze the 21bit ces into a 256 table
* @param ce collation element
* @return collapsed version of the collation element
*/
static
inline int hash(uint32_t ce)
{
// the old value UCOL_PRIMARYORDER(ce) % MAX_TABLE_SIZE_ does not work
// well with the new collation where most of the latin 1 characters
// are of the value xx000xxx. their hashes will most of the time be 0
// to be discussed on the hash algo.
return UCOL_PRIMARYORDER(ce) % MAX_TABLE_SIZE_;
}
U_CDECL_BEGIN
static UBool U_CALLCONV
usearch_cleanup(void) {
fcdTrieIndex = NULL;
return TRUE;
}
U_CDECL_END
/**
* Initializing the fcd tables.
* Internal method, status assumed to be a success.
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
*/
static
inline void initializeFCD(UErrorCode *status)
{
if (fcdTrieIndex == NULL) {
fcdTrieIndex = unorm_getFCDTrieIndex(fcdHighStart, status);
ucln_i18n_registerCleanup(UCLN_I18N_USEARCH, usearch_cleanup);
}
}
/**
* Gets the fcd value for a character at the argument index.
* This method takes into accounts of the supplementary characters.
* @param str UTF16 string where character for fcd retrieval resides
* @param offset position of the character whose fcd is to be retrieved, to be
* overwritten with the next character position, taking
* surrogate characters into consideration.
* @param strlength length of the argument string
* @return fcd value
*/
static
uint16_t getFCD(const UChar *str, int32_t *offset,
int32_t strlength)
{
const UChar *temp = str + *offset;
uint16_t result = unorm_nextFCD16(fcdTrieIndex, fcdHighStart, temp, str + strlength);
*offset = (int32_t)(temp - str);
return result;
}
/**
* Getting the modified collation elements taking into account the collation
* attributes
* @param strsrch string search data
* @param sourcece
* @return the modified collation element
*/
static
inline int32_t getCE(const UStringSearch *strsrch, uint32_t sourcece)
{
// note for tertiary we can't use the collator->tertiaryMask, that
// is a preprocessed mask that takes into account case options. since
// we are only concerned with exact matches, we don't need that.
sourcece &= strsrch->ceMask;
if (strsrch->toShift) {
// alternate handling here, since only the 16 most significant digits
// is only used, we can safely do a compare without masking
// if the ce is a variable, we mask and get only the primary values
// no shifting to quartenary is required since all primary values
// less than variabletop will need to be masked off anyway.
if (strsrch->variableTop > sourcece) {
if (strsrch->strength >= UCOL_QUATERNARY) {
sourcece &= UCOL_PRIMARYORDERMASK;
}
else {
sourcece = UCOL_IGNORABLE;
}
}
} else if (strsrch->strength >= UCOL_QUATERNARY && sourcece == UCOL_IGNORABLE) {
sourcece = 0xFFFF;
}
return sourcece;
}
/**
* Allocate a memory and returns NULL if it failed.
* Internal method, status assumed to be a success.
* @param size to allocate
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return newly allocated array, NULL otherwise
*/
static
inline void * allocateMemory(uint32_t size, UErrorCode *status)
{
uint32_t *result = (uint32_t *)uprv_malloc(size);
if (result == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
}
return result;
}
/**
* Adds a uint32_t value to a destination array.
* Creates a new array if we run out of space. The caller will have to
* manually deallocate the newly allocated array.
* Internal method, status assumed to be success, caller has to check status
* before calling this method. destination not to be NULL and has at least
* size destinationlength.
* @param destination target array
* @param offset destination offset to add value
* @param destinationlength target array size, return value for the new size
* @param value to be added
* @param increments incremental size expected
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return new destination array, destination if there was no new allocation
*/
static
inline int32_t * addTouint32_tArray(int32_t *destination,
uint32_t offset,
uint32_t *destinationlength,
uint32_t value,
uint32_t increments,
UErrorCode *status)
{
uint32_t newlength = *destinationlength;
if (offset + 1 == newlength) {
newlength += increments;
int32_t *temp = (int32_t *)allocateMemory(
sizeof(int32_t) * newlength, status);
if (U_FAILURE(*status)) {
return NULL;
}
uprv_memcpy(temp, destination, sizeof(int32_t) * offset);
*destinationlength = newlength;
destination = temp;
}
destination[offset] = value;
return destination;
}
/**
* Adds a uint64_t value to a destination array.
* Creates a new array if we run out of space. The caller will have to
* manually deallocate the newly allocated array.
* Internal method, status assumed to be success, caller has to check status
* before calling this method. destination not to be NULL and has at least
* size destinationlength.
* @param destination target array
* @param offset destination offset to add value
* @param destinationlength target array size, return value for the new size
* @param value to be added
* @param increments incremental size expected
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return new destination array, destination if there was no new allocation
*/
static
inline int64_t * addTouint64_tArray(int64_t *destination,
uint32_t offset,
uint32_t *destinationlength,
uint64_t value,
uint32_t increments,
UErrorCode *status)
{
uint32_t newlength = *destinationlength;
if (offset + 1 == newlength) {
newlength += increments;
int64_t *temp = (int64_t *)allocateMemory(
sizeof(int64_t) * newlength, status);
if (U_FAILURE(*status)) {
return NULL;
}
uprv_memcpy(temp, destination, sizeof(int64_t) * offset);
*destinationlength = newlength;
destination = temp;
}
destination[offset] = value;
return destination;
}
/**
* Initializing the ce table for a pattern.
* Stores non-ignorable collation keys.
* Table size will be estimated by the size of the pattern text. Table
* expansion will be perform as we go along. Adding 1 to ensure that the table
* size definitely increases.
* Internal method, status assumed to be a success.
* @param strsrch string search data
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return total number of expansions
*/
static
inline uint16_t initializePatternCETable(UStringSearch *strsrch,
UErrorCode *status)
{
UPattern *pattern = &(strsrch->pattern);
uint32_t cetablesize = INITIAL_ARRAY_SIZE_;
int32_t *cetable = pattern->CEBuffer;
uint32_t patternlength = pattern->textLength;
UCollationElements *coleiter = strsrch->utilIter;
if (coleiter == NULL) {
coleiter = ucol_openElements(strsrch->collator, pattern->text,
patternlength, status);
// status will be checked in ucol_next(..) later and if it is an
// error UCOL_NULLORDER the result of ucol_next(..) and 0 will be
// returned.
strsrch->utilIter = coleiter;
}
else {
uprv_init_collIterate(strsrch->collator, pattern->text,
pattern->textLength,
&coleiter->iteratordata_,
status);
}
if(U_FAILURE(*status)) {
return 0;
}
if (pattern->CE != cetable && pattern->CE) {
uprv_free(pattern->CE);
}
uint16_t offset = 0;
uint16_t result = 0;
int32_t ce;
while ((ce = ucol_next(coleiter, status)) != UCOL_NULLORDER &&
U_SUCCESS(*status)) {
uint32_t newce = getCE(strsrch, ce);
if (newce) {
int32_t *temp = addTouint32_tArray(cetable, offset, &cetablesize,
newce,
patternlength - ucol_getOffset(coleiter) + 1,
status);
if (U_FAILURE(*status)) {
return 0;
}
offset ++;
if (cetable != temp && cetable != pattern->CEBuffer) {
uprv_free(cetable);
}
cetable = temp;
}
result += (uint16_t)(ucol_getMaxExpansion(coleiter, ce) - 1);
}
cetable[offset] = 0;
pattern->CE = cetable;
pattern->CELength = offset;
return result;
}
/**
* Initializing the pce table for a pattern.
* Stores non-ignorable collation keys.
* Table size will be estimated by the size of the pattern text. Table
* expansion will be perform as we go along. Adding 1 to ensure that the table
* size definitely increases.
* Internal method, status assumed to be a success.
* @param strsrch string search data
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return total number of expansions
*/
static
inline uint16_t initializePatternPCETable(UStringSearch *strsrch,
UErrorCode *status)
{
UPattern *pattern = &(strsrch->pattern);
uint32_t pcetablesize = INITIAL_ARRAY_SIZE_;
int64_t *pcetable = pattern->PCEBuffer;
uint32_t patternlength = pattern->textLength;
UCollationElements *coleiter = strsrch->utilIter;
if (coleiter == NULL) {
coleiter = ucol_openElements(strsrch->collator, pattern->text,
patternlength, status);
// status will be checked in ucol_next(..) later and if it is an
// error UCOL_NULLORDER the result of ucol_next(..) and 0 will be
// returned.
strsrch->utilIter = coleiter;
} else {
uprv_init_collIterate(strsrch->collator, pattern->text,
pattern->textLength,
&coleiter->iteratordata_,
status);
}
if(U_FAILURE(*status)) {
return 0;
}
if (pattern->PCE != pcetable && pattern->PCE != NULL) {
uprv_free(pattern->PCE);
}
uint16_t offset = 0;
uint16_t result = 0;
int64_t pce;
uprv_init_pce(coleiter);
// ** Should processed CEs be signed or unsigned?
// ** (the rest of the code in this file seems to play fast-and-loose with
// ** whether a CE is signed or unsigned. For example, look at routine above this one.)
while ((pce = ucol_nextProcessed(coleiter, NULL, NULL, status)) != UCOL_PROCESSED_NULLORDER &&
U_SUCCESS(*status)) {
int64_t *temp = addTouint64_tArray(pcetable, offset, &pcetablesize,
pce,
patternlength - ucol_getOffset(coleiter) + 1,
status);
if (U_FAILURE(*status)) {
return 0;
}
offset += 1;
if (pcetable != temp && pcetable != pattern->PCEBuffer) {
uprv_free(pcetable);
}
pcetable = temp;
//result += (uint16_t)(ucol_getMaxExpansion(coleiter, ce) - 1);
}
pcetable[offset] = 0;
pattern->PCE = pcetable;
pattern->PCELength = offset;
return result;
}
/**
* Initializes the pattern struct.
* Internal method, status assumed to be success.
* @param strsrch UStringSearch data storage
* @param status output error if any, caller to check status before calling
* method, status assumed to be success when passed in.
* @return expansionsize the total expansion size of the pattern
*/
static
inline int16_t initializePattern(UStringSearch *strsrch, UErrorCode *status)
{
UPattern *pattern = &(strsrch->pattern);
const UChar *patterntext = pattern->text;
int32_t length = pattern->textLength;
int32_t index = 0;
// Since the strength is primary, accents are ignored in the pattern.
if (strsrch->strength == UCOL_PRIMARY) {
pattern->hasPrefixAccents = 0;
pattern->hasSuffixAccents = 0;
} else {
pattern->hasPrefixAccents = getFCD(patterntext, &index, length) >>
SECOND_LAST_BYTE_SHIFT_;
index = length;
UTF_BACK_1(patterntext, 0, index);
pattern->hasSuffixAccents = getFCD(patterntext, &index, length) &
LAST_BYTE_MASK_;
}
// ** HACK **
if (strsrch->pattern.PCE != NULL) {
if (strsrch->pattern.PCE != strsrch->pattern.PCEBuffer) {
uprv_free(strsrch->pattern.PCE);
}
strsrch->pattern.PCE = NULL;
}
// since intializePattern is an internal method status is a success.
return initializePatternCETable(strsrch, status);
}
/**
* Initializing shift tables, with the default values.
* If a corresponding default value is 0, the shift table is not set.
* @param shift table for forwards shift
* @param backshift table for backwards shift
* @param cetable table containing pattern ce
* @param cesize size of the pattern ces
* @param expansionsize total size of the expansions
* @param defaultforward the default forward value
* @param defaultbackward the default backward value
*/
static
inline void setShiftTable(int16_t shift[], int16_t backshift[],
int32_t *cetable, int32_t cesize,
int16_t expansionsize,
int16_t defaultforward,
int16_t defaultbackward)
{
// estimate the value to shift. to do that we estimate the smallest
// number of characters to give the relevant ces, ie approximately
// the number of ces minus their expansion, since expansions can come
// from a character.
int32_t count;
for (count = 0; count < MAX_TABLE_SIZE_; count ++) {
shift[count] = defaultforward;
}
cesize --; // down to the last index
for (count = 0; count < cesize; count ++) {
// number of ces from right of array to the count
int temp = defaultforward - count - 1;
shift[hash(cetable[count])] = temp > 1 ? temp : 1;
}
shift[hash(cetable[cesize])] = 1;
// for ignorables we just shift by one. see test examples.
shift[hash(0)] = 1;
for (count = 0; count < MAX_TABLE_SIZE_; count ++) {
backshift[count] = defaultbackward;
}
for (count = cesize; count > 0; count --) {
// the original value count does not seem to work
backshift[hash(cetable[count])] = count > expansionsize ?
(int16_t)(count - expansionsize) : 1;
}
backshift[hash(cetable[0])] = 1;
backshift[hash(0)] = 1;
}
/**
* Building of the pattern collation element list and the boyer moore strsrch
* table.
* The canonical match will only be performed after the default match fails.
* For both cases we need to remember the size of the composed and decomposed
* versions of the string. Since the Boyer-Moore shift calculations shifts by
* a number of characters in the text and tries to match the pattern from that
* offset, the shift value can not be too large in case we miss some
* characters. To choose a right shift size, we estimate the NFC form of the
* and use its size as a shift guide. The NFC form should be the small
* possible representation of the pattern. Anyways, we'll err on the smaller
* shift size. Hence the calculation for minlength.
* Canonical match will be performed slightly differently. We'll split the
* pattern into 3 parts, the prefix accents (PA), the middle string bounded by
* the first and last base character (MS), the ending accents (EA). Matches
* will be done on MS first, and only when we match MS then some processing
* will be required for the prefix and end accents in order to determine if
* they match PA and EA. Hence the default shift values
* for the canonical match will take the size of either end's accent into
* consideration. Forwards search will take the end accents into consideration
* for the default shift values and the backwards search will take the prefix
* accents into consideration.
* If pattern has no non-ignorable ce, we return a illegal argument error.
* Internal method, status assumed to be success.
* @param strsrch UStringSearch data storage
* @param status for output errors if it occurs, status is assumed to be a
* success when it is passed in.
*/
static
inline void initialize(UStringSearch *strsrch, UErrorCode *status)
{
int16_t expandlength = initializePattern(strsrch, status);
if (U_SUCCESS(*status) && strsrch->pattern.CELength > 0) {
UPattern *pattern = &strsrch->pattern;
int32_t cesize = pattern->CELength;
int16_t minlength = cesize > expandlength
? (int16_t)cesize - expandlength : 1;
pattern->defaultShiftSize = minlength;
setShiftTable(pattern->shift, pattern->backShift, pattern->CE,
cesize, expandlength, minlength, minlength);
return;
}
strsrch->pattern.defaultShiftSize = 0;
}
#if BOYER_MOORE
/**
* Check to make sure that the match length is at the end of the character by
* using the breakiterator.
* @param strsrch string search data
* @param start target text start offset
* @param end target text end offset
*/
static
void checkBreakBoundary(const UStringSearch *strsrch, int32_t * /*start*/,
int32_t *end)
{
#if !UCONFIG_NO_BREAK_ITERATION
UBreakIterator *breakiterator = strsrch->search->internalBreakIter;
if (breakiterator) {
int32_t matchend = *end;
//int32_t matchstart = *start;
if (!ubrk_isBoundary(breakiterator, matchend)) {
*end = ubrk_following(breakiterator, matchend);
}
/* Check the start of the matched text to make sure it doesn't have any accents
* before it. This code may not be necessary and so it is commented out */
/*if (!ubrk_isBoundary(breakiterator, matchstart) && !ubrk_isBoundary(breakiterator, matchstart-1)) {
*start = ubrk_preceding(breakiterator, matchstart);
}*/
}
#endif
}
/**
* Determine whether the target text in UStringSearch bounded by the offset
* start and end is one or more whole units of text as
* determined by the breakiterator in UStringSearch.
* @param strsrch string search data
* @param start target text start offset
* @param end target text end offset
*/
static
UBool isBreakUnit(const UStringSearch *strsrch, int32_t start,
int32_t end)
{
#if !UCONFIG_NO_BREAK_ITERATION
UBreakIterator *breakiterator = strsrch->search->breakIter;
//TODO: Add here.
if (breakiterator) {
int32_t startindex = ubrk_first(breakiterator);
int32_t endindex = ubrk_last(breakiterator);
// out-of-range indexes are never boundary positions
if (start < startindex || start > endindex ||
end < startindex || end > endindex) {
return FALSE;
}
// otherwise, we can use following() on the position before the
// specified one and return true of the position we get back is the
// one the user specified
UBool result = (start == startindex ||
ubrk_following(breakiterator, start - 1) == start) &&
(end == endindex ||
ubrk_following(breakiterator, end - 1) == end);
if (result) {
// iterates the individual ces
UCollationElements *coleiter = strsrch->utilIter;
const UChar *text = strsrch->search->text +
start;
UErrorCode status = U_ZERO_ERROR;
ucol_setText(coleiter, text, end - start, &status);
for (int32_t count = 0; count < strsrch->pattern.CELength;
count ++) {
int32_t ce = getCE(strsrch, ucol_next(coleiter, &status));
if (ce == UCOL_IGNORABLE) {
count --;
continue;
}
if (U_FAILURE(status) || ce != strsrch->pattern.CE[count]) {
return FALSE;
}
}
int32_t nextce = ucol_next(coleiter, &status);
while (ucol_getOffset(coleiter) == (end - start)
&& getCE(strsrch, nextce) == UCOL_IGNORABLE) {
nextce = ucol_next(coleiter, &status);
}
if (ucol_getOffset(coleiter) == (end - start)
&& nextce != UCOL_NULLORDER) {
// extra collation elements at the end of the match
return FALSE;
}
}
return result;
}
#endif
return TRUE;
}
/**
* Getting the next base character offset if current offset is an accent,
* or the current offset if the current character contains a base character.
* accents the following base character will be returned
* @param text string
* @param textoffset current offset
* @param textlength length of text string
* @return the next base character or the current offset
* if the current character is contains a base character.
*/
static
inline int32_t getNextBaseOffset(const UChar *text,
int32_t textoffset,
int32_t textlength)
{
if (textoffset < textlength) {
int32_t temp = textoffset;
if (getFCD(text, &temp, textlength) >> SECOND_LAST_BYTE_SHIFT_) {
while (temp < textlength) {
int32_t result = temp;
if ((getFCD(text, &temp, textlength) >>
SECOND_LAST_BYTE_SHIFT_) == 0) {
return result;
}
}
return textlength;
}
}
return textoffset;
}
/**
* Gets the next base character offset depending on the string search pattern
* data
* @param strsrch string search data
* @param textoffset current offset, one offset away from the last character
* to search for.
* @return start index of the next base character or the current offset
* if the current character is contains a base character.
*/
static
inline int32_t getNextUStringSearchBaseOffset(UStringSearch *strsrch,
int32_t textoffset)
{
int32_t textlength = strsrch->search->textLength;
if (strsrch->pattern.hasSuffixAccents &&
textoffset < textlength) {
int32_t temp = textoffset;
const UChar *text = strsrch->search->text;
UTF_BACK_1(text, 0, temp);
if (getFCD(text, &temp, textlength) & LAST_BYTE_MASK_) {
return getNextBaseOffset(text, textoffset, textlength);
}
}
return textoffset;
}
/**
* Shifting the collation element iterator position forward to prepare for
* a following match. If the last character is a unsafe character, we'll only
* shift by 1 to capture contractions, normalization etc.
* Internal method, status assumed to be success.
* @param text strsrch string search data
* @param textoffset start text position to do search
* @param ce the text ce which failed the match.
* @param patternceindex index of the ce within the pattern ce buffer which
* failed the match
* @return final offset
*/
static
inline int32_t shiftForward(UStringSearch *strsrch,
int32_t textoffset,
int32_t ce,
int32_t patternceindex)
{
UPattern *pattern = &(strsrch->pattern);
if (ce != UCOL_NULLORDER) {
int32_t shift = pattern->shift[hash(ce)];
// this is to adjust for characters in the middle of the
// substring for matching that failed.
int32_t adjust = pattern->CELength - patternceindex;
if (adjust > 1 && shift >= adjust) {
shift -= adjust - 1;
}
textoffset += shift;
}
else {
textoffset += pattern->defaultShiftSize;
}
textoffset = getNextUStringSearchBaseOffset(strsrch, textoffset);
// check for unsafe characters
// * if it is the start or middle of a contraction: to be done after
// a initial match is found
// * thai or lao base consonant character: similar to contraction
// * high surrogate character: similar to contraction
// * next character is a accent: shift to the next base character
return textoffset;
}
#endif // #if BOYER_MOORE
/**
* sets match not found
* @param strsrch string search data
*/
static
inline void setMatchNotFound(UStringSearch *strsrch)
{
// this method resets the match result regardless of the error status.
strsrch->search->matchedIndex = USEARCH_DONE;
strsrch->search->matchedLength = 0;
if (strsrch->search->isForwardSearching) {
setColEIterOffset(strsrch->textIter, strsrch->search->textLength);
}
else {
setColEIterOffset(strsrch->textIter, 0);
}
}
#if BOYER_MOORE
/**
* Gets the offset to the next safe point in text.
* ie. not the middle of a contraction, swappable characters or supplementary
* characters.
* @param collator collation sata
* @param text string to work with
* @param textoffset offset in string
* @param textlength length of text string
* @return offset to the next safe character
*/
static
inline int32_t getNextSafeOffset(const UCollator *collator,
const UChar *text,
int32_t textoffset,
int32_t textlength)
{
int32_t result = textoffset; // first contraction character
while (result != textlength && ucol_unsafeCP(text[result], collator)) {
result ++;
}
return result;
}
/**
* This checks for accents in the potential match started with a .
* composite character.
* This is really painful... we have to check that composite character do not
* have any extra accents. We have to normalize the potential match and find
* the immediate decomposed character before the match.
* The first composite character would have been taken care of by the fcd
* checks in checkForwardExactMatch.
* This is the slow path after the fcd of the first character and
* the last character has been checked by checkForwardExactMatch and we
* determine that the potential match has extra non-ignorable preceding
* ces.
* E.g. looking for \u0301 acute in \u01FA A ring above and acute,
* checkExtraMatchAccent should fail since there is a middle ring in \u01FA
* Note here that accents checking are slow and cautioned in the API docs.
* Internal method, status assumed to be a success, caller should check status
* before calling this method
* @param strsrch string search data
* @param start index of the potential unfriendly composite character
* @param end index of the potential unfriendly composite character
* @param status output error status if any.
* @return TRUE if there is non-ignorable accents before at the beginning
* of the match, FALSE otherwise.
*/
static
UBool checkExtraMatchAccents(const UStringSearch *strsrch, int32_t start,
int32_t end,
UErrorCode *status)
{
UBool result = FALSE;
if (strsrch->pattern.hasPrefixAccents) {
int32_t length = end - start;
int32_t offset = 0;
const UChar *text = strsrch->search->text + start;
UTF_FWD_1(text, offset, length);
// we are only concerned with the first composite character
if (unorm_quickCheck(text, offset, UNORM_NFD, status) == UNORM_NO) {
int32_t safeoffset = getNextSafeOffset(strsrch->collator,
text, 0, length);
if (safeoffset != length) {
safeoffset ++;
}
UChar *norm = NULL;
UChar buffer[INITIAL_ARRAY_SIZE_];
int32_t size = unorm_normalize(text, safeoffset, UNORM_NFD, 0,
buffer, INITIAL_ARRAY_SIZE_,
status);
if (U_FAILURE(*status)) {
return FALSE;
}
if (size >= INITIAL_ARRAY_SIZE_) {
norm = (UChar *)allocateMemory((size + 1) * sizeof(UChar),
status);
// if allocation failed, status will be set to
// U_MEMORY_ALLOCATION_ERROR and unorm_normalize internally
// checks for it.
size = unorm_normalize(text, safeoffset, UNORM_NFD, 0, norm,
size, status);
if (U_FAILURE(*status) && norm != NULL) {
uprv_free(norm);
return FALSE;
}
}
else {
norm = buffer;
}
UCollationElements *coleiter = strsrch->utilIter;
ucol_setText(coleiter, norm, size, status);
uint32_t firstce = strsrch->pattern.CE[0];
UBool ignorable = TRUE;
uint32_t ce = UCOL_IGNORABLE;
while (U_SUCCESS(*status) && ce != firstce && ce != (uint32_t)UCOL_NULLORDER) {
offset = ucol_getOffset(coleiter);
if (ce != firstce && ce != UCOL_IGNORABLE) {
ignorable = FALSE;
}
ce = ucol_next(coleiter, status);
}
UChar32 codepoint;
UTF_PREV_CHAR(norm, 0, offset, codepoint);
result = !ignorable && (u_getCombiningClass(codepoint) != 0);
if (norm != buffer) {
uprv_free(norm);
}
}
}
return result;
}
/**
* Used by exact matches, checks if there are accents before the match.
* This is really painful... we have to check that composite characters at
* the start of the matches have to not have any extra accents.
* We check the FCD of the character first, if it starts with an accent and
* the first pattern ce does not match the first ce of the character, we bail.
* Otherwise we try normalizing the first composite
* character and find the immediate decomposed character before the match to
* see if it is an non-ignorable accent.
* Now normalizing the first composite character is enough because we ensure
* that when the match is passed in here with extra beginning ces, the
* first or last ce that match has to occur within the first character.
* E.g. looking for \u0301 acute in \u01FA A ring above and acute,
* checkExtraMatchAccent should fail since there is a middle ring in \u01FA
* Note here that accents checking are slow and cautioned in the API docs.
* @param strsrch string search data
* @param start offset
* @param end offset
* @return TRUE if there are accents on either side of the match,
* FALSE otherwise
*/
static
UBool hasAccentsBeforeMatch(const UStringSearch *strsrch, int32_t start,
int32_t end)
{
if (strsrch->pattern.hasPrefixAccents) {
UCollationElements *coleiter = strsrch->textIter;
UErrorCode status = U_ZERO_ERROR;
// we have been iterating forwards previously
uint32_t ignorable = TRUE;
int32_t firstce = strsrch->pattern.CE[0];
setColEIterOffset(coleiter, start);
int32_t ce = getCE(strsrch, ucol_next(coleiter, &status));
if (U_FAILURE(status)) {
return TRUE;
}
while (ce != firstce) {
if (ce != UCOL_IGNORABLE) {
ignorable = FALSE;
}
ce = getCE(strsrch, ucol_next(coleiter, &status));
if (U_FAILURE(status) || ce == UCOL_NULLORDER) {
return TRUE;
}
}
if (!ignorable && inNormBuf(coleiter)) {
// within normalization buffer, discontiguous handled here
return TRUE;
}
// within text
int32_t temp = start;
// original code
// accent = (getFCD(strsrch->search->text, &temp,
// strsrch->search->textLength)
// >> SECOND_LAST_BYTE_SHIFT_);
// however this code does not work well with VC7 .net in release mode.
// maybe the inlines for getFCD combined with shifting has bugs in
// VC7. anyways this is a work around.
UBool accent = getFCD(strsrch->search->text, &temp,
strsrch->search->textLength) > 0xFF;
if (!accent) {
return checkExtraMatchAccents(strsrch, start, end, &status);
}
if (!ignorable) {
return TRUE;
}
if (start > 0) {
temp = start;
UTF_BACK_1(strsrch->search->text, 0, temp);
if (getFCD(strsrch->search->text, &temp,
strsrch->search->textLength) & LAST_BYTE_MASK_) {
setColEIterOffset(coleiter, start);
ce = ucol_previous(coleiter, &status);
if (U_FAILURE(status) ||
(ce != UCOL_NULLORDER && ce != UCOL_IGNORABLE)) {
return TRUE;
}
}
}
}
return FALSE;
}
/**
* Used by exact matches, checks if there are accents bounding the match.
* Note this is the initial boundary check. If the potential match
* starts or ends with composite characters, the accents in those
* characters will be determined later.
* Not doing backwards iteration here, since discontiguos contraction for
* backwards collation element iterator, use up too many characters.
* E.g. looking for \u030A ring in \u01FA A ring above and acute,
* should fail since there is a acute at the end of \u01FA
* Note here that accents checking are slow and cautioned in the API docs.
* @param strsrch string search data
* @param start offset of match
* @param end end offset of the match
* @return TRUE if there are accents on either side of the match,
* FALSE otherwise
*/
static
UBool hasAccentsAfterMatch(const UStringSearch *strsrch, int32_t start,
int32_t end)
{
if (strsrch->pattern.hasSuffixAccents) {
const UChar *text = strsrch->search->text;
int32_t temp = end;
int32_t textlength = strsrch->search->textLength;
UTF_BACK_1(text, 0, temp);
if (getFCD(text, &temp, textlength) & LAST_BYTE_MASK_) {
int32_t firstce = strsrch->pattern.CE[0];
UCollationElements *coleiter = strsrch->textIter;
UErrorCode status = U_ZERO_ERROR;
int32_t ce;
setColEIterOffset(coleiter, start);
while ((ce = getCE(strsrch, ucol_next(coleiter, &status))) != firstce) {
if (U_FAILURE(status) || ce == UCOL_NULLORDER) {
return TRUE;
}
}
int32_t count = 1;
while (count < strsrch->pattern.CELength) {
if (getCE(strsrch, ucol_next(coleiter, &status))
== UCOL_IGNORABLE) {
// Thai can give an ignorable here.
count --;
}
if (U_FAILURE(status)) {
return TRUE;
}
count ++;
}
ce = ucol_next(coleiter, &status);
if (U_FAILURE(status)) {
return TRUE;
}
if (ce != UCOL_NULLORDER && ce != UCOL_IGNORABLE) {
ce = getCE(strsrch, ce);
}
if (ce != UCOL_NULLORDER && ce != UCOL_IGNORABLE) {
if (ucol_getOffset(coleiter) <= end) {
return TRUE;
}
if (getFCD(text, &end, textlength) >> SECOND_LAST_BYTE_SHIFT_) {
return TRUE;
}
}
}
}
return FALSE;
}
#endif // #if BOYER_MOORE
/**
* Checks if the offset runs out of the text string
* @param offset
* @param textlength of the text string
* @return TRUE if offset is out of bounds, FALSE otherwise
*/
static
inline UBool isOutOfBounds(int32_t textlength, int32_t offset)
{
return offset < 0 || offset > textlength;
}
/**
* Checks for identical match
* @param strsrch string search data
* @param start offset of possible match
* @param end offset of possible match
* @return TRUE if identical match is found
*/
static
inline UBool checkIdentical(const UStringSearch *strsrch, int32_t start,
int32_t end)
{
if (strsrch->strength != UCOL_IDENTICAL) {
return TRUE;
}
// Note: We could use Normalizer::compare() or similar, but for short strings
// which may not be in FCD it might be faster to just NFD them.
UErrorCode status = U_ZERO_ERROR;
UnicodeString t2, p2;
strsrch->nfd->normalize(
UnicodeString(FALSE, strsrch->search->text + start, end - start), t2, status);
strsrch->nfd->normalize(
UnicodeString(FALSE, strsrch->pattern.text, strsrch->pattern.textLength), p2, status);
// return FALSE if NFD failed
return U_SUCCESS(status) && t2 == p2;
}
#if BOYER_MOORE
/**
* Checks to see if the match is repeated
* @param strsrch string search data
* @param start new match start index
* @param end new match end index
* @return TRUE if the the match is repeated, FALSE otherwise
*/
static
inline UBool checkRepeatedMatch(UStringSearch *strsrch,
int32_t start,
int32_t end)
{
int32_t lastmatchindex = strsrch->search->matchedIndex;
UBool result;
if (lastmatchindex == USEARCH_DONE) {
return FALSE;
}
if (strsrch->search->isForwardSearching) {
result = start <= lastmatchindex;
}
else {
result = start >= lastmatchindex;
}
if (!result && !strsrch->search->isOverlap) {
if (strsrch->search->isForwardSearching) {
result = start < lastmatchindex + strsrch->search->matchedLength;
}
else {
result = end > lastmatchindex;
}
}
return result;
}
/**
* Gets the collation element iterator's current offset.
* @param coleiter collation element iterator
* @param forwards flag TRUE if we are moving in th forwards direction
* @return current offset
*/
static
inline int32_t getColElemIterOffset(const UCollationElements *coleiter,
UBool forwards)
{
int32_t result = ucol_getOffset(coleiter);
// intricacies of the the backwards collation element iterator
if (FALSE && !forwards && inNormBuf(coleiter) && !isFCDPointerNull(coleiter)) {
result ++;
}
return result;
}
/**
* Checks match for contraction.
* If the match ends with a partial contraction we fail.
* If the match starts too far off (because of backwards iteration) we try to
* chip off the extra characters depending on whether a breakiterator has
* been used.
* Internal method, error assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param start offset of potential match, to be modified if necessary
* @param end offset of potential match, to be modified if necessary
* @param status output error status if any
* @return TRUE if match passes the contraction test, FALSE otherwise
*/
static
UBool checkNextExactContractionMatch(UStringSearch *strsrch,
int32_t *start,
int32_t *end, UErrorCode *status)
{
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t temp = *start;
const UCollator *collator = strsrch->collator;
const UChar *text = strsrch->search->text;
// This part checks if either ends of the match contains potential
// contraction. If so we'll have to iterate through them
// The start contraction needs to be checked since ucol_previous dumps
// all characters till the first safe character into the buffer.
// *start + 1 is used to test for the unsafe characters instead of *start
// because ucol_prev takes all unsafe characters till the first safe
// character ie *start. so by testing *start + 1, we can estimate if
// excess prefix characters has been included in the potential search
// results.
if ((*end < textlength && ucol_unsafeCP(text[*end], collator)) ||
(*start + 1 < textlength
&& ucol_unsafeCP(text[*start + 1], collator))) {
int32_t expansion = getExpansionPrefix(coleiter);
UBool expandflag = expansion > 0;
setColEIterOffset(coleiter, *start);
while (expansion > 0) {
// getting rid of the redundant ce, caused by setOffset.
// since backward contraction/expansion may have extra ces if we
// are in the normalization buffer, hasAccentsBeforeMatch would
// have taken care of it.
// E.g. the character \u01FA will have an expansion of 3, but if
// we are only looking for acute and ring \u030A and \u0301, we'll
// have to skip the first ce in the expansion buffer.
ucol_next(coleiter, status);
if (U_FAILURE(*status)) {
return FALSE;
}
if (ucol_getOffset(coleiter) != temp) {
*start = temp;
temp = ucol_getOffset(coleiter);
}
expansion --;
}
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t count = 0;
while (count < patterncelength) {
int32_t ce = getCE(strsrch, ucol_next(coleiter, status));
if (ce == UCOL_IGNORABLE) {
continue;
}
if (expandflag && count == 0 && ucol_getOffset(coleiter) != temp) {
*start = temp;
temp = ucol_getOffset(coleiter);
}
if (U_FAILURE(*status) || ce != patternce[count]) {
(*end) ++;
*end = getNextUStringSearchBaseOffset(strsrch, *end);
return FALSE;
}
count ++;
}
}
return TRUE;
}
/**
* Checks and sets the match information if found.
* Checks
* <ul>
* <li> the potential match does not repeat the previous match
* <li> boundaries are correct
* <li> exact matches has no extra accents
* <li> identical matchesb
* <li> potential match does not end in the middle of a contraction
* <\ul>
* Otherwise the offset will be shifted to the next character.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset offset in the collation element text. the returned value
* will be the truncated end offset of the match or the new start
* search offset.
* @param status output error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
inline UBool checkNextExactMatch(UStringSearch *strsrch,
int32_t *textoffset, UErrorCode *status)
{
UCollationElements *coleiter = strsrch->textIter;
int32_t start = getColElemIterOffset(coleiter, FALSE);
if (!checkNextExactContractionMatch(strsrch, &start, textoffset, status)) {
return FALSE;
}
// this totally matches, however we need to check if it is repeating
if (!isBreakUnit(strsrch, start, *textoffset) ||
checkRepeatedMatch(strsrch, start, *textoffset) ||
hasAccentsBeforeMatch(strsrch, start, *textoffset) ||
!checkIdentical(strsrch, start, *textoffset) ||
hasAccentsAfterMatch(strsrch, start, *textoffset)) {
(*textoffset) ++;
*textoffset = getNextUStringSearchBaseOffset(strsrch, *textoffset);
return FALSE;
}
//Add breakiterator boundary check for primary strength search.
if (!strsrch->search->breakIter && strsrch->strength == UCOL_PRIMARY) {
checkBreakBoundary(strsrch, &start, textoffset);
}
// totally match, we will get rid of the ending ignorables.
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = *textoffset - start;
return TRUE;
}
/**
* Getting the previous base character offset, or the current offset if the
* current character is a base character
* @param text string
* @param textoffset one offset after the current character
* @return the offset of the next character after the base character or the first
* composed character with accents
*/
static
inline int32_t getPreviousBaseOffset(const UChar *text,
int32_t textoffset)
{
if (textoffset > 0) {
for (;;) {
int32_t result = textoffset;
UTF_BACK_1(text, 0, textoffset);
int32_t temp = textoffset;
uint16_t fcd = getFCD(text, &temp, result);
if ((fcd >> SECOND_LAST_BYTE_SHIFT_) == 0) {
if (fcd & LAST_BYTE_MASK_) {
return textoffset;
}
return result;
}
if (textoffset == 0) {
return 0;
}
}
}
return textoffset;
}
/**
* Getting the indexes of the accents that are not blocked in the argument
* accent array
* @param accents array of accents in nfd terminated by a 0.
* @param accentsindex array of indexes of the accents that are not blocked
*/
static
inline int getUnblockedAccentIndex(UChar *accents, int32_t *accentsindex)
{
int32_t index = 0;
int32_t length = u_strlen(accents);
UChar32 codepoint = 0;
int cclass = 0;
int result = 0;
int32_t temp;
while (index < length) {
temp = index;
UTF_NEXT_CHAR(accents, index, length, codepoint);
if (u_getCombiningClass(codepoint) != cclass) {
cclass = u_getCombiningClass(codepoint);
accentsindex[result] = temp;
result ++;
}
}
accentsindex[result] = length;
return result;
}
/**
* Appends 3 UChar arrays to a destination array.
* Creates a new array if we run out of space. The caller will have to
* manually deallocate the newly allocated array.
* Internal method, status assumed to be success, caller has to check status
* before calling this method. destination not to be NULL and has at least
* size destinationlength.
* @param destination target array
* @param destinationlength target array size, returning the appended length
* @param source1 null-terminated first array
* @param source2 second array
* @param source2length length of seond array
* @param source3 null-terminated third array
* @param status error status if any
* @return new destination array, destination if there was no new allocation
*/
static
inline UChar * addToUCharArray( UChar *destination,
int32_t *destinationlength,
const UChar *source1,
const UChar *source2,
int32_t source2length,
const UChar *source3,
UErrorCode *status)
{
int32_t source1length = source1 ? u_strlen(source1) : 0;
int32_t source3length = source3 ? u_strlen(source3) : 0;
if (*destinationlength < source1length + source2length + source3length +
1)
{
destination = (UChar *)allocateMemory(
(source1length + source2length + source3length + 1) * sizeof(UChar),
status);
// if error allocating memory, status will be
// U_MEMORY_ALLOCATION_ERROR
if (U_FAILURE(*status)) {
*destinationlength = 0;
return NULL;
}
}
if (source1length != 0) {
uprv_memcpy(destination, source1, sizeof(UChar) * source1length);
}
if (source2length != 0) {
uprv_memcpy(destination + source1length, source2,
sizeof(UChar) * source2length);
}
if (source3length != 0) {
uprv_memcpy(destination + source1length + source2length, source3,
sizeof(UChar) * source3length);
}
*destinationlength = source1length + source2length + source3length;
return destination;
}
/**
* Running through a collation element iterator to see if the contents matches
* pattern in string search data
* @param strsrch string search data
* @param coleiter collation element iterator
* @return TRUE if a match if found, FALSE otherwise
*/
static
inline UBool checkCollationMatch(const UStringSearch *strsrch,
UCollationElements *coleiter)
{
int patternceindex = strsrch->pattern.CELength;
int32_t *patternce = strsrch->pattern.CE;
UErrorCode status = U_ZERO_ERROR;
while (patternceindex > 0) {
int32_t ce = getCE(strsrch, ucol_next(coleiter, &status));
if (ce == UCOL_IGNORABLE) {
continue;
}
if (U_FAILURE(status) || ce != *patternce) {
return FALSE;
}
patternce ++;
patternceindex --;
}
return TRUE;
}
/**
* Rearranges the front accents to try matching.
* Prefix accents in the text will be grouped according to their combining
* class and the groups will be mixed and matched to try find the perfect
* match with the pattern.
* So for instance looking for "\u0301" in "\u030A\u0301\u0325"
* step 1: split "\u030A\u0301" into 6 other type of potential accent substrings
* "\u030A", "\u0301", "\u0325", "\u030A\u0301", "\u030A\u0325",
* "\u0301\u0325".
* step 2: check if any of the generated substrings matches the pattern.
* Internal method, status is assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search match
* @param start first offset of the accents to start searching
* @param end start of the last accent set
* @param status output error status if any
* @return USEARCH_DONE if a match is not found, otherwise return the starting
* offset of the match. Note this start includes all preceding accents.
*/
static
int32_t doNextCanonicalPrefixMatch(UStringSearch *strsrch,
int32_t start,
int32_t end,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
int32_t textlength = strsrch->search->textLength;
int32_t tempstart = start;
if ((getFCD(text, &tempstart, textlength) & LAST_BYTE_MASK_) == 0) {
// die... failed at a base character
return USEARCH_DONE;
}
int32_t offset = getNextBaseOffset(text, tempstart, textlength);
start = getPreviousBaseOffset(text, tempstart);
UChar accents[INITIAL_ARRAY_SIZE_];
// normalizing the offensive string
unorm_normalize(text + start, offset - start, UNORM_NFD, 0, accents,
INITIAL_ARRAY_SIZE_, status);
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
int32_t accentsindex[INITIAL_ARRAY_SIZE_];
int32_t accentsize = getUnblockedAccentIndex(accents,
accentsindex);
int32_t count = (2 << (accentsize - 1)) - 1;
UChar buffer[INITIAL_ARRAY_SIZE_];
UCollationElements *coleiter = strsrch->utilIter;
while (U_SUCCESS(*status) && count > 0) {
UChar *rearrange = strsrch->canonicalPrefixAccents;
// copy the base characters
for (int k = 0; k < accentsindex[0]; k ++) {
*rearrange ++ = accents[k];
}
// forming all possible canonical rearrangement by dropping
// sets of accents
for (int i = 0; i <= accentsize - 1; i ++) {
int32_t mask = 1 << (accentsize - i - 1);
if (count & mask) {
for (int j = accentsindex[i]; j < accentsindex[i + 1]; j ++) {
*rearrange ++ = accents[j];
}
}
}
*rearrange = 0;
int32_t matchsize = INITIAL_ARRAY_SIZE_;
UChar *match = addToUCharArray(buffer, &matchsize,
strsrch->canonicalPrefixAccents,
strsrch->search->text + offset,
end - offset,
strsrch->canonicalSuffixAccents,
status);
// if status is a failure, ucol_setText does nothing.
// run the collator iterator through this match
ucol_setText(coleiter, match, matchsize, status);
if (U_SUCCESS(*status)) {
if (checkCollationMatch(strsrch, coleiter)) {
if (match != buffer) {
uprv_free(match);
}
return start;
}
}
count --;
}
return USEARCH_DONE;
}
/**
* Gets the offset to the safe point in text before textoffset.
* ie. not the middle of a contraction, swappable characters or supplementary
* characters.
* @param collator collation sata
* @param text string to work with
* @param textoffset offset in string
* @param textlength length of text string
* @return offset to the previous safe character
*/
static
inline uint32_t getPreviousSafeOffset(const UCollator *collator,
const UChar *text,
int32_t textoffset)
{
int32_t result = textoffset; // first contraction character
while (result != 0 && ucol_unsafeCP(text[result - 1], collator)) {
result --;
}
if (result != 0) {
// the first contraction character is consider unsafe here
result --;
}
return result;
}
/**
* Cleaning up after we passed the safe zone
* @param strsrch string search data
* @param safetext safe text array
* @param safebuffer safe text buffer
* @param coleiter collation element iterator for safe text
*/
static
inline void cleanUpSafeText(const UStringSearch *strsrch, UChar *safetext,
UChar *safebuffer)
{
if (safetext != safebuffer && safetext != strsrch->canonicalSuffixAccents)
{
uprv_free(safetext);
}
}
/**
* Take the rearranged end accents and tries matching. If match failed at
* a seperate preceding set of accents (seperated from the rearranged on by
* at least a base character) then we rearrange the preceding accents and
* tries matching again.
* We allow skipping of the ends of the accent set if the ces do not match.
* However if the failure is found before the accent set, it fails.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset of the start of the rearranged accent
* @param status output error status if any
* @return USEARCH_DONE if a match is not found, otherwise return the starting
* offset of the match. Note this start includes all preceding accents.
*/
static
int32_t doNextCanonicalSuffixMatch(UStringSearch *strsrch,
int32_t textoffset,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
const UCollator *collator = strsrch->collator;
int32_t safelength = 0;
UChar *safetext;
int32_t safetextlength;
UChar safebuffer[INITIAL_ARRAY_SIZE_];
UCollationElements *coleiter = strsrch->utilIter;
int32_t safeoffset = textoffset;
if (textoffset != 0 && ucol_unsafeCP(strsrch->canonicalSuffixAccents[0],
collator)) {
safeoffset = getPreviousSafeOffset(collator, text, textoffset);
safelength = textoffset - safeoffset;
safetextlength = INITIAL_ARRAY_SIZE_;
safetext = addToUCharArray(safebuffer, &safetextlength, NULL,
text + safeoffset, safelength,
strsrch->canonicalSuffixAccents,
status);
}
else {
safetextlength = u_strlen(strsrch->canonicalSuffixAccents);
safetext = strsrch->canonicalSuffixAccents;
}
// if status is a failure, ucol_setText does nothing
ucol_setText(coleiter, safetext, safetextlength, status);
// status checked in loop below
int32_t *ce = strsrch->pattern.CE;
int32_t celength = strsrch->pattern.CELength;
int ceindex = celength - 1;
UBool isSafe = TRUE; // indication flag for position in safe zone
while (ceindex >= 0) {
int32_t textce = ucol_previous(coleiter, status);
if (U_FAILURE(*status)) {
if (isSafe) {
cleanUpSafeText(strsrch, safetext, safebuffer);
}
return USEARCH_DONE;
}
if (textce == UCOL_NULLORDER) {
// check if we have passed the safe buffer
if (coleiter == strsrch->textIter) {
cleanUpSafeText(strsrch, safetext, safebuffer);
return USEARCH_DONE;
}
cleanUpSafeText(strsrch, safetext, safebuffer);
safetext = safebuffer;
coleiter = strsrch->textIter;
setColEIterOffset(coleiter, safeoffset);
// status checked at the start of the loop
isSafe = FALSE;
continue;
}
textce = getCE(strsrch, textce);
if (textce != UCOL_IGNORABLE && textce != ce[ceindex]) {
// do the beginning stuff
int32_t failedoffset = getColElemIterOffset(coleiter, FALSE);
if (isSafe && failedoffset >= safelength) {
// alas... no hope. failed at rearranged accent set
cleanUpSafeText(strsrch, safetext, safebuffer);
return USEARCH_DONE;
}
else {
if (isSafe) {
failedoffset += safeoffset;
cleanUpSafeText(strsrch, safetext, safebuffer);
}
// try rearranging the front accents
int32_t result = doNextCanonicalPrefixMatch(strsrch,
failedoffset, textoffset, status);
if (result != USEARCH_DONE) {
// if status is a failure, ucol_setOffset does nothing
setColEIterOffset(strsrch->textIter, result);
}
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
return result;
}
}
if (textce == ce[ceindex]) {
ceindex --;
}
}
// set offset here
if (isSafe) {
int32_t result = getColElemIterOffset(coleiter, FALSE);
// sets the text iterator here with the correct expansion and offset
int32_t leftoverces = getExpansionPrefix(coleiter);
cleanUpSafeText(strsrch, safetext, safebuffer);
if (result >= safelength) {
result = textoffset;
}
else {
result += safeoffset;
}
setColEIterOffset(strsrch->textIter, result);
strsrch->textIter->iteratordata_.toReturn =
setExpansionPrefix(strsrch->textIter, leftoverces);
return result;
}
return ucol_getOffset(coleiter);
}
/**
* Trying out the substring and sees if it can be a canonical match.
* This will try normalizing the end accents and arranging them into canonical
* equivalents and check their corresponding ces with the pattern ce.
* Suffix accents in the text will be grouped according to their combining
* class and the groups will be mixed and matched to try find the perfect
* match with the pattern.
* So for instance looking for "\u0301" in "\u030A\u0301\u0325"
* step 1: split "\u030A\u0301" into 6 other type of potential accent substrings
* "\u030A", "\u0301", "\u0325", "\u030A\u0301", "\u030A\u0325",
* "\u0301\u0325".
* step 2: check if any of the generated substrings matches the pattern.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset end offset in the collation element text that ends with
* the accents to be rearranged
* @param status error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
UBool doNextCanonicalMatch(UStringSearch *strsrch,
int32_t textoffset,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
int32_t temp = textoffset;
UTF_BACK_1(text, 0, temp);
if ((getFCD(text, &temp, textoffset) & LAST_BYTE_MASK_) == 0) {
UCollationElements *coleiter = strsrch->textIter;
int32_t offset = getColElemIterOffset(coleiter, FALSE);
if (strsrch->pattern.hasPrefixAccents) {
offset = doNextCanonicalPrefixMatch(strsrch, offset, textoffset,
status);
if (U_SUCCESS(*status) && offset != USEARCH_DONE) {
setColEIterOffset(coleiter, offset);
return TRUE;
}
}
return FALSE;
}
if (!strsrch->pattern.hasSuffixAccents) {
return FALSE;
}
UChar accents[INITIAL_ARRAY_SIZE_];
// offset to the last base character in substring to search
int32_t baseoffset = getPreviousBaseOffset(text, textoffset);
// normalizing the offensive string
unorm_normalize(text + baseoffset, textoffset - baseoffset, UNORM_NFD,
0, accents, INITIAL_ARRAY_SIZE_, status);
// status checked in loop below
int32_t accentsindex[INITIAL_ARRAY_SIZE_];
int32_t size = getUnblockedAccentIndex(accents, accentsindex);
// 2 power n - 1 plus the full set of accents
int32_t count = (2 << (size - 1)) - 1;
while (U_SUCCESS(*status) && count > 0) {
UChar *rearrange = strsrch->canonicalSuffixAccents;
// copy the base characters
for (int k = 0; k < accentsindex[0]; k ++) {
*rearrange ++ = accents[k];
}
// forming all possible canonical rearrangement by dropping
// sets of accents
for (int i = 0; i <= size - 1; i ++) {
int32_t mask = 1 << (size - i - 1);
if (count & mask) {
for (int j = accentsindex[i]; j < accentsindex[i + 1]; j ++) {
*rearrange ++ = accents[j];
}
}
}
*rearrange = 0;
int32_t offset = doNextCanonicalSuffixMatch(strsrch, baseoffset,
status);
if (offset != USEARCH_DONE) {
return TRUE; // match found
}
count --;
}
return FALSE;
}
/**
* Gets the previous base character offset depending on the string search
* pattern data
* @param strsrch string search data
* @param textoffset current offset, current character
* @return the offset of the next character after this base character or itself
* if it is a composed character with accents
*/
static
inline int32_t getPreviousUStringSearchBaseOffset(UStringSearch *strsrch,
int32_t textoffset)
{
if (strsrch->pattern.hasPrefixAccents && textoffset > 0) {
const UChar *text = strsrch->search->text;
int32_t offset = textoffset;
if (getFCD(text, &offset, strsrch->search->textLength) >>
SECOND_LAST_BYTE_SHIFT_) {
return getPreviousBaseOffset(text, textoffset);
}
}
return textoffset;
}
/**
* Checks match for contraction.
* If the match ends with a partial contraction we fail.
* If the match starts too far off (because of backwards iteration) we try to
* chip off the extra characters
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param start offset of potential match, to be modified if necessary
* @param end offset of potential match, to be modified if necessary
* @param status output error status if any
* @return TRUE if match passes the contraction test, FALSE otherwise
*/
static
UBool checkNextCanonicalContractionMatch(UStringSearch *strsrch,
int32_t *start,
int32_t *end,
UErrorCode *status)
{
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t temp = *start;
const UCollator *collator = strsrch->collator;
const UChar *text = strsrch->search->text;
// This part checks if either ends of the match contains potential
// contraction. If so we'll have to iterate through them
if ((*end < textlength && ucol_unsafeCP(text[*end], collator)) ||
(*start + 1 < textlength
&& ucol_unsafeCP(text[*start + 1], collator))) {
int32_t expansion = getExpansionPrefix(coleiter);
UBool expandflag = expansion > 0;
setColEIterOffset(coleiter, *start);
while (expansion > 0) {
// getting rid of the redundant ce, caused by setOffset.
// since backward contraction/expansion may have extra ces if we
// are in the normalization buffer, hasAccentsBeforeMatch would
// have taken care of it.
// E.g. the character \u01FA will have an expansion of 3, but if
// we are only looking for acute and ring \u030A and \u0301, we'll
// have to skip the first ce in the expansion buffer.
ucol_next(coleiter, status);
if (U_FAILURE(*status)) {
return FALSE;
}
if (ucol_getOffset(coleiter) != temp) {
*start = temp;
temp = ucol_getOffset(coleiter);
}
expansion --;
}
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t count = 0;
int32_t textlength = strsrch->search->textLength;
while (count < patterncelength) {
int32_t ce = getCE(strsrch, ucol_next(coleiter, status));
// status checked below, note that if status is a failure
// ucol_next returns UCOL_NULLORDER
if (ce == UCOL_IGNORABLE) {
continue;
}
if (expandflag && count == 0 && ucol_getOffset(coleiter) != temp) {
*start = temp;
temp = ucol_getOffset(coleiter);
}
if (count == 0 && ce != patternce[0]) {
// accents may have extra starting ces, this occurs when a
// pure accent pattern is matched without rearrangement
// text \u0325\u0300 and looking for \u0300
int32_t expected = patternce[0];
if (getFCD(text, start, textlength) & LAST_BYTE_MASK_) {
ce = getCE(strsrch, ucol_next(coleiter, status));
while (U_SUCCESS(*status) && ce != expected &&
ce != UCOL_NULLORDER &&
ucol_getOffset(coleiter) <= *end) {
ce = getCE(strsrch, ucol_next(coleiter, status));
}
}
}
if (U_FAILURE(*status) || ce != patternce[count]) {
(*end) ++;
*end = getNextUStringSearchBaseOffset(strsrch, *end);
return FALSE;
}
count ++;
}
}
return TRUE;
}
/**
* Checks and sets the match information if found.
* Checks
* <ul>
* <li> the potential match does not repeat the previous match
* <li> boundaries are correct
* <li> potential match does not end in the middle of a contraction
* <li> identical matches
* <\ul>
* Otherwise the offset will be shifted to the next character.
* Internal method, status assumed to be success, caller has to check the
* status before calling this method.
* @param strsrch string search data
* @param textoffset offset in the collation element text. the returned value
* will be the truncated end offset of the match or the new start
* search offset.
* @param status output error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
inline UBool checkNextCanonicalMatch(UStringSearch *strsrch,
int32_t *textoffset,
UErrorCode *status)
{
// to ensure that the start and ends are not composite characters
UCollationElements *coleiter = strsrch->textIter;
// if we have a canonical accent match
if ((strsrch->pattern.hasSuffixAccents &&
strsrch->canonicalSuffixAccents[0]) ||
(strsrch->pattern.hasPrefixAccents &&
strsrch->canonicalPrefixAccents[0])) {
strsrch->search->matchedIndex = getPreviousUStringSearchBaseOffset(
strsrch,
ucol_getOffset(coleiter));
strsrch->search->matchedLength = *textoffset -
strsrch->search->matchedIndex;
return TRUE;
}
int32_t start = getColElemIterOffset(coleiter, FALSE);
if (!checkNextCanonicalContractionMatch(strsrch, &start, textoffset,
status) || U_FAILURE(*status)) {
return FALSE;
}
start = getPreviousUStringSearchBaseOffset(strsrch, start);
// this totally matches, however we need to check if it is repeating
if (checkRepeatedMatch(strsrch, start, *textoffset) ||
!isBreakUnit(strsrch, start, *textoffset) ||
!checkIdentical(strsrch, start, *textoffset)) {
(*textoffset) ++;
*textoffset = getNextBaseOffset(strsrch->search->text, *textoffset,
strsrch->search->textLength);
return FALSE;
}
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = *textoffset - start;
return TRUE;
}
/**
* Shifting the collation element iterator position forward to prepare for
* a preceding match. If the first character is a unsafe character, we'll only
* shift by 1 to capture contractions, normalization etc.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param text strsrch string search data
* @param textoffset start text position to do search
* @param ce the text ce which failed the match.
* @param patternceindex index of the ce within the pattern ce buffer which
* failed the match
* @return final offset
*/
static
inline int32_t reverseShift(UStringSearch *strsrch,
int32_t textoffset,
int32_t ce,
int32_t patternceindex)
{
if (strsrch->search->isOverlap) {
if (textoffset != strsrch->search->textLength) {
textoffset --;
}
else {
textoffset -= strsrch->pattern.defaultShiftSize;
}
}
else {
if (ce != UCOL_NULLORDER) {
int32_t shift = strsrch->pattern.backShift[hash(ce)];
// this is to adjust for characters in the middle of the substring
// for matching that failed.
int32_t adjust = patternceindex;
if (adjust > 1 && shift > adjust) {
shift -= adjust - 1;
}
textoffset -= shift;
}
else {
textoffset -= strsrch->pattern.defaultShiftSize;
}
}
textoffset = getPreviousUStringSearchBaseOffset(strsrch, textoffset);
return textoffset;
}
/**
* Checks match for contraction.
* If the match starts with a partial contraction we fail.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param start offset of potential match, to be modified if necessary
* @param end offset of potential match, to be modified if necessary
* @param status output error status if any
* @return TRUE if match passes the contraction test, FALSE otherwise
*/
static
UBool checkPreviousExactContractionMatch(UStringSearch *strsrch,
int32_t *start,
int32_t *end, UErrorCode *status)
{
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t temp = *end;
const UCollator *collator = strsrch->collator;
const UChar *text = strsrch->search->text;
// This part checks if either if the start of the match contains potential
// contraction. If so we'll have to iterate through them
// Since we used ucol_next while previously looking for the potential
// match, this guarantees that our end will not be a partial contraction,
// or a partial supplementary character.
if (*start < textlength && ucol_unsafeCP(text[*start], collator)) {
int32_t expansion = getExpansionSuffix(coleiter);
UBool expandflag = expansion > 0;
setColEIterOffset(coleiter, *end);
while (U_SUCCESS(*status) && expansion > 0) {
// getting rid of the redundant ce
// since forward contraction/expansion may have extra ces
// if we are in the normalization buffer, hasAccentsBeforeMatch
// would have taken care of it.
// E.g. the character \u01FA will have an expansion of 3, but if
// we are only looking for A ring A\u030A, we'll have to skip the
// last ce in the expansion buffer
ucol_previous(coleiter, status);
if (U_FAILURE(*status)) {
return FALSE;
}
if (ucol_getOffset(coleiter) != temp) {
*end = temp;
temp = ucol_getOffset(coleiter);
}
expansion --;
}
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t count = patterncelength;
while (count > 0) {
int32_t ce = getCE(strsrch, ucol_previous(coleiter, status));
// status checked below, note that if status is a failure
// ucol_previous returns UCOL_NULLORDER
if (ce == UCOL_IGNORABLE) {
continue;
}
if (expandflag && count == 0 &&
getColElemIterOffset(coleiter, FALSE) != temp) {
*end = temp;
temp = ucol_getOffset(coleiter);
}
if (U_FAILURE(*status) || ce != patternce[count - 1]) {
(*start) --;
*start = getPreviousBaseOffset(text, *start);
return FALSE;
}
count --;
}
}
return TRUE;
}
/**
* Checks and sets the match information if found.
* Checks
* <ul>
* <li> the current match does not repeat the last match
* <li> boundaries are correct
* <li> exact matches has no extra accents
* <li> identical matches
* <\ul>
* Otherwise the offset will be shifted to the preceding character.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param collator
* @param coleiter collation element iterator
* @param text string
* @param textoffset offset in the collation element text. the returned value
* will be the truncated start offset of the match or the new start
* search offset.
* @param status output error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
inline UBool checkPreviousExactMatch(UStringSearch *strsrch,
int32_t *textoffset,
UErrorCode *status)
{
// to ensure that the start and ends are not composite characters
int32_t end = ucol_getOffset(strsrch->textIter);
if (!checkPreviousExactContractionMatch(strsrch, textoffset, &end, status)
|| U_FAILURE(*status)) {
return FALSE;
}
// this totally matches, however we need to check if it is repeating
// the old match
if (checkRepeatedMatch(strsrch, *textoffset, end) ||
!isBreakUnit(strsrch, *textoffset, end) ||
hasAccentsBeforeMatch(strsrch, *textoffset, end) ||
!checkIdentical(strsrch, *textoffset, end) ||
hasAccentsAfterMatch(strsrch, *textoffset, end)) {
(*textoffset) --;
*textoffset = getPreviousBaseOffset(strsrch->search->text,
*textoffset);
return FALSE;
}
//Add breakiterator boundary check for primary strength search.
if (!strsrch->search->breakIter && strsrch->strength == UCOL_PRIMARY) {
checkBreakBoundary(strsrch, textoffset, &end);
}
strsrch->search->matchedIndex = *textoffset;
strsrch->search->matchedLength = end - *textoffset;
return TRUE;
}
/**
* Rearranges the end accents to try matching.
* Suffix accents in the text will be grouped according to their combining
* class and the groups will be mixed and matched to try find the perfect
* match with the pattern.
* So for instance looking for "\u0301" in "\u030A\u0301\u0325"
* step 1: split "\u030A\u0301" into 6 other type of potential accent substrings
* "\u030A", "\u0301", "\u0325", "\u030A\u0301", "\u030A\u0325",
* "\u0301\u0325".
* step 2: check if any of the generated substrings matches the pattern.
* Internal method, status assumed to be success, user has to check status
* before calling this method.
* @param strsrch string search match
* @param start offset of the first base character
* @param end start of the last accent set
* @param status only error status if any
* @return USEARCH_DONE if a match is not found, otherwise return the ending
* offset of the match. Note this start includes all following accents.
*/
static
int32_t doPreviousCanonicalSuffixMatch(UStringSearch *strsrch,
int32_t start,
int32_t end,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
int32_t tempend = end;
UTF_BACK_1(text, 0, tempend);
if (!(getFCD(text, &tempend, strsrch->search->textLength) &
LAST_BYTE_MASK_)) {
// die... failed at a base character
return USEARCH_DONE;
}
end = getNextBaseOffset(text, end, strsrch->search->textLength);
if (U_SUCCESS(*status)) {
UChar accents[INITIAL_ARRAY_SIZE_];
int32_t offset = getPreviousBaseOffset(text, end);
// normalizing the offensive string
unorm_normalize(text + offset, end - offset, UNORM_NFD, 0, accents,
INITIAL_ARRAY_SIZE_, status);
int32_t accentsindex[INITIAL_ARRAY_SIZE_];
int32_t accentsize = getUnblockedAccentIndex(accents,
accentsindex);
int32_t count = (2 << (accentsize - 1)) - 1;
UChar buffer[INITIAL_ARRAY_SIZE_];
UCollationElements *coleiter = strsrch->utilIter;
while (U_SUCCESS(*status) && count > 0) {
UChar *rearrange = strsrch->canonicalSuffixAccents;
// copy the base characters
for (int k = 0; k < accentsindex[0]; k ++) {
*rearrange ++ = accents[k];
}
// forming all possible canonical rearrangement by dropping
// sets of accents
for (int i = 0; i <= accentsize - 1; i ++) {
int32_t mask = 1 << (accentsize - i - 1);
if (count & mask) {
for (int j = accentsindex[i]; j < accentsindex[i + 1]; j ++) {
*rearrange ++ = accents[j];
}
}
}
*rearrange = 0;
int32_t matchsize = INITIAL_ARRAY_SIZE_;
UChar *match = addToUCharArray(buffer, &matchsize,
strsrch->canonicalPrefixAccents,
strsrch->search->text + start,
offset - start,
strsrch->canonicalSuffixAccents,
status);
// run the collator iterator through this match
// if status is a failure ucol_setText does nothing
ucol_setText(coleiter, match, matchsize, status);
if (U_SUCCESS(*status)) {
if (checkCollationMatch(strsrch, coleiter)) {
if (match != buffer) {
uprv_free(match);
}
return end;
}
}
count --;
}
}
return USEARCH_DONE;
}
/**
* Take the rearranged start accents and tries matching. If match failed at
* a seperate following set of accents (seperated from the rearranged on by
* at least a base character) then we rearrange the preceding accents and
* tries matching again.
* We allow skipping of the ends of the accent set if the ces do not match.
* However if the failure is found before the accent set, it fails.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset of the ends of the rearranged accent
* @param status output error status if any
* @return USEARCH_DONE if a match is not found, otherwise return the ending
* offset of the match. Note this start includes all following accents.
*/
static
int32_t doPreviousCanonicalPrefixMatch(UStringSearch *strsrch,
int32_t textoffset,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
const UCollator *collator = strsrch->collator;
int32_t safelength = 0;
UChar *safetext;
int32_t safetextlength;
UChar safebuffer[INITIAL_ARRAY_SIZE_];
int32_t safeoffset = textoffset;
if (textoffset &&
ucol_unsafeCP(strsrch->canonicalPrefixAccents[
u_strlen(strsrch->canonicalPrefixAccents) - 1
], collator)) {
safeoffset = getNextSafeOffset(collator, text, textoffset,
strsrch->search->textLength);
safelength = safeoffset - textoffset;
safetextlength = INITIAL_ARRAY_SIZE_;
safetext = addToUCharArray(safebuffer, &safetextlength,
strsrch->canonicalPrefixAccents,
text + textoffset, safelength,
NULL, status);
}
else {
safetextlength = u_strlen(strsrch->canonicalPrefixAccents);
safetext = strsrch->canonicalPrefixAccents;
}
UCollationElements *coleiter = strsrch->utilIter;
// if status is a failure, ucol_setText does nothing
ucol_setText(coleiter, safetext, safetextlength, status);
// status checked in loop below
int32_t *ce = strsrch->pattern.CE;
int32_t celength = strsrch->pattern.CELength;
int ceindex = 0;
UBool isSafe = TRUE; // safe zone indication flag for position
int32_t prefixlength = u_strlen(strsrch->canonicalPrefixAccents);
while (ceindex < celength) {
int32_t textce = ucol_next(coleiter, status);
if (U_FAILURE(*status)) {
if (isSafe) {
cleanUpSafeText(strsrch, safetext, safebuffer);
}
return USEARCH_DONE;
}
if (textce == UCOL_NULLORDER) {
// check if we have passed the safe buffer
if (coleiter == strsrch->textIter) {
cleanUpSafeText(strsrch, safetext, safebuffer);
return USEARCH_DONE;
}
cleanUpSafeText(strsrch, safetext, safebuffer);
safetext = safebuffer;
coleiter = strsrch->textIter;
setColEIterOffset(coleiter, safeoffset);
// status checked at the start of the loop
isSafe = FALSE;
continue;
}
textce = getCE(strsrch, textce);
if (textce != UCOL_IGNORABLE && textce != ce[ceindex]) {
// do the beginning stuff
int32_t failedoffset = ucol_getOffset(coleiter);
if (isSafe && failedoffset <= prefixlength) {
// alas... no hope. failed at rearranged accent set
cleanUpSafeText(strsrch, safetext, safebuffer);
return USEARCH_DONE;
}
else {
if (isSafe) {
failedoffset = safeoffset - failedoffset;
cleanUpSafeText(strsrch, safetext, safebuffer);
}
// try rearranging the end accents
int32_t result = doPreviousCanonicalSuffixMatch(strsrch,
textoffset, failedoffset, status);
if (result != USEARCH_DONE) {
// if status is a failure, ucol_setOffset does nothing
setColEIterOffset(strsrch->textIter, result);
}
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
return result;
}
}
if (textce == ce[ceindex]) {
ceindex ++;
}
}
// set offset here
if (isSafe) {
int32_t result = ucol_getOffset(coleiter);
// sets the text iterator here with the correct expansion and offset
int32_t leftoverces = getExpansionSuffix(coleiter);
cleanUpSafeText(strsrch, safetext, safebuffer);
if (result <= prefixlength) {
result = textoffset;
}
else {
result = textoffset + (safeoffset - result);
}
setColEIterOffset(strsrch->textIter, result);
setExpansionSuffix(strsrch->textIter, leftoverces);
return result;
}
return ucol_getOffset(coleiter);
}
/**
* Trying out the substring and sees if it can be a canonical match.
* This will try normalizing the starting accents and arranging them into
* canonical equivalents and check their corresponding ces with the pattern ce.
* Prefix accents in the text will be grouped according to their combining
* class and the groups will be mixed and matched to try find the perfect
* match with the pattern.
* So for instance looking for "\u0301" in "\u030A\u0301\u0325"
* step 1: split "\u030A\u0301" into 6 other type of potential accent substrings
* "\u030A", "\u0301", "\u0325", "\u030A\u0301", "\u030A\u0325",
* "\u0301\u0325".
* step 2: check if any of the generated substrings matches the pattern.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset start offset in the collation element text that starts
* with the accents to be rearranged
* @param status output error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
UBool doPreviousCanonicalMatch(UStringSearch *strsrch,
int32_t textoffset,
UErrorCode *status)
{
const UChar *text = strsrch->search->text;
int32_t temp = textoffset;
int32_t textlength = strsrch->search->textLength;
if ((getFCD(text, &temp, textlength) >> SECOND_LAST_BYTE_SHIFT_) == 0) {
UCollationElements *coleiter = strsrch->textIter;
int32_t offset = ucol_getOffset(coleiter);
if (strsrch->pattern.hasSuffixAccents) {
offset = doPreviousCanonicalSuffixMatch(strsrch, textoffset,
offset, status);
if (U_SUCCESS(*status) && offset != USEARCH_DONE) {
setColEIterOffset(coleiter, offset);
return TRUE;
}
}
return FALSE;
}
if (!strsrch->pattern.hasPrefixAccents) {
return FALSE;
}
UChar accents[INITIAL_ARRAY_SIZE_];
// offset to the last base character in substring to search
int32_t baseoffset = getNextBaseOffset(text, textoffset, textlength);
// normalizing the offensive string
unorm_normalize(text + textoffset, baseoffset - textoffset, UNORM_NFD,
0, accents, INITIAL_ARRAY_SIZE_, status);
// status checked in loop
int32_t accentsindex[INITIAL_ARRAY_SIZE_];
int32_t size = getUnblockedAccentIndex(accents, accentsindex);
// 2 power n - 1 plus the full set of accents
int32_t count = (2 << (size - 1)) - 1;
while (U_SUCCESS(*status) && count > 0) {
UChar *rearrange = strsrch->canonicalPrefixAccents;
// copy the base characters
for (int k = 0; k < accentsindex[0]; k ++) {
*rearrange ++ = accents[k];
}
// forming all possible canonical rearrangement by dropping
// sets of accents
for (int i = 0; i <= size - 1; i ++) {
int32_t mask = 1 << (size - i - 1);
if (count & mask) {
for (int j = accentsindex[i]; j < accentsindex[i + 1]; j ++) {
*rearrange ++ = accents[j];
}
}
}
*rearrange = 0;
int32_t offset = doPreviousCanonicalPrefixMatch(strsrch,
baseoffset, status);
if (offset != USEARCH_DONE) {
return TRUE; // match found
}
count --;
}
return FALSE;
}
/**
* Checks match for contraction.
* If the match starts with a partial contraction we fail.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param start offset of potential match, to be modified if necessary
* @param end offset of potential match, to be modified if necessary
* @param status only error status if any
* @return TRUE if match passes the contraction test, FALSE otherwise
*/
static
UBool checkPreviousCanonicalContractionMatch(UStringSearch *strsrch,
int32_t *start,
int32_t *end, UErrorCode *status)
{
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t temp = *end;
const UCollator *collator = strsrch->collator;
const UChar *text = strsrch->search->text;
// This part checks if either if the start of the match contains potential
// contraction. If so we'll have to iterate through them
// Since we used ucol_next while previously looking for the potential
// match, this guarantees that our end will not be a partial contraction,
// or a partial supplementary character.
if (*start < textlength && ucol_unsafeCP(text[*start], collator)) {
int32_t expansion = getExpansionSuffix(coleiter);
UBool expandflag = expansion > 0;
setColEIterOffset(coleiter, *end);
while (expansion > 0) {
// getting rid of the redundant ce
// since forward contraction/expansion may have extra ces
// if we are in the normalization buffer, hasAccentsBeforeMatch
// would have taken care of it.
// E.g. the character \u01FA will have an expansion of 3, but if
// we are only looking for A ring A\u030A, we'll have to skip the
// last ce in the expansion buffer
ucol_previous(coleiter, status);
if (U_FAILURE(*status)) {
return FALSE;
}
if (ucol_getOffset(coleiter) != temp) {
*end = temp;
temp = ucol_getOffset(coleiter);
}
expansion --;
}
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t count = patterncelength;
while (count > 0) {
int32_t ce = getCE(strsrch, ucol_previous(coleiter, status));
// status checked below, note that if status is a failure
// ucol_previous returns UCOL_NULLORDER
if (ce == UCOL_IGNORABLE) {
continue;
}
if (expandflag && count == 0 &&
getColElemIterOffset(coleiter, FALSE) != temp) {
*end = temp;
temp = ucol_getOffset(coleiter);
}
if (count == patterncelength &&
ce != patternce[patterncelength - 1]) {
// accents may have extra starting ces, this occurs when a
// pure accent pattern is matched without rearrangement
int32_t expected = patternce[patterncelength - 1];
UTF_BACK_1(text, 0, *end);
if (getFCD(text, end, textlength) & LAST_BYTE_MASK_) {
ce = getCE(strsrch, ucol_previous(coleiter, status));
while (U_SUCCESS(*status) && ce != expected &&
ce != UCOL_NULLORDER &&
ucol_getOffset(coleiter) <= *start) {
ce = getCE(strsrch, ucol_previous(coleiter, status));
}
}
}
if (U_FAILURE(*status) || ce != patternce[count - 1]) {
(*start) --;
*start = getPreviousBaseOffset(text, *start);
return FALSE;
}
count --;
}
}
return TRUE;
}
/**
* Checks and sets the match information if found.
* Checks
* <ul>
* <li> the potential match does not repeat the previous match
* <li> boundaries are correct
* <li> potential match does not end in the middle of a contraction
* <li> identical matches
* <\ul>
* Otherwise the offset will be shifted to the next character.
* Internal method, status assumed to be success, caller has to check status
* before calling this method.
* @param strsrch string search data
* @param textoffset offset in the collation element text. the returned value
* will be the truncated start offset of the match or the new start
* search offset.
* @param status only error status if any
* @return TRUE if the match is valid, FALSE otherwise
*/
static
inline UBool checkPreviousCanonicalMatch(UStringSearch *strsrch,
int32_t *textoffset,
UErrorCode *status)
{
// to ensure that the start and ends are not composite characters
UCollationElements *coleiter = strsrch->textIter;
// if we have a canonical accent match
if ((strsrch->pattern.hasSuffixAccents &&
strsrch->canonicalSuffixAccents[0]) ||
(strsrch->pattern.hasPrefixAccents &&
strsrch->canonicalPrefixAccents[0])) {
strsrch->search->matchedIndex = *textoffset;
strsrch->search->matchedLength =
getNextUStringSearchBaseOffset(strsrch,
getColElemIterOffset(coleiter, FALSE))
- *textoffset;
return TRUE;
}
int32_t end = ucol_getOffset(coleiter);
if (!checkPreviousCanonicalContractionMatch(strsrch, textoffset, &end,
status) ||
U_FAILURE(*status)) {
return FALSE;
}
end = getNextUStringSearchBaseOffset(strsrch, end);
// this totally matches, however we need to check if it is repeating
if (checkRepeatedMatch(strsrch, *textoffset, end) ||
!isBreakUnit(strsrch, *textoffset, end) ||
!checkIdentical(strsrch, *textoffset, end)) {
(*textoffset) --;
*textoffset = getPreviousBaseOffset(strsrch->search->text,
*textoffset);
return FALSE;
}
strsrch->search->matchedIndex = *textoffset;
strsrch->search->matchedLength = end - *textoffset;
return TRUE;
}
#endif // #if BOYER_MOORE
// constructors and destructor -------------------------------------------
U_CAPI UStringSearch * U_EXPORT2 usearch_open(const UChar *pattern,
int32_t patternlength,
const UChar *text,
int32_t textlength,
const char *locale,
UBreakIterator *breakiter,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return NULL;
}
#if UCONFIG_NO_BREAK_ITERATION
if (breakiter != NULL) {
*status = U_UNSUPPORTED_ERROR;
return NULL;
}
#endif
if (locale) {
// ucol_open internally checks for status
UCollator *collator = ucol_open(locale, status);
// pattern, text checks are done in usearch_openFromCollator
UStringSearch *result = usearch_openFromCollator(pattern,
patternlength, text, textlength,
collator, breakiter, status);
if (result == NULL || U_FAILURE(*status)) {
if (collator) {
ucol_close(collator);
}
return NULL;
}
else {
result->ownCollator = TRUE;
}
return result;
}
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
U_CAPI UStringSearch * U_EXPORT2 usearch_openFromCollator(
const UChar *pattern,
int32_t patternlength,
const UChar *text,
int32_t textlength,
const UCollator *collator,
UBreakIterator *breakiter,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return NULL;
}
#if UCONFIG_NO_BREAK_ITERATION
if (breakiter != NULL) {
*status = U_UNSUPPORTED_ERROR;
return NULL;
}
#endif
if (pattern == NULL || text == NULL || collator == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
// string search does not really work when numeric collation is turned on
if(ucol_getAttribute(collator, UCOL_NUMERIC_COLLATION, status) == UCOL_ON) {
*status = U_UNSUPPORTED_ERROR;
return NULL;
}
if (U_SUCCESS(*status)) {
initializeFCD(status);
if (U_FAILURE(*status)) {
return NULL;
}
UStringSearch *result;
if (textlength == -1) {
textlength = u_strlen(text);
}
if (patternlength == -1) {
patternlength = u_strlen(pattern);
}
if (textlength <= 0 || patternlength <= 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return NULL;
}
result = (UStringSearch *)uprv_malloc(sizeof(UStringSearch));
if (result == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
return NULL;
}
result->collator = collator;
result->strength = ucol_getStrength(collator);
result->ceMask = getMask(result->strength);
result->toShift =
ucol_getAttribute(collator, UCOL_ALTERNATE_HANDLING, status) ==
UCOL_SHIFTED;
result->variableTop = ucol_getVariableTop(collator, status);
result->nfd = Normalizer2Factory::getNFDInstance(*status);
if (U_FAILURE(*status)) {
uprv_free(result);
return NULL;
}
result->search = (USearch *)uprv_malloc(sizeof(USearch));
if (result->search == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
uprv_free(result);
return NULL;
}
result->search->text = text;
result->search->textLength = textlength;
result->pattern.text = pattern;
result->pattern.textLength = patternlength;
result->pattern.CE = NULL;
result->pattern.PCE = NULL;
result->search->breakIter = breakiter;
#if !UCONFIG_NO_BREAK_ITERATION
result->search->internalBreakIter = ubrk_open(UBRK_CHARACTER, ucol_getLocaleByType(result->collator, ULOC_VALID_LOCALE, status), text, textlength, status);
if (breakiter) {
ubrk_setText(breakiter, text, textlength, status);
}
#endif
result->ownCollator = FALSE;
result->search->matchedLength = 0;
result->search->matchedIndex = USEARCH_DONE;
result->utilIter = NULL;
result->textIter = ucol_openElements(collator, text,
textlength, status);
if (U_FAILURE(*status)) {
usearch_close(result);
return NULL;
}
result->search->isOverlap = FALSE;
result->search->isCanonicalMatch = FALSE;
result->search->elementComparisonType = 0;
result->search->isForwardSearching = TRUE;
result->search->reset = TRUE;
initialize(result, status);
if (U_FAILURE(*status)) {
usearch_close(result);
return NULL;
}
return result;
}
return NULL;
}
U_CAPI void U_EXPORT2 usearch_close(UStringSearch *strsrch)
{
if (strsrch) {
if (strsrch->pattern.CE != strsrch->pattern.CEBuffer &&
strsrch->pattern.CE) {
uprv_free(strsrch->pattern.CE);
}
if (strsrch->pattern.PCE != NULL &&
strsrch->pattern.PCE != strsrch->pattern.PCEBuffer) {
uprv_free(strsrch->pattern.PCE);
}
ucol_closeElements(strsrch->textIter);
ucol_closeElements(strsrch->utilIter);
if (strsrch->ownCollator && strsrch->collator) {
ucol_close((UCollator *)strsrch->collator);
}
#if !UCONFIG_NO_BREAK_ITERATION
if (strsrch->search->internalBreakIter) {
ubrk_close(strsrch->search->internalBreakIter);
}
#endif
uprv_free(strsrch->search);
uprv_free(strsrch);
}
}
// set and get methods --------------------------------------------------
U_CAPI void U_EXPORT2 usearch_setOffset(UStringSearch *strsrch,
int32_t position,
UErrorCode *status)
{
if (U_SUCCESS(*status) && strsrch) {
if (isOutOfBounds(strsrch->search->textLength, position)) {
*status = U_INDEX_OUTOFBOUNDS_ERROR;
}
else {
setColEIterOffset(strsrch->textIter, position);
}
strsrch->search->matchedIndex = USEARCH_DONE;
strsrch->search->matchedLength = 0;
strsrch->search->reset = FALSE;
}
}
U_CAPI int32_t U_EXPORT2 usearch_getOffset(const UStringSearch *strsrch)
{
if (strsrch) {
int32_t result = ucol_getOffset(strsrch->textIter);
if (isOutOfBounds(strsrch->search->textLength, result)) {
return USEARCH_DONE;
}
return result;
}
return USEARCH_DONE;
}
U_CAPI void U_EXPORT2 usearch_setAttribute(UStringSearch *strsrch,
USearchAttribute attribute,
USearchAttributeValue value,
UErrorCode *status)
{
if (U_SUCCESS(*status) && strsrch) {
switch (attribute)
{
case USEARCH_OVERLAP :
strsrch->search->isOverlap = (value == USEARCH_ON ? TRUE : FALSE);
break;
case USEARCH_CANONICAL_MATCH :
strsrch->search->isCanonicalMatch = (value == USEARCH_ON ? TRUE :
FALSE);
break;
case USEARCH_ELEMENT_COMPARISON :
if (value == USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD || value == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD) {
strsrch->search->elementComparisonType = (int16_t)value;
} else {
strsrch->search->elementComparisonType = 0;
}
break;
case USEARCH_ATTRIBUTE_COUNT :
default:
*status = U_ILLEGAL_ARGUMENT_ERROR;
}
}
if (value == USEARCH_ATTRIBUTE_VALUE_COUNT) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
}
}
U_CAPI USearchAttributeValue U_EXPORT2 usearch_getAttribute(
const UStringSearch *strsrch,
USearchAttribute attribute)
{
if (strsrch) {
switch (attribute) {
case USEARCH_OVERLAP :
return (strsrch->search->isOverlap == TRUE ? USEARCH_ON :
USEARCH_OFF);
case USEARCH_CANONICAL_MATCH :
return (strsrch->search->isCanonicalMatch == TRUE ? USEARCH_ON :
USEARCH_OFF);
case USEARCH_ELEMENT_COMPARISON :
{
int16_t value = strsrch->search->elementComparisonType;
if (value == USEARCH_PATTERN_BASE_WEIGHT_IS_WILDCARD || value == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD) {
return (USearchAttributeValue)value;
} else {
return USEARCH_STANDARD_ELEMENT_COMPARISON;
}
}
case USEARCH_ATTRIBUTE_COUNT :
return USEARCH_DEFAULT;
}
}
return USEARCH_DEFAULT;
}
U_CAPI int32_t U_EXPORT2 usearch_getMatchedStart(
const UStringSearch *strsrch)
{
if (strsrch == NULL) {
return USEARCH_DONE;
}
return strsrch->search->matchedIndex;
}
U_CAPI int32_t U_EXPORT2 usearch_getMatchedText(const UStringSearch *strsrch,
UChar *result,
int32_t resultCapacity,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
if (strsrch == NULL || resultCapacity < 0 || (resultCapacity > 0 &&
result == NULL)) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return USEARCH_DONE;
}
int32_t copylength = strsrch->search->matchedLength;
int32_t copyindex = strsrch->search->matchedIndex;
if (copyindex == USEARCH_DONE) {
u_terminateUChars(result, resultCapacity, 0, status);
return USEARCH_DONE;
}
if (resultCapacity < copylength) {
copylength = resultCapacity;
}
if (copylength > 0) {
uprv_memcpy(result, strsrch->search->text + copyindex,
copylength * sizeof(UChar));
}
return u_terminateUChars(result, resultCapacity,
strsrch->search->matchedLength, status);
}
U_CAPI int32_t U_EXPORT2 usearch_getMatchedLength(
const UStringSearch *strsrch)
{
if (strsrch) {
return strsrch->search->matchedLength;
}
return USEARCH_DONE;
}
#if !UCONFIG_NO_BREAK_ITERATION
U_CAPI void U_EXPORT2 usearch_setBreakIterator(UStringSearch *strsrch,
UBreakIterator *breakiter,
UErrorCode *status)
{
if (U_SUCCESS(*status) && strsrch) {
strsrch->search->breakIter = breakiter;
if (breakiter) {
ubrk_setText(breakiter, strsrch->search->text,
strsrch->search->textLength, status);
}
}
}
U_CAPI const UBreakIterator* U_EXPORT2
usearch_getBreakIterator(const UStringSearch *strsrch)
{
if (strsrch) {
return strsrch->search->breakIter;
}
return NULL;
}
#endif
U_CAPI void U_EXPORT2 usearch_setText( UStringSearch *strsrch,
const UChar *text,
int32_t textlength,
UErrorCode *status)
{
if (U_SUCCESS(*status)) {
if (strsrch == NULL || text == NULL || textlength < -1 ||
textlength == 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
}
else {
if (textlength == -1) {
textlength = u_strlen(text);
}
strsrch->search->text = text;
strsrch->search->textLength = textlength;
ucol_setText(strsrch->textIter, text, textlength, status);
strsrch->search->matchedIndex = USEARCH_DONE;
strsrch->search->matchedLength = 0;
strsrch->search->reset = TRUE;
#if !UCONFIG_NO_BREAK_ITERATION
if (strsrch->search->breakIter != NULL) {
ubrk_setText(strsrch->search->breakIter, text,
textlength, status);
}
ubrk_setText(strsrch->search->internalBreakIter, text, textlength, status);
#endif
}
}
}
U_CAPI const UChar * U_EXPORT2 usearch_getText(const UStringSearch *strsrch,
int32_t *length)
{
if (strsrch) {
*length = strsrch->search->textLength;
return strsrch->search->text;
}
return NULL;
}
U_CAPI void U_EXPORT2 usearch_setCollator( UStringSearch *strsrch,
const UCollator *collator,
UErrorCode *status)
{
if (U_SUCCESS(*status)) {
if (collator == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
if (strsrch) {
if (strsrch->ownCollator && (strsrch->collator != collator)) {
ucol_close((UCollator *)strsrch->collator);
strsrch->ownCollator = FALSE;
}
strsrch->collator = collator;
strsrch->strength = ucol_getStrength(collator);
strsrch->ceMask = getMask(strsrch->strength);
#if !UCONFIG_NO_BREAK_ITERATION
ubrk_close(strsrch->search->internalBreakIter);
strsrch->search->internalBreakIter = ubrk_open(UBRK_CHARACTER, ucol_getLocaleByType(collator, ULOC_VALID_LOCALE, status),
strsrch->search->text, strsrch->search->textLength, status);
#endif
// if status is a failure, ucol_getAttribute returns UCOL_DEFAULT
strsrch->toShift =
ucol_getAttribute(collator, UCOL_ALTERNATE_HANDLING, status) ==
UCOL_SHIFTED;
// if status is a failure, ucol_getVariableTop returns 0
strsrch->variableTop = ucol_getVariableTop(collator, status);
if (U_SUCCESS(*status)) {
initialize(strsrch, status);
if (U_SUCCESS(*status)) {
/* free offset buffer to avoid memory leak before initializing. */
ucol_freeOffsetBuffer(&(strsrch->textIter->iteratordata_));
uprv_init_collIterate(collator, strsrch->search->text,
strsrch->search->textLength,
&(strsrch->textIter->iteratordata_),
status);
strsrch->utilIter->iteratordata_.coll = collator;
}
}
}
// **** are these calls needed?
// **** we call uprv_init_pce in initializePatternPCETable
// **** and the CEBuffer constructor...
#if 0
uprv_init_pce(strsrch->textIter);
uprv_init_pce(strsrch->utilIter);
#endif
}
}
U_CAPI UCollator * U_EXPORT2 usearch_getCollator(const UStringSearch *strsrch)
{
if (strsrch) {
return (UCollator *)strsrch->collator;
}
return NULL;
}
U_CAPI void U_EXPORT2 usearch_setPattern( UStringSearch *strsrch,
const UChar *pattern,
int32_t patternlength,
UErrorCode *status)
{
if (U_SUCCESS(*status)) {
if (strsrch == NULL || pattern == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
}
else {
if (patternlength == -1) {
patternlength = u_strlen(pattern);
}
if (patternlength == 0) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
strsrch->pattern.text = pattern;
strsrch->pattern.textLength = patternlength;
initialize(strsrch, status);
}
}
}
U_CAPI const UChar* U_EXPORT2
usearch_getPattern(const UStringSearch *strsrch,
int32_t *length)
{
if (strsrch) {
*length = strsrch->pattern.textLength;
return strsrch->pattern.text;
}
return NULL;
}
// miscellanous methods --------------------------------------------------
U_CAPI int32_t U_EXPORT2 usearch_first(UStringSearch *strsrch,
UErrorCode *status)
{
if (strsrch && U_SUCCESS(*status)) {
strsrch->search->isForwardSearching = TRUE;
usearch_setOffset(strsrch, 0, status);
if (U_SUCCESS(*status)) {
return usearch_next(strsrch, status);
}
}
return USEARCH_DONE;
}
U_CAPI int32_t U_EXPORT2 usearch_following(UStringSearch *strsrch,
int32_t position,
UErrorCode *status)
{
if (strsrch && U_SUCCESS(*status)) {
strsrch->search->isForwardSearching = TRUE;
// position checked in usearch_setOffset
usearch_setOffset(strsrch, position, status);
if (U_SUCCESS(*status)) {
return usearch_next(strsrch, status);
}
}
return USEARCH_DONE;
}
U_CAPI int32_t U_EXPORT2 usearch_last(UStringSearch *strsrch,
UErrorCode *status)
{
if (strsrch && U_SUCCESS(*status)) {
strsrch->search->isForwardSearching = FALSE;
usearch_setOffset(strsrch, strsrch->search->textLength, status);
if (U_SUCCESS(*status)) {
return usearch_previous(strsrch, status);
}
}
return USEARCH_DONE;
}
U_CAPI int32_t U_EXPORT2 usearch_preceding(UStringSearch *strsrch,
int32_t position,
UErrorCode *status)
{
if (strsrch && U_SUCCESS(*status)) {
strsrch->search->isForwardSearching = FALSE;
// position checked in usearch_setOffset
usearch_setOffset(strsrch, position, status);
if (U_SUCCESS(*status)) {
return usearch_previous(strsrch, status);
}
}
return USEARCH_DONE;
}
/**
* If a direction switch is required, we'll count the number of ces till the
* beginning of the collation element iterator and iterate forwards that
* number of times. This is so that we get to the correct point within the
* string to continue the search in. Imagine when we are in the middle of the
* normalization buffer when the change in direction is request. arrrgghh....
* After searching the offset within the collation element iterator will be
* shifted to the start of the match. If a match is not found, the offset would
* have been set to the end of the text string in the collation element
* iterator.
* Okay, here's my take on normalization buffer. The only time when there can
* be 2 matches within the same normalization is when the pattern is consists
* of all accents. But since the offset returned is from the text string, we
* should not confuse the caller by returning the second match within the
* same normalization buffer. If we do, the 2 results will have the same match
* offsets, and that'll be confusing. I'll return the next match that doesn't
* fall within the same normalization buffer. Note this does not affect the
* results of matches spanning the text and the normalization buffer.
* The position to start searching is taken from the collation element
* iterator. Callers of this API would have to set the offset in the collation
* element iterator before using this method.
*/
U_CAPI int32_t U_EXPORT2 usearch_next(UStringSearch *strsrch,
UErrorCode *status)
{
if (U_SUCCESS(*status) && strsrch) {
// note offset is either equivalent to the start of the previous match
// or is set by the user
int32_t offset = usearch_getOffset(strsrch);
USearch *search = strsrch->search;
search->reset = FALSE;
int32_t textlength = search->textLength;
if (search->isForwardSearching) {
#if BOYER_MOORE
if (offset == textlength
|| (!search->isOverlap &&
(offset + strsrch->pattern.defaultShiftSize > textlength ||
(search->matchedIndex != USEARCH_DONE &&
offset + search->matchedLength >= textlength)))) {
// not enough characters to match
setMatchNotFound(strsrch);
return USEARCH_DONE;
}
#else
if (offset == textlength ||
(! search->isOverlap &&
(search->matchedIndex != USEARCH_DONE &&
offset + search->matchedLength > textlength))) {
// not enough characters to match
setMatchNotFound(strsrch);
return USEARCH_DONE;
}
#endif
}
else {
// switching direction.
// if matchedIndex == USEARCH_DONE, it means that either a
// setOffset has been called or that previous ran off the text
// string. the iterator would have been set to offset 0 if a
// match is not found.
search->isForwardSearching = TRUE;
if (search->matchedIndex != USEARCH_DONE) {
// there's no need to set the collation element iterator
// the next call to next will set the offset.
return search->matchedIndex;
}
}
if (U_SUCCESS(*status)) {
if (strsrch->pattern.CELength == 0) {
if (search->matchedIndex == USEARCH_DONE) {
search->matchedIndex = offset;
}
else { // moves by codepoints
UTF_FWD_1(search->text, search->matchedIndex, textlength);
}
search->matchedLength = 0;
setColEIterOffset(strsrch->textIter, search->matchedIndex);
// status checked below
if (search->matchedIndex == textlength) {
search->matchedIndex = USEARCH_DONE;
}
}
else {
if (search->matchedLength > 0) {
// if matchlength is 0 we are at the start of the iteration
if (search->isOverlap) {
ucol_setOffset(strsrch->textIter, offset + 1, status);
}
else {
ucol_setOffset(strsrch->textIter,
offset + search->matchedLength, status);
}
}
else {
// for boundary check purposes. this will ensure that the
// next match will not preceed the current offset
// note search->matchedIndex will always be set to something
// in the code
search->matchedIndex = offset - 1;
}
if (search->isCanonicalMatch) {
// can't use exact here since extra accents are allowed.
usearch_handleNextCanonical(strsrch, status);
}
else {
usearch_handleNextExact(strsrch, status);
}
}
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
#if !BOYER_MOORE
if (search->matchedIndex == USEARCH_DONE) {
ucol_setOffset(strsrch->textIter, search->textLength, status);
} else {
ucol_setOffset(strsrch->textIter, search->matchedIndex, status);
}
#endif
return search->matchedIndex;
}
}
return USEARCH_DONE;
}
U_CAPI int32_t U_EXPORT2 usearch_previous(UStringSearch *strsrch,
UErrorCode *status)
{
if (U_SUCCESS(*status) && strsrch) {
int32_t offset;
USearch *search = strsrch->search;
if (search->reset) {
offset = search->textLength;
search->isForwardSearching = FALSE;
search->reset = FALSE;
setColEIterOffset(strsrch->textIter, offset);
}
else {
offset = usearch_getOffset(strsrch);
}
int32_t matchedindex = search->matchedIndex;
if (search->isForwardSearching == TRUE) {
// switching direction.
// if matchedIndex == USEARCH_DONE, it means that either a
// setOffset has been called or that next ran off the text
// string. the iterator would have been set to offset textLength if
// a match is not found.
search->isForwardSearching = FALSE;
if (matchedindex != USEARCH_DONE) {
return matchedindex;
}
}
else {
#if BOYER_MOORE
if (offset == 0 || matchedindex == 0 ||
(!search->isOverlap &&
(offset < strsrch->pattern.defaultShiftSize ||
(matchedindex != USEARCH_DONE &&
matchedindex < strsrch->pattern.defaultShiftSize)))) {
// not enough characters to match
setMatchNotFound(strsrch);
return USEARCH_DONE;
}
#else
// Could check pattern length, but the
// linear search will do the right thing
if (offset == 0 || matchedindex == 0) {
setMatchNotFound(strsrch);
return USEARCH_DONE;
}
#endif
}
if (U_SUCCESS(*status)) {
if (strsrch->pattern.CELength == 0) {
search->matchedIndex =
(matchedindex == USEARCH_DONE ? offset : matchedindex);
if (search->matchedIndex == 0) {
setMatchNotFound(strsrch);
// status checked below
}
else { // move by codepoints
UTF_BACK_1(search->text, 0, search->matchedIndex);
setColEIterOffset(strsrch->textIter, search->matchedIndex);
// status checked below
search->matchedLength = 0;
}
}
else {
if (strsrch->search->isCanonicalMatch) {
// can't use exact here since extra accents are allowed.
usearch_handlePreviousCanonical(strsrch, status);
// status checked below
}
else {
usearch_handlePreviousExact(strsrch, status);
// status checked below
}
}
if (U_FAILURE(*status)) {
return USEARCH_DONE;
}
return search->matchedIndex;
}
}
return USEARCH_DONE;
}
U_CAPI void U_EXPORT2 usearch_reset(UStringSearch *strsrch)
{
/*
reset is setting the attributes that are already in
string search, hence all attributes in the collator should
be retrieved without any problems
*/
if (strsrch) {
UErrorCode status = U_ZERO_ERROR;
UBool sameCollAttribute = TRUE;
uint32_t ceMask;
UBool shift;
uint32_t varTop;
// **** hack to deal w/ how processed CEs encode quaternary ****
UCollationStrength newStrength = ucol_getStrength(strsrch->collator);
if ((strsrch->strength < UCOL_QUATERNARY && newStrength >= UCOL_QUATERNARY) ||
(strsrch->strength >= UCOL_QUATERNARY && newStrength < UCOL_QUATERNARY)) {
sameCollAttribute = FALSE;
}
strsrch->strength = ucol_getStrength(strsrch->collator);
ceMask = getMask(strsrch->strength);
if (strsrch->ceMask != ceMask) {
strsrch->ceMask = ceMask;
sameCollAttribute = FALSE;
}
// if status is a failure, ucol_getAttribute returns UCOL_DEFAULT
shift = ucol_getAttribute(strsrch->collator, UCOL_ALTERNATE_HANDLING,
&status) == UCOL_SHIFTED;
if (strsrch->toShift != shift) {
strsrch->toShift = shift;
sameCollAttribute = FALSE;
}
// if status is a failure, ucol_getVariableTop returns 0
varTop = ucol_getVariableTop(strsrch->collator, &status);
if (strsrch->variableTop != varTop) {
strsrch->variableTop = varTop;
sameCollAttribute = FALSE;
}
if (!sameCollAttribute) {
initialize(strsrch, &status);
}
/* free offset buffer to avoid memory leak before initializing. */
ucol_freeOffsetBuffer(&(strsrch->textIter->iteratordata_));
uprv_init_collIterate(strsrch->collator, strsrch->search->text,
strsrch->search->textLength,
&(strsrch->textIter->iteratordata_),
&status);
strsrch->search->matchedLength = 0;
strsrch->search->matchedIndex = USEARCH_DONE;
strsrch->search->isOverlap = FALSE;
strsrch->search->isCanonicalMatch = FALSE;
strsrch->search->elementComparisonType = 0;
strsrch->search->isForwardSearching = TRUE;
strsrch->search->reset = TRUE;
}
}
//
// CEI Collation Element + source text index.
// These structs are kept in the circular buffer.
//
struct CEI {
int64_t ce;
int32_t lowIndex;
int32_t highIndex;
};
U_NAMESPACE_BEGIN
//
// CEBuffer A circular buffer of CEs from the text being searched.
//
#define DEFAULT_CEBUFFER_SIZE 96
#define CEBUFFER_EXTRA 32
// Some typical max values to make buffer size more reasonable for asymmetric search.
// #8694 is for a better long-term solution to allocation of this buffer.
#define MAX_TARGET_IGNORABLES_PER_PAT_JAMO_L 8
#define MAX_TARGET_IGNORABLES_PER_PAT_OTHER 3
#define MIGHT_BE_JAMO_L(c) ((c >= 0x1100 && c <= 0x115E) || (c >= 0x3131 && c <= 0x314E) || (c >= 0x3165 && c <= 0x3186))
struct CEBuffer {
CEI defBuf[DEFAULT_CEBUFFER_SIZE];
CEI *buf;
int32_t bufSize;
int32_t firstIx;
int32_t limitIx;
UCollationElements *ceIter;
UStringSearch *strSearch;
CEBuffer(UStringSearch *ss, UErrorCode *status);
~CEBuffer();
const CEI *get(int32_t index);
const CEI *getPrevious(int32_t index);
};
CEBuffer::CEBuffer(UStringSearch *ss, UErrorCode *status) {
buf = defBuf;
strSearch = ss;
bufSize = ss->pattern.PCELength + CEBUFFER_EXTRA;
if (ss->search->elementComparisonType != 0) {
const UChar * patText = ss->pattern.text;
if (patText) {
const UChar * patTextLimit = patText + ss->pattern.textLength;
while ( patText < patTextLimit ) {
UChar c = *patText++;
if (MIGHT_BE_JAMO_L(c)) {
bufSize += MAX_TARGET_IGNORABLES_PER_PAT_JAMO_L;
} else {
// No check for surrogates, we might allocate slightly more buffer than necessary.
bufSize += MAX_TARGET_IGNORABLES_PER_PAT_OTHER;
}
}
}
}
ceIter = ss->textIter;
firstIx = 0;
limitIx = 0;
uprv_init_pce(ceIter);
if (bufSize>DEFAULT_CEBUFFER_SIZE) {
buf = (CEI *)uprv_malloc(bufSize * sizeof(CEI));
if (buf == NULL) {
*status = U_MEMORY_ALLOCATION_ERROR;
}
}
}
// TODO: add a reset or init function so that allocated
// buffers can be retained & reused.
CEBuffer::~CEBuffer() {
if (buf != defBuf) {
uprv_free(buf);
}
}
// Get the CE with the specified index.
// Index must be in the range
// n-history_size < index < n+1
// where n is the largest index to have been fetched by some previous call to this function.
// The CE value will be UCOL__PROCESSED_NULLORDER at end of input.
//
const CEI *CEBuffer::get(int32_t index) {
int i = index % bufSize;
if (index>=firstIx && index<limitIx) {
// The request was for an entry already in our buffer.
// Just return it.
return &buf[i];
}
// Caller is requesting a new, never accessed before, CE.
// Verify that it is the next one in sequence, which is all
// that is allowed.
if (index != limitIx) {
U_ASSERT(FALSE);
return NULL;
}
// Manage the circular CE buffer indexing
limitIx++;
if (limitIx - firstIx >= bufSize) {
// The buffer is full, knock out the lowest-indexed entry.
firstIx++;
}
UErrorCode status = U_ZERO_ERROR;
buf[i].ce = ucol_nextProcessed(ceIter, &buf[i].lowIndex, &buf[i].highIndex, &status);
return &buf[i];
}
// Get the CE with the specified index.
// Index must be in the range
// n-history_size < index < n+1
// where n is the largest index to have been fetched by some previous call to this function.
// The CE value will be UCOL__PROCESSED_NULLORDER at end of input.
//
const CEI *CEBuffer::getPrevious(int32_t index) {
int i = index % bufSize;
if (index>=firstIx && index<limitIx) {
// The request was for an entry already in our buffer.
// Just return it.
return &buf[i];
}
// Caller is requesting a new, never accessed before, CE.
// Verify that it is the next one in sequence, which is all
// that is allowed.
if (index != limitIx) {
U_ASSERT(FALSE);
return NULL;
}
// Manage the circular CE buffer indexing
limitIx++;
if (limitIx - firstIx >= bufSize) {
// The buffer is full, knock out the lowest-indexed entry.
firstIx++;
}
UErrorCode status = U_ZERO_ERROR;
buf[i].ce = ucol_previousProcessed(ceIter, &buf[i].lowIndex, &buf[i].highIndex, &status);
return &buf[i];
}
U_NAMESPACE_END
// #define USEARCH_DEBUG
#ifdef USEARCH_DEBUG
#include <stdio.h>
#include <stdlib.h>
#endif
/*
* Find the next break boundary after startIndex. If the UStringSearch object
* has an external break iterator, use that. Otherwise use the internal character
* break iterator.
*/
static int32_t nextBoundaryAfter(UStringSearch *strsrch, int32_t startIndex) {
#if 0
const UChar *text = strsrch->search->text;
int32_t textLen = strsrch->search->textLength;
U_ASSERT(startIndex>=0);
U_ASSERT(startIndex<=textLen);
if (startIndex >= textLen) {
return startIndex;
}
UChar32 c;
int32_t i = startIndex;
U16_NEXT(text, i, textLen, c);
// If we are on a control character, stop without looking for combining marks.
// Control characters do not combine.
int32_t gcProperty = u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);
if (gcProperty==U_GCB_CONTROL || gcProperty==U_GCB_LF || gcProperty==U_GCB_CR) {
return i;
}
// The initial character was not a control, and can thus accept trailing
// combining characters. Advance over however many of them there are.
int32_t indexOfLastCharChecked;
for (;;) {
indexOfLastCharChecked = i;
if (i>=textLen) {
break;
}
U16_NEXT(text, i, textLen, c);
gcProperty = u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);
if (gcProperty != U_GCB_EXTEND && gcProperty != U_GCB_SPACING_MARK) {
break;
}
}
return indexOfLastCharChecked;
#elif !UCONFIG_NO_BREAK_ITERATION
UBreakIterator *breakiterator = strsrch->search->breakIter;
if (breakiterator == NULL) {
breakiterator = strsrch->search->internalBreakIter;
}
if (breakiterator != NULL) {
return ubrk_following(breakiterator, startIndex);
}
return startIndex;
#else
// **** or should we use the original code? ****
return startIndex;
#endif
}
/*
* Returns TRUE if index is on a break boundary. If the UStringSearch
* has an external break iterator, test using that, otherwise test
* using the internal character break iterator.
*/
static UBool isBreakBoundary(UStringSearch *strsrch, int32_t index) {
#if 0
const UChar *text = strsrch->search->text;
int32_t textLen = strsrch->search->textLength;
U_ASSERT(index>=0);
U_ASSERT(index<=textLen);
if (index>=textLen || index<=0) {
return TRUE;
}
// If the character at the current index is not a GRAPHEME_EXTEND
// then we can not be within a combining sequence.
UChar32 c;
U16_GET(text, 0, index, textLen, c);
int32_t gcProperty = u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);
if (gcProperty != U_GCB_EXTEND && gcProperty != U_GCB_SPACING_MARK) {
return TRUE;
}
// We are at a combining mark. If the preceding character is anything
// except a CONTROL, CR or LF, we are in a combining sequence.
U16_PREV(text, 0, index, c);
gcProperty = u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);
UBool combining = !(gcProperty==U_GCB_CONTROL || gcProperty==U_GCB_LF || gcProperty==U_GCB_CR);
return !combining;
#elif !UCONFIG_NO_BREAK_ITERATION
UBreakIterator *breakiterator = strsrch->search->breakIter;
if (breakiterator == NULL) {
breakiterator = strsrch->search->internalBreakIter;
}
return (breakiterator != NULL && ubrk_isBoundary(breakiterator, index));
#else
// **** or use the original code? ****
return TRUE;
#endif
}
#if 0
static UBool onBreakBoundaries(const UStringSearch *strsrch, int32_t start, int32_t end)
{
#if !UCONFIG_NO_BREAK_ITERATION
UBreakIterator *breakiterator = strsrch->search->breakIter;
if (breakiterator != NULL) {
int32_t startindex = ubrk_first(breakiterator);
int32_t endindex = ubrk_last(breakiterator);
// out-of-range indexes are never boundary positions
if (start < startindex || start > endindex ||
end < startindex || end > endindex) {
return FALSE;
}
return ubrk_isBoundary(breakiterator, start) &&
ubrk_isBoundary(breakiterator, end);
}
#endif
return TRUE;
}
#endif
typedef enum {
U_CE_MATCH = -1,
U_CE_NO_MATCH = 0,
U_CE_SKIP_TARG,
U_CE_SKIP_PATN
} UCompareCEsResult;
#define U_CE_LEVEL2_BASE 0x00000005
#define U_CE_LEVEL3_BASE 0x00050000
static UCompareCEsResult compareCE64s(int64_t targCE, int64_t patCE, int16_t compareType) {
if (targCE == patCE) {
return U_CE_MATCH;
}
if (compareType == 0) {
return U_CE_NO_MATCH;
}
int64_t targCEshifted = targCE >> 32;
int64_t patCEshifted = patCE >> 32;
int64_t mask;
mask = 0xFFFF0000;
int32_t targLev1 = (int32_t)(targCEshifted & mask);
int32_t patLev1 = (int32_t)(patCEshifted & mask);
if ( targLev1 != patLev1 ) {
if ( targLev1 == 0 ) {
return U_CE_SKIP_TARG;
}
if ( patLev1 == 0 && compareType == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD ) {
return U_CE_SKIP_PATN;
}
return U_CE_NO_MATCH;
}
mask = 0x0000FFFF;
int32_t targLev2 = (int32_t)(targCEshifted & mask);
int32_t patLev2 = (int32_t)(patCEshifted & mask);
if ( targLev2 != patLev2 ) {
if ( targLev2 == 0 ) {
return U_CE_SKIP_TARG;
}
if ( patLev2 == 0 && compareType == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD ) {
return U_CE_SKIP_PATN;
}
return (patLev2 == U_CE_LEVEL2_BASE || (compareType == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD && targLev2 == U_CE_LEVEL2_BASE) )?
U_CE_MATCH: U_CE_NO_MATCH;
}
mask = 0xFFFF0000;
int32_t targLev3 = (int32_t)(targCE & mask);
int32_t patLev3 = (int32_t)(patCE & mask);
if ( targLev3 != patLev3 ) {
return (patLev3 == U_CE_LEVEL3_BASE || (compareType == USEARCH_ANY_BASE_WEIGHT_IS_WILDCARD && targLev3 == U_CE_LEVEL3_BASE) )?
U_CE_MATCH: U_CE_NO_MATCH;
}
return U_CE_MATCH;
}
#if BOYER_MOORE
// TODO: #if BOYER_MOORE, need 32-bit version of compareCE64s
#endif
U_CAPI UBool U_EXPORT2 usearch_search(UStringSearch *strsrch,
int32_t startIdx,
int32_t *matchStart,
int32_t *matchLimit,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return FALSE;
}
// TODO: reject search patterns beginning with a combining char.
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("Pattern CEs\n");
for (int ii=0; ii<strsrch->pattern.CELength; ii++) {
printf(" %8x", strsrch->pattern.CE[ii]);
}
printf("\n");
}
#endif
// Input parameter sanity check.
// TODO: should input indicies clip to the text length
// in the same way that UText does.
if(strsrch->pattern.CELength == 0 ||
startIdx < 0 ||
startIdx > strsrch->search->textLength ||
strsrch->pattern.CE == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
if (strsrch->pattern.PCE == NULL) {
initializePatternPCETable(strsrch, status);
}
ucol_setOffset(strsrch->textIter, startIdx, status);
CEBuffer ceb(strsrch, status);
int32_t targetIx = 0;
const CEI *targetCEI = NULL;
int32_t patIx;
UBool found;
int32_t mStart = -1;
int32_t mLimit = -1;
int32_t minLimit;
int32_t maxLimit;
// Outer loop moves over match starting positions in the
// target CE space.
// Here we see the target as a sequence of collation elements, resulting from the following:
// 1. Target characters were decomposed, and (if appropriate) other compressions and expansions are applied
// (for example, digraphs such as IJ may be broken into two characters).
// 2. An int64_t CE weight is determined for each resulting unit (high 16 bits are primary strength, next
// 16 bits are secondary, next 16 (the high 16 bits of the low 32-bit half) are tertiary. Any of these
// fields that are for strengths below that of the collator are set to 0. If this makes the int64_t
// CE weight 0 (as for a combining diacritic with secondary weight when the collator strentgh is primary),
// then the CE is deleted, so the following code sees only CEs that are relevant.
// For each CE, the lowIndex and highIndex correspond to where this CE begins and ends in the original text.
// If lowIndex==highIndex, either the CE resulted from an expansion/decomposition of one of the original text
// characters, or the CE marks the limit of the target text (in which case the CE weight is UCOL_PROCESSED_NULLORDER).
//
for(targetIx=0; ; targetIx++)
{
found = TRUE;
// Inner loop checks for a match beginning at each
// position from the outer loop.
int32_t targetIxOffset = 0;
int64_t patCE = 0;
// For targetIx > 0, this ceb.get gets a CE that is as far back in the ring buffer
// (compared to the last CE fetched for the previous targetIx value) as we need to go
// for this targetIx value, so if it is non-NULL then other ceb.get calls should be OK.
const CEI *firstCEI = ceb.get(targetIx);
if (firstCEI == NULL) {
*status = U_INTERNAL_PROGRAM_ERROR;
found = FALSE;
break;
}
for (patIx=0; patIx<strsrch->pattern.PCELength; patIx++) {
patCE = strsrch->pattern.PCE[patIx];
targetCEI = ceb.get(targetIx+patIx+targetIxOffset);
// Compare CE from target string with CE from the pattern.
// Note that the target CE will be UCOL_PROCESSED_NULLORDER if we reach the end of input,
// which will fail the compare, below.
UCompareCEsResult ceMatch = compareCE64s(targetCEI->ce, patCE, strsrch->search->elementComparisonType);
if ( ceMatch == U_CE_NO_MATCH ) {
found = FALSE;
break;
} else if ( ceMatch > U_CE_NO_MATCH ) {
if ( ceMatch == U_CE_SKIP_TARG ) {
// redo with same patCE, next targCE
patIx--;
targetIxOffset++;
} else { // ceMatch == U_CE_SKIP_PATN
// redo with same targCE, next patCE
targetIxOffset--;
}
}
}
targetIxOffset += strsrch->pattern.PCELength; // this is now the offset in target CE space to end of the match so far
if (!found && ((targetCEI == NULL) || (targetCEI->ce != UCOL_PROCESSED_NULLORDER))) {
// No match at this targetIx. Try again at the next.
continue;
}
if (!found) {
// No match at all, we have run off the end of the target text.
break;
}
// We have found a match in CE space.
// Now determine the bounds in string index space.
// There still is a chance of match failure if the CE range not correspond to
// an acceptable character range.
//
const CEI *lastCEI = ceb.get(targetIx + targetIxOffset - 1);
mStart = firstCEI->lowIndex;
minLimit = lastCEI->lowIndex;
// Look at the CE following the match. If it is UCOL_NULLORDER the match
// extended to the end of input, and the match is good.
// Look at the high and low indices of the CE following the match. If
// they are the same it means one of two things:
// 1. The match extended to the last CE from the target text, which is OK, or
// 2. The last CE that was part of the match is in an expansion that extends
// to the first CE after the match. In this case, we reject the match.
const CEI *nextCEI = 0;
if (strsrch->search->elementComparisonType == 0) {
nextCEI = ceb.get(targetIx + targetIxOffset);
maxLimit = nextCEI->lowIndex;
if (nextCEI->lowIndex == nextCEI->highIndex && nextCEI->ce != UCOL_PROCESSED_NULLORDER) {
found = FALSE;
}
} else {
for ( ; ; ++targetIxOffset ) {
nextCEI = ceb.get(targetIx + targetIxOffset);
maxLimit = nextCEI->lowIndex;
// If we are at the end of the target too, match succeeds
if ( nextCEI->ce == UCOL_PROCESSED_NULLORDER ) {
break;
}
// As long as the next CE has primary weight of 0,
// it is part of the last target element matched by the pattern;
// make sure it can be part of a match with the last patCE
if ( (((nextCEI->ce) >> 32) & 0xFFFF0000UL) == 0 ) {
UCompareCEsResult ceMatch = compareCE64s(nextCEI->ce, patCE, strsrch->search->elementComparisonType);
if ( ceMatch == U_CE_NO_MATCH || ceMatch == U_CE_SKIP_PATN ) {
found = FALSE;
break;
}
// If lowIndex == highIndex, this target CE is part of an expansion of the last matched
// target element, but it has non-zero primary weight => match fails
} else if ( nextCEI->lowIndex == nextCEI->highIndex ) {
found = false;
break;
// Else the target CE is not part of an expansion of the last matched element, match succeeds
} else {
break;
}
}
}
// Check for the start of the match being within a combining sequence.
// This can happen if the pattern itself begins with a combining char, and
// the match found combining marks in the target text that were attached
// to something else.
// This type of match should be rejected for not completely consuming a
// combining sequence.
if (!isBreakBoundary(strsrch, mStart)) {
found = FALSE;
}
// Check for the start of the match being within an Collation Element Expansion,
// meaning that the first char of the match is only partially matched.
// With exapnsions, the first CE will report the index of the source
// character, and all subsequent (expansions) CEs will report the source index of the
// _following_ character.
int32_t secondIx = firstCEI->highIndex;
if (mStart == secondIx) {
found = FALSE;
}
// Advance the match end position to the first acceptable match boundary.
// This advances the index over any combining charcters.
mLimit = maxLimit;
if (minLimit < maxLimit) {
// When the last CE's low index is same with its high index, the CE is likely
// a part of expansion. In this case, the index is located just after the
// character corresponding to the CEs compared above. If the index is right
// at the break boundary, move the position to the next boundary will result
// incorrect match length when there are ignorable characters exist between
// the position and the next character produces CE(s). See ticket#8482.
if (minLimit == lastCEI->highIndex && isBreakBoundary(strsrch, minLimit)) {
mLimit = minLimit;
} else {
int32_t nba = nextBoundaryAfter(strsrch, minLimit);
if (nba >= lastCEI->highIndex) {
mLimit = nba;
}
}
}
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("minLimit, maxLimit, mLimit = %d, %d, %d\n", minLimit, maxLimit, mLimit);
}
#endif
// If advancing to the end of a combining sequence in character indexing space
// advanced us beyond the end of the match in CE space, reject this match.
if (mLimit > maxLimit) {
found = FALSE;
}
if (!isBreakBoundary(strsrch, mLimit)) {
found = FALSE;
}
if (! checkIdentical(strsrch, mStart, mLimit)) {
found = FALSE;
}
if (found) {
break;
}
}
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("Target CEs [%d .. %d]\n", ceb.firstIx, ceb.limitIx);
int32_t lastToPrint = ceb.limitIx+2;
for (int ii=ceb.firstIx; ii<lastToPrint; ii++) {
printf("%8x@%d ", ceb.get(ii)->ce, ceb.get(ii)->srcIndex);
}
printf("\n%s\n", found? "match found" : "no match");
}
#endif
// All Done. Store back the match bounds to the caller.
//
if (found==FALSE) {
mLimit = -1;
mStart = -1;
}
if (matchStart != NULL) {
*matchStart= mStart;
}
if (matchLimit != NULL) {
*matchLimit = mLimit;
}
return found;
}
U_CAPI UBool U_EXPORT2 usearch_searchBackwards(UStringSearch *strsrch,
int32_t startIdx,
int32_t *matchStart,
int32_t *matchLimit,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
return FALSE;
}
// TODO: reject search patterns beginning with a combining char.
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("Pattern CEs\n");
for (int ii=0; ii<strsrch->pattern.CELength; ii++) {
printf(" %8x", strsrch->pattern.CE[ii]);
}
printf("\n");
}
#endif
// Input parameter sanity check.
// TODO: should input indicies clip to the text length
// in the same way that UText does.
if(strsrch->pattern.CELength == 0 ||
startIdx < 0 ||
startIdx > strsrch->search->textLength ||
strsrch->pattern.CE == NULL) {
*status = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
if (strsrch->pattern.PCE == NULL) {
initializePatternPCETable(strsrch, status);
}
CEBuffer ceb(strsrch, status);
int32_t targetIx = 0;
/*
* Pre-load the buffer with the CE's for the grapheme
* after our starting position so that we're sure that
* we can look at the CE following the match when we
* check the match boundaries.
*
* This will also pre-fetch the first CE that we'll
* consider for the match.
*/
if (startIdx < strsrch->search->textLength) {
UBreakIterator *bi = strsrch->search->internalBreakIter;
int32_t next = ubrk_following(bi, startIdx);
ucol_setOffset(strsrch->textIter, next, status);
for (targetIx = 0; ; targetIx += 1) {
if (ceb.getPrevious(targetIx)->lowIndex < startIdx) {
break;
}
}
} else {
ucol_setOffset(strsrch->textIter, startIdx, status);
}
const CEI *targetCEI = NULL;
int32_t patIx;
UBool found;
int32_t limitIx = targetIx;
int32_t mStart = -1;
int32_t mLimit = -1;
int32_t minLimit;
int32_t maxLimit;
// Outer loop moves over match starting positions in the
// target CE space.
// Here, targetIx values increase toward the beginning of the base text (i.e. we get the text CEs in reverse order).
// But patIx is 0 at the beginning of the pattern and increases toward the end.
// So this loop performs a comparison starting with the end of pattern, and prcessd toward the beginning of the pattern
// and the beginning of the base text.
for(targetIx = limitIx; ; targetIx += 1)
{
found = TRUE;
// For targetIx > limitIx, this ceb.getPrevious gets a CE that is as far back in the ring buffer
// (compared to the last CE fetched for the previous targetIx value) as we need to go
// for this targetIx value, so if it is non-NULL then other ceb.getPrevious calls should be OK.
const CEI *lastCEI = ceb.getPrevious(targetIx);
if (lastCEI == NULL) {
*status = U_INTERNAL_PROGRAM_ERROR;
found = FALSE;
break;
}
// Inner loop checks for a match beginning at each
// position from the outer loop.
int32_t targetIxOffset = 0;
for (patIx = strsrch->pattern.PCELength - 1; patIx >= 0; patIx -= 1) {
int64_t patCE = strsrch->pattern.PCE[patIx];
targetCEI = ceb.getPrevious(targetIx + strsrch->pattern.PCELength - 1 - patIx + targetIxOffset);
// Compare CE from target string with CE from the pattern.
// Note that the target CE will be UCOL_NULLORDER if we reach the end of input,
// which will fail the compare, below.
UCompareCEsResult ceMatch = compareCE64s(targetCEI->ce, patCE, strsrch->search->elementComparisonType);
if ( ceMatch == U_CE_NO_MATCH ) {
found = FALSE;
break;
} else if ( ceMatch > U_CE_NO_MATCH ) {
if ( ceMatch == U_CE_SKIP_TARG ) {
// redo with same patCE, next targCE
patIx++;
targetIxOffset++;
} else { // ceMatch == U_CE_SKIP_PATN
// redo with same targCE, next patCE
targetIxOffset--;
}
}
}
if (!found && ((targetCEI == NULL) || (targetCEI->ce != UCOL_PROCESSED_NULLORDER))) {
// No match at this targetIx. Try again at the next.
continue;
}
if (!found) {
// No match at all, we have run off the end of the target text.
break;
}
// We have found a match in CE space.
// Now determine the bounds in string index space.
// There still is a chance of match failure if the CE range not correspond to
// an acceptable character range.
//
const CEI *firstCEI = ceb.getPrevious(targetIx + strsrch->pattern.PCELength - 1 + targetIxOffset);
mStart = firstCEI->lowIndex;
// Check for the start of the match being within a combining sequence.
// This can happen if the pattern itself begins with a combining char, and
// the match found combining marks in the target text that were attached
// to something else.
// This type of match should be rejected for not completely consuming a
// combining sequence.
if (!isBreakBoundary(strsrch, mStart)) {
found = FALSE;
}
// Look at the high index of the first CE in the match. If it's the same as the
// low index, the first CE in the match is in the middle of an expansion.
if (mStart == firstCEI->highIndex) {
found = FALSE;
}
minLimit = lastCEI->lowIndex;
if (targetIx > 0) {
// Look at the CE following the match. If it is UCOL_NULLORDER the match
// extended to the end of input, and the match is good.
// Look at the high and low indices of the CE following the match. If
// they are the same it means one of two things:
// 1. The match extended to the last CE from the target text, which is OK, or
// 2. The last CE that was part of the match is in an expansion that extends
// to the first CE after the match. In this case, we reject the match.
const CEI *nextCEI = ceb.getPrevious(targetIx - 1);
if (nextCEI->lowIndex == nextCEI->highIndex && nextCEI->ce != UCOL_PROCESSED_NULLORDER) {
found = FALSE;
}
mLimit = maxLimit = nextCEI->lowIndex;
// Advance the match end position to the first acceptable match boundary.
// This advances the index over any combining charcters.
if (minLimit < maxLimit) {
int32_t nba = nextBoundaryAfter(strsrch, minLimit);
if (nba >= lastCEI->highIndex) {
mLimit = nba;
}
}
// If advancing to the end of a combining sequence in character indexing space
// advanced us beyond the end of the match in CE space, reject this match.
if (mLimit > maxLimit) {
found = FALSE;
}
// Make sure the end of the match is on a break boundary
if (!isBreakBoundary(strsrch, mLimit)) {
found = FALSE;
}
} else {
// No non-ignorable CEs after this point.
// The maximum position is detected by boundary after
// the last non-ignorable CE. Combining sequence
// across the start index will be truncated.
int32_t nba = nextBoundaryAfter(strsrch, minLimit);
mLimit = maxLimit = (nba > 0) && (startIdx > nba) ? nba : startIdx;
}
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("minLimit, maxLimit, mLimit = %d, %d, %d\n", minLimit, maxLimit, mLimit);
}
#endif
if (! checkIdentical(strsrch, mStart, mLimit)) {
found = FALSE;
}
if (found) {
break;
}
}
#ifdef USEARCH_DEBUG
if (getenv("USEARCH_DEBUG") != NULL) {
printf("Target CEs [%d .. %d]\n", ceb.firstIx, ceb.limitIx);
int32_t lastToPrint = ceb.limitIx+2;
for (int ii=ceb.firstIx; ii<lastToPrint; ii++) {
printf("%8x@%d ", ceb.get(ii)->ce, ceb.get(ii)->srcIndex);
}
printf("\n%s\n", found? "match found" : "no match");
}
#endif
// All Done. Store back the match bounds to the caller.
//
if (found==FALSE) {
mLimit = -1;
mStart = -1;
}
if (matchStart != NULL) {
*matchStart= mStart;
}
if (matchLimit != NULL) {
*matchLimit = mLimit;
}
return found;
}
// internal use methods declared in usrchimp.h -----------------------------
UBool usearch_handleNextExact(UStringSearch *strsrch, UErrorCode *status)
{
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
#if BOYER_MOORE
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t textoffset = ucol_getOffset(coleiter);
// status used in setting coleiter offset, since offset is checked in
// shiftForward before setting the coleiter offset, status never
// a failure
textoffset = shiftForward(strsrch, textoffset, UCOL_NULLORDER,
patterncelength);
while (textoffset <= textlength)
{
uint32_t patternceindex = patterncelength - 1;
int32_t targetce;
UBool found = FALSE;
int32_t lastce = UCOL_NULLORDER;
setColEIterOffset(coleiter, textoffset);
for (;;) {
// finding the last pattern ce match, imagine composite characters
// for example: search for pattern A in text \u00C0
// we'll have to skip \u0300 the grave first before we get to A
targetce = ucol_previous(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (targetce == UCOL_IGNORABLE && inNormBuf(coleiter)) {
// this is for the text \u0315\u0300 that requires
// normalization and pattern \u0300, where \u0315 is ignorable
continue;
}
if (lastce == UCOL_NULLORDER || lastce == UCOL_IGNORABLE) {
lastce = targetce;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
if (targetce == patternce[patternceindex]) {
// the first ce can be a contraction
found = TRUE;
break;
}
if (!hasExpansion(coleiter)) {
found = FALSE;
break;
}
}
//targetce = lastce;
while (found && patternceindex > 0) {
lastce = targetce;
targetce = ucol_previous(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (targetce == UCOL_IGNORABLE) {
continue;
}
patternceindex --;
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
found = found && targetce == patternce[patternceindex];
}
targetce = lastce;
if (!found) {
if (U_FAILURE(*status)) {
break;
}
textoffset = shiftForward(strsrch, textoffset, lastce,
patternceindex);
// status checked at loop.
patternceindex = patterncelength;
continue;
}
if (checkNextExactMatch(strsrch, &textoffset, status)) {
// status checked in ucol_setOffset
setColEIterOffset(coleiter, strsrch->search->matchedIndex);
return TRUE;
}
}
setMatchNotFound(strsrch);
return FALSE;
#else
int32_t textOffset = ucol_getOffset(strsrch->textIter);
int32_t start = -1;
int32_t end = -1;
if (usearch_search(strsrch, textOffset, &start, &end, status)) {
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = end - start;
return TRUE;
} else {
setMatchNotFound(strsrch);
return FALSE;
}
#endif
}
UBool usearch_handleNextCanonical(UStringSearch *strsrch, UErrorCode *status)
{
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
#if BOYER_MOORE
UCollationElements *coleiter = strsrch->textIter;
int32_t textlength = strsrch->search->textLength;
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t textoffset = ucol_getOffset(coleiter);
UBool hasPatternAccents =
strsrch->pattern.hasSuffixAccents || strsrch->pattern.hasPrefixAccents;
textoffset = shiftForward(strsrch, textoffset, UCOL_NULLORDER,
patterncelength);
strsrch->canonicalPrefixAccents[0] = 0;
strsrch->canonicalSuffixAccents[0] = 0;
while (textoffset <= textlength)
{
int32_t patternceindex = patterncelength - 1;
int32_t targetce;
UBool found = FALSE;
int32_t lastce = UCOL_NULLORDER;
setColEIterOffset(coleiter, textoffset);
for (;;) {
// finding the last pattern ce match, imagine composite characters
// for example: search for pattern A in text \u00C0
// we'll have to skip \u0300 the grave first before we get to A
targetce = ucol_previous(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (lastce == UCOL_NULLORDER || lastce == UCOL_IGNORABLE) {
lastce = targetce;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
if (targetce == patternce[patternceindex]) {
// the first ce can be a contraction
found = TRUE;
break;
}
if (!hasExpansion(coleiter)) {
found = FALSE;
break;
}
}
while (found && patternceindex > 0) {
targetce = ucol_previous(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (targetce == UCOL_IGNORABLE) {
continue;
}
patternceindex --;
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
found = found && targetce == patternce[patternceindex];
}
// initializing the rearranged accent array
if (hasPatternAccents && !found) {
strsrch->canonicalPrefixAccents[0] = 0;
strsrch->canonicalSuffixAccents[0] = 0;
if (U_FAILURE(*status)) {
break;
}
found = doNextCanonicalMatch(strsrch, textoffset, status);
}
if (!found) {
if (U_FAILURE(*status)) {
break;
}
textoffset = shiftForward(strsrch, textoffset, lastce,
patternceindex);
// status checked at loop
patternceindex = patterncelength;
continue;
}
if (checkNextCanonicalMatch(strsrch, &textoffset, status)) {
setColEIterOffset(coleiter, strsrch->search->matchedIndex);
return TRUE;
}
}
setMatchNotFound(strsrch);
return FALSE;
#else
int32_t textOffset = ucol_getOffset(strsrch->textIter);
int32_t start = -1;
int32_t end = -1;
if (usearch_search(strsrch, textOffset, &start, &end, status)) {
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = end - start;
return TRUE;
} else {
setMatchNotFound(strsrch);
return FALSE;
}
#endif
}
UBool usearch_handlePreviousExact(UStringSearch *strsrch, UErrorCode *status)
{
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
#if BOYER_MOORE
UCollationElements *coleiter = strsrch->textIter;
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t textoffset = ucol_getOffset(coleiter);
// shifting it check for setting offset
// if setOffset is called previously or there was no previous match, we
// leave the offset as it is.
if (strsrch->search->matchedIndex != USEARCH_DONE) {
textoffset = strsrch->search->matchedIndex;
}
textoffset = reverseShift(strsrch, textoffset, UCOL_NULLORDER,
patterncelength);
while (textoffset >= 0)
{
int32_t patternceindex = 1;
int32_t targetce;
UBool found = FALSE;
int32_t firstce = UCOL_NULLORDER;
// if status is a failure, ucol_setOffset does nothing
setColEIterOffset(coleiter, textoffset);
for (;;) {
// finding the first pattern ce match, imagine composite
// characters. for example: search for pattern \u0300 in text
// \u00C0, we'll have to skip A first before we get to
// \u0300 the grave accent
targetce = ucol_next(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (firstce == UCOL_NULLORDER || firstce == UCOL_IGNORABLE) {
firstce = targetce;
}
if (targetce == UCOL_IGNORABLE && strsrch->strength != UCOL_PRIMARY) {
continue;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
if (targetce == patternce[0]) {
found = TRUE;
break;
}
if (!hasExpansion(coleiter)) {
// checking for accents in composite character
found = FALSE;
break;
}
}
//targetce = firstce;
while (found && (patternceindex < patterncelength)) {
firstce = targetce;
targetce = ucol_next(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (targetce == UCOL_IGNORABLE) {
continue;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
found = found && targetce == patternce[patternceindex];
patternceindex ++;
}
targetce = firstce;
if (!found) {
if (U_FAILURE(*status)) {
break;
}
textoffset = reverseShift(strsrch, textoffset, targetce,
patternceindex);
patternceindex = 0;
continue;
}
if (checkPreviousExactMatch(strsrch, &textoffset, status)) {
setColEIterOffset(coleiter, textoffset);
return TRUE;
}
}
setMatchNotFound(strsrch);
return FALSE;
#else
int32_t textOffset;
if (strsrch->search->isOverlap) {
if (strsrch->search->matchedIndex != USEARCH_DONE) {
textOffset = strsrch->search->matchedIndex + strsrch->search->matchedLength - 1;
} else {
// move the start position at the end of possible match
initializePatternPCETable(strsrch, status);
for (int32_t nPCEs = 0; nPCEs < strsrch->pattern.PCELength - 1; nPCEs++) {
int64_t pce = ucol_nextProcessed(strsrch->textIter, NULL, NULL, status);
if (pce == UCOL_PROCESSED_NULLORDER) {
// at the end of the text
break;
}
}
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
textOffset = ucol_getOffset(strsrch->textIter);
}
} else {
textOffset = ucol_getOffset(strsrch->textIter);
}
int32_t start = -1;
int32_t end = -1;
if (usearch_searchBackwards(strsrch, textOffset, &start, &end, status)) {
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = end - start;
return TRUE;
} else {
setMatchNotFound(strsrch);
return FALSE;
}
#endif
}
UBool usearch_handlePreviousCanonical(UStringSearch *strsrch,
UErrorCode *status)
{
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
#if BOYER_MOORE
UCollationElements *coleiter = strsrch->textIter;
int32_t *patternce = strsrch->pattern.CE;
int32_t patterncelength = strsrch->pattern.CELength;
int32_t textoffset = ucol_getOffset(coleiter);
UBool hasPatternAccents =
strsrch->pattern.hasSuffixAccents || strsrch->pattern.hasPrefixAccents;
// shifting it check for setting offset
// if setOffset is called previously or there was no previous match, we
// leave the offset as it is.
if (strsrch->search->matchedIndex != USEARCH_DONE) {
textoffset = strsrch->search->matchedIndex;
}
textoffset = reverseShift(strsrch, textoffset, UCOL_NULLORDER,
patterncelength);
strsrch->canonicalPrefixAccents[0] = 0;
strsrch->canonicalSuffixAccents[0] = 0;
while (textoffset >= 0)
{
int32_t patternceindex = 1;
int32_t targetce;
UBool found = FALSE;
int32_t firstce = UCOL_NULLORDER;
setColEIterOffset(coleiter, textoffset);
for (;;) {
// finding the first pattern ce match, imagine composite
// characters. for example: search for pattern \u0300 in text
// \u00C0, we'll have to skip A first before we get to
// \u0300 the grave accent
targetce = ucol_next(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (firstce == UCOL_NULLORDER || firstce == UCOL_IGNORABLE) {
firstce = targetce;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
if (targetce == patternce[0]) {
// the first ce can be a contraction
found = TRUE;
break;
}
if (!hasExpansion(coleiter)) {
// checking for accents in composite character
found = FALSE;
break;
}
}
targetce = firstce;
while (found && patternceindex < patterncelength) {
targetce = ucol_next(coleiter, status);
if (U_FAILURE(*status) || targetce == UCOL_NULLORDER) {
found = FALSE;
break;
}
targetce = getCE(strsrch, targetce);
if (targetce == UCOL_IGNORABLE) {
continue;
}
// TODO: #if BOYER_MOORE, replace with code using 32-bit version of compareCE64s
found = found && targetce == patternce[patternceindex];
patternceindex ++;
}
// initializing the rearranged accent array
if (hasPatternAccents && !found) {
strsrch->canonicalPrefixAccents[0] = 0;
strsrch->canonicalSuffixAccents[0] = 0;
if (U_FAILURE(*status)) {
break;
}
found = doPreviousCanonicalMatch(strsrch, textoffset, status);
}
if (!found) {
if (U_FAILURE(*status)) {
break;
}
textoffset = reverseShift(strsrch, textoffset, targetce,
patternceindex);
patternceindex = 0;
continue;
}
if (checkPreviousCanonicalMatch(strsrch, &textoffset, status)) {
setColEIterOffset(coleiter, textoffset);
return TRUE;
}
}
setMatchNotFound(strsrch);
return FALSE;
#else
int32_t textOffset;
if (strsrch->search->isOverlap) {
if (strsrch->search->matchedIndex != USEARCH_DONE) {
textOffset = strsrch->search->matchedIndex + strsrch->search->matchedLength - 1;
} else {
// move the start position at the end of possible match
initializePatternPCETable(strsrch, status);
for (int32_t nPCEs = 0; nPCEs < strsrch->pattern.PCELength - 1; nPCEs++) {
int64_t pce = ucol_nextProcessed(strsrch->textIter, NULL, NULL, status);
if (pce == UCOL_PROCESSED_NULLORDER) {
// at the end of the text
break;
}
}
if (U_FAILURE(*status)) {
setMatchNotFound(strsrch);
return FALSE;
}
textOffset = ucol_getOffset(strsrch->textIter);
}
} else {
textOffset = ucol_getOffset(strsrch->textIter);
}
int32_t start = -1;
int32_t end = -1;
if (usearch_searchBackwards(strsrch, textOffset, &start, &end, status)) {
strsrch->search->matchedIndex = start;
strsrch->search->matchedLength = end - start;
return TRUE;
} else {
setMatchNotFound(strsrch);
return FALSE;
}
#endif
}
#endif /* #if !UCONFIG_NO_COLLATION */
|